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
- Create
.env
files in the root of your project for different environments. - Define environment variables in these files, using the
NEXT_PUBLIC_
prefix for client-side variables. - Access environment variables in your code using
process.env
. - Next.js will automatically load the appropriate environment variables based on the environment you’re running in.
- 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.