Open In App

Next.js Environment Variables

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to use environment variables in Next.js. Environment variables in Next.js are a way to set configuration values that are used by your application. They can be used to store data such as the name of your company, the port your application will run on, or any other configuration values you need.

You can set environment variables in Next.js using the .env file. You have to create this file at the root of your project. You can use this file to set environment variables for your application.

Follow the below steps to add environment variables in the Next.js application:

Creating Next.js Application:

Step 1: To create a new NextJs App run the below command in your terminal:

npx create-next-app GFG

Step 2: After creating your project folder (i.e. GFG ), move to it by using the following command:

cd GFG

Project Structure: It will look like this.

Example: Add Environment Variables, for example, let’s create a new environment variable and display the value of that variable on the homepage. Create a new .env file and add the below content.

NEXT_PUBLIC_DEMO_VARIABLE=random_value

Now in your index.js file add the below content:

Javascript




// Importing the Link component
import Link from 'next/link'
 
export default function Homepage() {
    return (
        <div>
            This is the Homepage page - GeeksforGeeks
            <h2>
                Environment Variable :-
                {process.env.NEXT_PUBLIC_DEMO_VARIABLE}
             </h2>
        </div>
    )
}


Step to run the application: Now run the application with the below command:

npm run dev

Output: Here we are accessing the value of the environment variable using ‘process.env’.


Last Updated : 05 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads