Next.js Environment Variables
In this article, we will learn how we can use environment variables in Next.js. Next.js comes with built-in support for environment variables that you can declare and use anywhere in your project.
Follow the below steps to set up the environment variable in Next.js application.
Step 1: To create a new Next.js 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:
Project Structure: It will look like this.
Step 3: Creating .env.local file – We will create a .env.local file to create environment variables that are specific to our local machine. There are also other environment variables file type that you can use like:
After creating the file, we can store our environment variables on them.
Example: We can have .env.local file with the following data.
Step 4: Accessing Environment Variables – Now you can access your environment variable using ‘process.env.VARIABLE_NAME’. To try this, let’s access our environment variable from the Homepage of a NextJs app.
Step 5: Run the application – Run the following command to start the server.
Output: We will see the following output on your browser screen.