codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

42 / 73 topics
41Environment Variables42Using .env Files43Secrets Management
Tutorials/Next.js/Using .env Files
▲Next.js

Using .env Files

Updated 2026-04-20
3 min read

Introduction

In modern web development, managing environment-specific configurations is crucial for maintaining a clean and secure codebase. Next.js provides an elegant solution through the use of .env files, which allow you to define environment variables that can be accessed throughout your application. This tutorial will guide you through setting up and using .env files in a Next.js project.

What are .env Files?

.env files are plain text files used to store environment-specific configuration settings such as API keys, database URLs, or any other sensitive information that should not be hard-coded into your source code. By using these files, you can easily switch between different environments (development, staging, production) without changing your codebase.

Setting Up .env Files in Next.js

Next.js automatically loads environment variables from .env files located at the root of your project. There are three types of .env files that Next.js recognizes:

  1. .env.local: Loaded only during development and ignored by Git.
  2. .env.development: Loaded during development but not in production.
  3. .env.production: Loaded during production but not in development.

Creating .env Files

To start using .env files, create the appropriate file(s) at the root of your Next.js project:

touch .env.local
touch .env.development
touch .env.production

Adding Environment Variables

Add your environment variables to these files in the format KEY=VALUE. For example:

.env.local

NEXT_PUBLIC_API_URL=http://localhost:3000/api
DATABASE_URL=mongodb://localhost:27017/mydatabase

.env.development

NEXT_PUBLIC_API_URL=http://dev.example.com/api
DATABASE_URL=mongodb://dev.example.com:27017/mydatabase

.env.production

NEXT_PUBLIC_API_URL=https://example.com/api
DATABASE_URL=mongodb://prod.example.com:27017/mydatabase

Accessing Environment Variables

Next.js exposes environment variables to your application through the process.env object. However, there are some important rules to follow:

  • Public Variables: To make an environment variable accessible on the client-side (e.g., in browser JavaScript), prefix it with NEXT_PUBLIC_. For example, NEXT_PUBLIC_API_URL can be accessed as process.env.NEXT_PUBLIC_API_URL both on the server and the client.

  • Server-Side Only Variables: Without the NEXT_PUBLIC_ prefix, environment variables are only accessible on the server-side. This is crucial for keeping sensitive information secure.

Example Usage

Here’s how you can use these environment variables in your Next.js application:

pages/index.js

import { useEffect } from 'react';

export default function Home() {
  useEffect(() => {
    // Accessing a public environment variable on the client-side
    const apiUrl = process.env.NEXT_PUBLIC_API_URL;
    console.log('API URL:', apiUrl);

    // Accessing a server-side only environment variable
    const databaseUrl = process.env.DATABASE_URL;
    console.log('Database URL:', databaseUrl);
  }, []);

  return <div>Welcome to Next.js!</div>;
}

Best Practices

  1. Security: Always keep your .env files out of version control by adding them to your .gitignore. This prevents sensitive information from being exposed in public repositories.

  2. Naming Conventions: Use clear and descriptive names for your environment variables. For example, API_KEY, DATABASE_URL, or NEXT_PUBLIC_GOOGLE_MAPS_API.

  3. Validation: Validate environment variables at runtime to ensure they are correctly set before using them. This can help prevent runtime errors due to missing or incorrect configurations.

  4. Environment-Specific Files: Use separate .env files for different environments to keep your configuration organized and avoid conflicts.

  5. Documentation: Document your environment variables and their purposes. This helps new team members understand the project setup and reduces the risk of misconfigurations.

Advanced Usage

Dynamic Environment Variables

Next.js also supports dynamic environment variables, which can be set at runtime using the NEXT_PUBLIC_ prefix. However, this is generally not recommended for sensitive information due to security concerns.

Example:

export default function Home() {
  const customEnvVar = process.env.NEXT_PUBLIC_CUSTOM_VAR;
  return <div>Custom Env Var: {customEnvVar}</div>;
}

Using Environment Variables in API Routes

Environment variables can also be used within Next.js API routes:

pages/api/example.js

export default function handler(req, res) {
  const apiUrl = process.env.NEXT_PUBLIC_API_URL;
  res.status(200).json({ message: `API URL is ${apiUrl}` });
}

Conclusion

Using .env files in Next.js provides a powerful and flexible way to manage environment-specific configurations. By following the guidelines outlined in this tutorial, you can ensure that your application remains secure, maintainable, and easy to deploy across different environments. Remember to keep sensitive information out of version control and validate your environment variables to prevent runtime errors. Happy coding!


PreviousEnvironment VariablesNext Secrets Management

Recommended Gear

Environment VariablesSecrets Management