Troubleshooting Next.js Environment Variable Issues

Updated: January 1, 2024 By: Guest Contributor Post a comment

The Problem

Environment variables play a key role in Next.js projects, providing a secure way to manage configurations for different environments like development, testing, and production. When you encounter an error stating that environment variables are undefined, it is primarily due to either not defining them properly, not loading them at the right phase of the application lifecycle, or trying to access them from a context where they’re not available.

Correct Usage Of .env Files

To start off, make sure you define your environment variables within the proper .env files in the root of your Next.js project. There are a few conventional filenames that Next.js recognizes, each for different environments: .env.local for local development, .env.development, .env.test, and .env.production for their respective environments.

Inside your chosen .env file, define your variables like so:

NEXT_PUBLIC_API_KEY=yourSecretKey
DATABASE_PASSWORD=anotherSecret

After defining these variables, you need to restart your development server to make them accessible.

Accessing Public Vs. Private Environment Variables

Next.js distinguishes between public and server-only environment variables. Variables prefixed with NEXT_PUBLIC_ are accessible both on the server and client-side, while those without the prefix are server-only. Ensure you are accessing the right type of environment variable for your use case. Client-side code should only use variables defined with the NEXT_PUBLIC_ prefix.

Loading Environment Variables In next.config.js

If you need to customize the loading of environment variables or provide defaults, modify your next.config.js file. Here’s an example:

module.exports = {
  env: {
    CUSTOM_VAR: process.env.CUSTOM_VAR || 'defaultValue',
    NEXT_PUBLIC_API_KEY: process.env.NEXT_PUBLIC_API_KEY,
  },
};

This code snippet explicitly loads environment variables and sets a default value for CUSTOM_VAR if it’s not otherwise specified.

Accessing Environment Variables in Your Application

To use your environment variables within your application, refer to them through process.env. For example:

function Page() {
  console.log(process.env.NEXT_PUBLIC_API_KEY); // safe to use, it's a public var
  console.log(process.env.DATABASE_PASSWORD); // should be used only server-side
  return (
    <div>
      Hello, check the console for the environment variables!
    </div>
  );
}

export default Page;

Remember never to directly use private environment variables in components that will be rendered on the client side, as that would expose potentially sensitive data.

Troubleshooting Common Mistakes

Even when you define and access environment variables correctly, issues can still arise. Watch out for spelling mistakes or incorrect capitalization—as environment variable names are case-sensitive. Always double-check your environment variable names for accuracy.

Keep in mind that changes to .env files won’t trigger hot reloading or recompilation. When you add new variables or change existing ones, you’ll need to stop the development server and start it again.

With these guidelines, you should be well-equipped to manage environment variables in your Next.js projects and resolve the ‘undefined’ error when it arises.