To expose or get environment variables to the browser in Nextjs, you have to prefix the environment variables name with the NEXT_PUBLIC_
string. By doing so Nextjs automatically binds the environment variables from the server context to the browser context.
# Expose environment variables to browser Nextjs
NEXT_PUBLIC_ENV_VAR_NAME=VALUE;
For example, let's say you have an environment variable called SERVER_ID
with the value of HELLO!
in the .env
file in the root of your Nextjs project folder like this,
.env file
SERVER_ID=HELLO!
Currently, this is available in the server-side (or Nodejs context) of the Nextjs project.
To expose it to the browser, we can add a prefix NEXT_PUBLIC_
to the env variable SERVER_ID
like this,
NEXT_PUBLIC_SERVER_ID=HELLO!
Now the environment variable is available in the browser context too. Magic of Nextjs! π₯³
Now to access it you can use the process.env
API just like you would normally use it in a Node.js context.
For example, to access the NEXT_PUBLIC_SERVER_ID
env in a Nextjs page called About.js
, you can use it like this,
about.js file
export default About(){
return(
<p>{process.env.NEXT_PUBLIC_SERVER_ID}</p>
)
}
That's it! π
See the above code live in Codesandbox
Top comments (0)