How to Use Environment Variables in Next.js

Reading Time: 6 min read

Introduction

Environment variables are essential for configuring applications, especially when it comes to managing sensitive data like API keys, database credentials, and other configuration settings. Next.js provides a straightforward way to use environment variables in your applications. In this post, we'll explore how to securely manage and use environment variables in Next.js.

Setting Up Environment Variables

  1. Creating Environment Files:

    Next.js supports different environment files for different stages of development. Create the following files in the root of your project:

    • .env.local – Local development
    • .env.development – Development environment
    • .env.production – Production environment

    Each file should contain key-value pairs of your environment variables.

    // .env.local
    NEXT_PUBLIC_API_URL=http://localhost:3000/api
    API_SECRET_KEY=your-secret-key
  2. Loading Environment Variables:

    Next.js automatically loads environment variables from these files and makes them available in your code. Variables prefixed with NEXT_PUBLIC_ are exposed to the browser, while others are only available on the server.

Using Environment Variables

  1. Accessing Environment Variables in Code:

    Access environment variables using process.env in your code.

    // pages/index.js
    export default function Home() {
      const apiUrl = process.env.NEXT_PUBLIC_API_URL
     
      return (
        <div>
          <h1>Environment Variables in Next.js</h1>
          <p>API URL: {apiUrl}</p>
        </div>
      )
    }
  2. Server-Side Environment Variables:

    Environment variables not prefixed with NEXT_PUBLIC_ are only available on the server. Use them in API routes or server-side functions.

    // pages/api/secret.js
    export default function handler(req, res) {
      const secretKey = process.env.API_SECRET_KEY
     
      res.status(200).json({ key: secretKey })
    }

Best Practices for Managing Environment Variables

  1. Do Not Commit Environment Files:

    Never commit .env files to version control. Use a .gitignore file to ensure they are not included.

    // .gitignore
    .env.local
    .env.development
    .env.production
  2. Use Environment Variable Management Tools:

    For larger projects, consider using environment variable management tools like dotenv, Vault, or environment variable services provided by hosting platforms (e.g., Vercel, Heroku).

    npm install dotenv
    // next.config.js
    require('dotenv').config()
     
    module.exports = {
      // Your Next.js config
    }
  3. Validate Environment Variables:

    Validate the presence and format of environment variables to avoid runtime errors.

    // utils/validateEnv.js
    export function validateEnv() {
      if (!process.env.NEXT_PUBLIC_API_URL) {
        throw new Error('Missing NEXT_PUBLIC_API_URL')
      }
      if (!process.env.API_SECRET_KEY) {
        throw new Error('Missing API_SECRET_KEY')
      }
    }
    // next.config.js
    const { validateEnv } = require('./utils/validateEnv')
    validateEnv()
     
    module.exports = {
      // Your Next.js config
    }

Example: Using Environment Variables with Fetch

Here's an example of using environment variables to fetch data from an API in a Next.js page.

// pages/index.js
import { useEffect, useState } from 'react'
 
export default function Home() {
  const [data, setData] = useState(null)
 
  useEffect(() => {
    fetch(process.env.NEXT_PUBLIC_API_URL)
      .then((response) => response.json())
      .then((data) => setData(data))
  }, [])
 
  return (
    <div>
      <h1>Data from API</h1>
      {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : <p>Loading...</p>}
    </div>
  )
}

Conclusion

Using environment variables in Next.js is straightforward and essential for managing configuration and sensitive data. By following best practices, you can ensure that your environment variables are handled securely and efficiently. Start using environment variables in your Next.js projects today to improve your development workflow and application security.

For more detailed information, visit the Next.js documentation on environment variables.

Go back Home.