Part 52: Efficiently Managing Environment Variables in Next.js Applications

[Pages] Data Fetching

[Pages] Data Fetching

When developing web applications with frameworks like Next.js, configuring different environments—such as development, testing, and production—is crucial. Environment variables provide a flexible way to manage configurations without hardcoding values in your application code. In this post, we'll explore how to use environment variables in Next.js to ensure your app connects to the correct resources, like a content management system (CMS), across different environments.

Why Use Environment Variables?

Environment variables allow you to separate configuration from code. This separation makes it easier to:

  1. Switch Environments: Quickly switch between development, testing, and production configurations.

  2. Secure Sensitive Information: Keep sensitive information like API keys out of your source code.

  3. Maintain Consistency: Ensure consistent configurations across different parts of your application.

Setting Up Environment Variables in Next.js

Step 1: Create an .env File

At the root of your Next.js project, create an .env file to store default environment variables. Here's an example configuration:

# .env
CMS_URL=http://localhost:1337
REVALIDATE_SECONDS=300
  • CMS_URL: The URL of your CMS. In development, this might point to a local server.

  • REVALIDATE_SECONDS: The revalidation time for Incremental Static Regeneration (ISR), set to 300 seconds (5 minutes) by default.

Step 2: Access Environment Variables in Your Code

In your JavaScript files, you can access environment variables using process.env. Here’s how you can use CMS_URL:

// lib/products.js

import { fetchJson } from './api';

const { CMS_URL } = process.env;

export async function getProduct(id) {
  const product = await fetchJson(`${CMS_URL}/products/${id}`);
  return product;
}

Step 3: Override with .env.local

To override default settings for local development, create an .env.local file:

# .env.local
CMS_URL=http://localhost:1337
REVALIDATE_SECONDS=30

Values in .env.local will override those in .env. For example, REVALIDATE_SECONDS is set to 30 seconds for local testing.

Step 4: Use Environment Variables in Next.js Pages

Ensure your Next.js pages reference these variables:

// pages/index.js

export async function getStaticProps() {
  const products = await getProducts();
  return {
    props: { products },
    revalidate: parseInt(process.env.REVALIDATE_SECONDS),
  };
}

Note: Environment variable values are strings by default, so you need to convert them to numbers if necessary, as shown with parseInt(process.env.REVALIDATE_SECONDS).

Step 5: Version Control Best Practices

  • Check .env into Version Control: This file contains default settings that should be consistent across environments.

  • Exclude .env.local from Version Control: Local settings are specific to your machine and should not be included in production deployments.

If you use Git, add .env.local to your .gitignore file to ensure it isn’t tracked:

# .gitignore
.env.local

Benefits of Environment Variables

Using environment variables offers several benefits:

  • Flexibility: Easily switch configurations without changing the codebase.

  • Security: Keep sensitive information, like API keys, out of the code.

  • Scalability: Manage settings more effectively as your application grows.

By leveraging environment variables, you can maintain a clean, secure, and flexible codebase that adapts to different environments seamlessly. As you continue developing with Next.js, these practices will help streamline your workflow and enhance the reliability of your applications.

Last updated