Why Can’t I access my .env files in Next js?

Accessing .env files in NextJS can be challenging, especially for those from a traditional react background. This article aims to help avoid common mistakes and provide guidance on how to navigate these files effectively.
Adding secrets in our environmental variable files is a crucial way to protect those secrets without exposing it to the public.
If you are using Next Js, you are likely to have issues accessing those secret keys in your browser if you store them in this pattern:
DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword
//accessing the .env
const user = process.env.DB_USER
This loads process.env.DB_HOST
, process.env.DB_USER
, and process.env.DB_PASS
into the Node.js environment (only) automatically allowing you to use them in Next.js data fetching methods and API routes.
But note that the method above loads the secrets into the node.js environment only. You cannot access it in your browser because Next Js has some other way to do that.
What is the right method?
In Next.js, to make environment variables accessible in the browser, use “NEXT_PUBLIC_” prefix. This tells Next.js to “hide” the value in the code during build, keeping it secure yet functional. So, “process.env.NEXT_PUBLIC_[variable]” becomes a secret code in your website’s code.
NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
// acessing the .env
const ID = process.env.NEXT_PUBLIC_ANALYTICS_ID
Next.js is smart about keeping secrets. When you add “NEXT_PUBLIC_” to an environment variable’s name, it knows to hide the value in the code during the build. This way, your secret code (like an analytics ID) stays secure but still works in your website. So, “process.env.NEXT_PUBLIC_ANALYTICS_ID” becomes a hidden message that only your website understands.
Now you don’t have problem accessing your .env files, you can read the full documentation on Next Js docs.
Encourage me to write more by Engaging and sharing this content to other developers….
Follow me on LinkedIn and X (Twitter ), i also post amazing stuffs there..