How to create and use environment variables in an .env file in NextJS

Oscar de la Hera Gomez
A flower that represents NextJS with the text "Create and Use Environment Variables in a .env file” beneath it.

A step by step guide on creating a .env file, defining environment variables and using them in a NextJS project.

Step One: Create the .env file

A screenshot of VSCode showing a newly created .env file.

At the root of the project, create a new file called .env.

Step Two: Define the Environment Variables

A screenshot of VSCode .env file with a "SAMPLE_VARIABLE" environment variable. The variable is defined to equal "Hello World."

In NextJS, environment variables can be called whatever you like.

Please note that if you wish for the environment variable to be available in the client you must use NEXT_PUBLIC_ prefix.

Step Three: Use the Environment Variables

A screenshot of VSCode showing how we used the environment variable through process.env.SAMPLE_VARIABLE.

Within your project you can use environment variables through the syntax process.env.VARIABLE_NAME.

In the example above, we used process.env.SAMPLE_VARIABLE as that was the variable that we defined in Step Two.

Step Four: Run

A screenshot of the NextJS app showing "Hello World" in the location where we used the environment variable.

Confirm that everything works as expected by running the project locally and deploying the change to Vercel.

Looking to learn more about NextJS, ReactJS or web development?

Search our blog to find educational content on NextJS, ReactJS and web development.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details