Skip to content
Related Articles

Related Articles

Next.js Environment Variables

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 08 Oct, 2021

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:

cd GFG

Project Structure: It will look like this.

project structure

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:

  • .env
  • .env.[environment]
  • .env.[environment].local
  • .env.development
  • .env.development.local

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.

Filename: pages/index.js


export const getServerSideProps = async () => {
  return {
    props: {
      // Returning value of Environment
      // variable as prop
      value: process.env.KEY,
      id: process.env.ID,
export default function Home({ value, id }) {
  return (
      {/* Adding Heading */}
      <h1>This is Homepage</h1>
      {/* Adding the value of Environment variable */}
      <h2>Value of KEY variable:- {value}</h2>
      <h2>Value of ID variable:- {id}</h2>

Step 5: Run the application – Run the following command to start the server.

npm start

Output: We will see the following output on your browser screen.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!