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

February 28, 2021 - 2 min read

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

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


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,


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(){

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 😃.