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.