How do environment variables work in Next.js?

Environment variables in Next.js are used to configure deployment-specific values.

Server, Build, and Client-side Env Vars

  • Server: Required before app/web server starts, e.g., API keys.
  • Build: For settings during the build process.
  • Client: For global client-side use. Ensure no sensitive information here.

Configuring Environment Variables

Create an .env.local file in the project’s root, listing the key-value pairs, each on a separate line:

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

Access the defined variables in the code using process.env.<VARIABLE_NAME>:

console.log(process.env.DB_HOST);

Secure sensitive information on platforms like Vercel, by using their environment variable management tools.

Establishing Default Values:

By adding defaults in the code, Next.js ensures the app doesn’t break if an environment variable is missing:

const dbHost = process.env.DB_HOST || 'localhost';

Leave a comment

Your email address will not be published. Required fields are marked *