
- Next.js - Home
- Next.js - Overview
- Next.js - Project Setup
- Next.js - Folder Structure
- Next.js - App Router
- Next.js - Page Router
- Next.js Features
- Next.js - Pages
- Next.js - Data Fetching
- Next.js - ISR
- Next.js - Static File Serving
- Next.js - Pre-Rendering
- Next.js - Partial Pre Rendering
- Next.js - Server Side Rendering
- Next.js - Client Side Rendering
- Next.js Routing
- Next.js - Routing
- Next.js - Nested Routing
- Next.js - Dynamic Routing
- Next.js - Parallel Routing
- Next.js - Imperative Routing
- Next.js - Shallow Routing
- Next.js - Intercepting Routes
- Next.js - Redirecting Routes
- Next.js - Navigation and Linking
- Next.js Configuration
- Next.js - TypeScript
- Next.js - Environment Variables
- Next.js - File Conventions
- Next.js - ESLint
- Next.js API & Backend
- Next.js - API Routes
- Next.js - Dynamic API Routes
- Next.js - Route Handlers
- Next.js - API MiddleWares
- Next.js - Response Helpers
- Next.js API Reference
- Next.js - CLI Commands
- Next.js - Functions
- Next.js - Directives
- Next.js - Components
- Next.js - Image Component
- Next.js - Font Component
- Next.js - Head Component
- Next.js - Form Component
- Next.js - Link Component
- Next.js - Script Component
- Next.js Styling & SEO
- Next.js - CSS Support
- Next.js - Global CSS Support
- Next.js - Meta Data
- Next.js Advanced Topics
- Next.js - Error Handling
- Next.js - Server Actions
- Next.js - Fast Refresh
- Next.js - Internationalization
- Next.js - Authentication
- Next.js - Session Management
- Next.js - Authorization
- Next.js - Caching
- Next.js - Data Caching
- Next.js - Router Caching
- Next.js - Full Route Caching
- Next.js - Request Memoization
- Next.js Performance Optimization
- Next.js - Optimizations
- Next.js - Image Optimization
- Next.js - Lazy Loading
- Next.js - Font Optimization
- Next.js - Video Optimization
- Next.js - Script Optimization
- Next.js - Memory Optimization
- Next.js - Using OpenTelemetry
- Next.js - Package Bundling Optimization
- Next.js Testing
- Next.js - Testing
- Next.js - Testing with Jest
- Next.js - Testing with Cypress
- Next.js - Testing with Vitest
- Next.js - Testing with Playwright
- Next.js Debugging & Deployment
- Next.js - Debugging
- Next.js - Deployment
- Next.js Useful Resources
- Next.js - Interview Questions
- Next.js - Quick Guide
- Next.js - Useful Resources
- Next.js - Discussion
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.

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.
