Next.js - Environment Variables



Environment Variables

The environment variables are key value pairs that store configuration data of application. It is generally used to store sensitive information like API keys, database connection strings, and other secrets. Next.js have built-in support for loading environment variables from the .env file to process.env object.

Example

For example, you can create a .env file in the root directory of your project and add API keys like this:

// File: /.env

API_KEY=djcjcwj-wcdkjcnw

Next.js will automatically load the API key defined in this file and make it available in the process.env object. You can access the API key using the following code:

console.log(process.env.API_KEY)

Loading Environment Variables

Next.js will automatically load environment variables from the following files:

  • .env: This is a common file used to store environment variables that are specific to your project.
  • .env.local: This file is used to store sensitive information like API keys. This file have highest priority and will override the values (ie, API keys) defined in the other .env files. It should never be committed to git and must be added to .gitignore file.
  • .env.development: This file is used to store environment variables that are specific to your development environment.
  • .env.production: This file is used to store environment variables that are specific to your production environment.

Accessing Environment Variables on Server-Side

To access environment variables on server-side, you can use the process.env object.

Example

In the code below, we defined a authentication middleware that checks if the request contains a valid API key. The API key is defined in the .env.local file.

// File: /middlewares/authMiddleware.js

export default function authMiddleware(handler) {
    return (req, res) => {
      const headerApiKey = req.headers.apikey;
      const queryApiKey = req.query.apiKey;

      // Check if API key is present in header or query
      if ( (!headerApiKey && !queryApiKey) || 
             (headerApiKey !== process.env.API_KEY && 
             queryApiKey !== process.env.API_KEY) ) {
        return res.status(401).json({ message: 'Unauthorized' });
      }
      return handler(req, res);
    };
}

Usage

Now, let's use the authentication middleware in an API route. Create a file named 'hello.js' inside the 'pages/api' directory with the following code:

// File: pages/api/hello.js

import authMiddleware from '../../middlewares/authMiddleware';

export default authMiddleware(function handler(req, res) {
    res.status(200).json({ message: 'Hello, Next.js API!' });
});

Output

We have added an API key "djcjcwj-wcdkjcnw" to '.env.local' file in root folder. Now, if we visit the URL '/api/hello', an unauthorized response will be returned. But when we visited '/api/hello?apiKey=djcjcwj-wcdkjcnw', the API key is validated and the proper response is returned.

Next.js API Middleware

Accessing Environment Variables on Client-Side

For security reasons, only environment variables prefixed with NEXT_PUBLIC_ are exposed at client-side. So a general purpose environment variable such as analytics ID can be accessed at client-side using the prefix.

// File: /.env.local
API_KEY=djcjcwj-wcdkjcnw
NEXT_PUBLIC_ANALYTICS_ID=123


// File: /pages/index.tsx

"use client" 
export default function Home() {
    return (
        <div>
            <h1>Hello World</h1>
            <p>
             API Key: {process.env.API_KEY}
            </p>
            <p>  
             Analytics ID: {process.env.NEXT_PUBLIC_ANALYTICS_ID}
            </p>
        </div>
    );
}

Output

In the output below, we can see that API key is not visible at client-side as it is not publicly exposed. But the analytics ID is visible as it is publicly exposed.

Next.js Environment Variables Client-Side
Advertisements