How to create and use environment variables in Nextjs?

February 23, 2021 - 2 min read

Creating an environment variable in Nextjs

To create environment variables in Nextjs, you need to make a .env file in the root of your Next.js project folder.

For example, let's say I want to make an environment variable called SERVER_ID with a value of HELLOWORLD123.

So to do that you need to create a .env at the root of the Nextjs project and put the key and value separated by an equal sign (=).

It will look like this,

  • ENVIRONEMNT_VARIABLE=VALUE

So from our example, the .env file will look like this,

.env file

SERVER_ID=HELLOWORLD123;

Using an environment variable in Nextjs

After we have successfully defined our environment variables in the .env file, we can use the environment variable by calling the process.env inbuilt API and then using the dot operator (.) followed by the environment variable name.

So in our case, to call the SERVER_ID environment variable, we can use it like this,

const serverId = process.env.SERVER_ID;

console.log(serverID); // HELLOWORLD123

See a working demo of the above code in Codesandbox.

NOTE: This will work only in a Nodejs environment (or a Nodejs context), so talking from the context of Nextjs this will work on server-side parts including thegetStaticProps, getStaticPathsandgetServerSideProps functions, and all other parts that are not related to browsers. We will talk about using environment variables in the browser in an upcoming blog post.

Feel free to share if you found this useful 😃.