DEV Community

Cover image for How to get environment variables into the browser context in Nextjs?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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;
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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>
    )
}
Enter fullscreen mode Exit fullscreen mode

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 πŸ˜ƒ.


Top comments (0)