Loading...

How to set environment variable in a Nextjs App and when to use NEXT_PUBLIC prefix?

question nextjs react
Ram Patra Published on July 11, 2024
Tested on Next.js 14

Setting environment variables in a Next.js app is straightforward. Next.js supports loading environment variables from .env files. Here’s a step-by-step guide on how to set and use environment variables in your Next.js application:

Step 1: Create Environment Files

Create environment files in the root directory of your project. Commonly used files include:

  • .env.local (for local development)
  • .env.development (for development environment)
  • .env.production (for production environment)

Remember to not commit these files to your version control as these may contain sensitive information like api key, etc. Instead, every cloud provider has a way to set environment variables, either via their UI or CLI.

Step 2: Define Environment Variables

Add your environment variables to these files. Use the NEXT_PUBLIC_ prefix for variables that need to be exposed to the client-side.

Example .env.local:

# Server-side only
DATABASE_URL=your-database-url
SECRET_KEY=your-secret-key

# Client-side
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_FEATURE_FLAG=true

Step 3: Access Environment Variables in Code

Server-Side Code

In server-side code, such as API routes or within server components, you can access environment variables directly using process.env.

Example server-side usage:

// app/api/example/route.ts

import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
    const secretKey = process.env.SECRET_KEY;
    return NextResponse.json({ message: 'Success', secretKey });
}

Server Components

In server components, you can directly access environment variables.

Example server component usage:

// app/page.tsx

export default function Home() {
    const databaseUrl = process.env.DATABASE_URL;
    return <div>Database URL: {databaseUrl}</div>;
}

Client-Side Code

In client components, you can access the environment variables that are prefixed with NEXT_PUBLIC_.

Example client component usage:

// app/components/ExampleComponent.tsx

'use client';

import React from 'react';

const ExampleComponent = () => {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL;
    const featureFlag = process.env.NEXT_PUBLIC_FEATURE_FLAG === 'true';

    return (
        <div>
            <p>API URL: {apiUrl}</p>
            {featureFlag && <p>Feature is enabled!</p>}
        </div>
    );
};

export default ExampleComponent;

Step 4: Using Different Environment Variables for Different Environments

Next.js will automatically load environment variables based on the environment. For example, if you run next build and next start, it will use variables from .env.production. If you run next dev, it will use variables from .env.development.

Step 5: Built-in Environment Variable Support

Next.js 14 loads environment variables defined in .env.* files automatically during build time and runtime.

Step 6: Validate Environment Variables (Optional)

In Next.js 14, you can validate environment variables to ensure all necessary variables are set and have valid values.

Example validation using next.config.js:

// next.config.js

module.exports = {
    env: {
        DATABASE_URL: process.env.DATABASE_URL,
        SECRET_KEY: process.env.SECRET_KEY,
        NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
        NEXT_PUBLIC_FEATURE_FLAG: process.env.NEXT_PUBLIC_FEATURE_FLAG
    },
    // Add other configurations here
};

Summary

  1. Create .env files in the root of your project for different environments.
  2. Define environment variables in these files, using the NEXT_PUBLIC_ prefix for client-side variables.
  3. Access environment variables in your code using process.env.
  4. Next.js will automatically load the appropriate environment variables based on the environment you’re running in.
  5. Validate environment variables (optional) using next.config.js.

Example .env Files

.env.local:

# Server-side only
DATABASE_URL=your-local-database-url
SECRET_KEY=your-local-secret-key

# Client-side
NEXT_PUBLIC_API_URL=http://localhost:3000/api
NEXT_PUBLIC_FEATURE_FLAG=true

.env.development:

# Server-side only
DATABASE_URL=your-dev-database-url
SECRET_KEY=your-dev-secret-key

# Client-side
NEXT_PUBLIC_API_URL=https://dev-api.example.com
NEXT_PUBLIC_FEATURE_FLAG=false

.env.production:

# Server-side only
DATABASE_URL=your-prod-database-url
SECRET_KEY=your-prod-secret-key

# Client-side
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_FEATURE_FLAG=true

By following these steps, you can effectively manage environment variables in your Next.js 14 application with the App Router.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on July 11, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question nextjs front-end November 12, 2024 How to define schemas, foreign keys, relations, and query data by performing joins in a Nextjs app using Supabase and Drizzle?

Drizzle is an ORM that makes it easy to work with db, data migrations, etc. Here’s how you can define foreign keys, relations, and perform table joins using Drizzle ORM in a Next.js app with Supabase:

question nextjs react July 9, 2024 How to create custom types in Typescript in a Next.js app?

Declaring custom types in TypeScript for a Next.js application involves creating type definitions that can be used across your project to ensure type safety and better code management. Here are the steps to declare and use custom types in a Next.js app:

question nextjs react November 17, 2024 How to define metadata in a client component in Nextjs?

Nextjs does not allow defining the metadata object in client components. There are a couple of ways to resolve this problem. I will be talking about two of them here.