How to get environment variables into the browser context in Nextjs?

Published February 28, 2021

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

Check out How to create and use environment variables in Nextjs? to know more about using the same.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter