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

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

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 04/17/2024 at 09:20
Last Updated on 04/17/2024 at 09:51
<p>A flower that represents NextJS with the text "Create and Use Environment Variables in a .env file” beneath it.</p>

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

SubscribeDownload Open Source Project

Step One: Create the .env file

<p>A screenshot of VSCode showing a newly created .env file.</p>

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

Step Two: Define the Environment Variables

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

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.

NextJS: Environment Variables

Step Three: Use the Environment Variables

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

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

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

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

How to deploy a NextJS project 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.

Search our Blog

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe