Skip to main content


Show more

Nextjs Environment Variables

Next.js - Environment Variables

Environment variables in Next.js allow developers to configure their application behavior based on the environment in which it is running, such as development, staging, or production.

1. Setup

To use environment variables in a Next.js project, create a .env file in the root directory and define variables in the format KEY=VALUE. Access environment variables in Next.js using the process.env object.

// .env

2. Accessing Environment Variables

Environment variables defined in the .env file can be accessed in Next.js components using the process.env object.

// pages/index.js
import React from 'react';

const HomePage = () => {
    return (
            <h1>Welcome to Next.js</h1>
            <p>API URL: {process.env.NEXT_PUBLIC_API_URL}</p>

export default HomePage;

3. Environment-specific Variables

Next.js supports environment-specific variables by defining separate .env files for different environments, such as .env.development, .env.staging, and .env.production.

// .env.development

// .env.production

4. Public Environment Variables

Environment variables prefixed with NEXT_PUBLIC_ are exposed to the browser, allowing them to be accessed on the client-side.

// .env


Environment variables in Next.js provide a flexible and powerful way to configure application behavior based on the environment. By defining and accessing environment variables, developers can manage sensitive information, configure API endpoints, and customize application behavior for different environments with ease.