Blog>
Snippets

Creating Environment Variables for Different Deployment Stages

Show how to configure and use environment variables in a Next.js 14 application for local, development, staging, and production environments.
// next.config.js
module.exports = {
  env: {
    CUSTOM_ENV_VARIABLE: process.env.CUSTOM_ENV_VARIABLE,
  },
};
This is a basic configuration in 'next.config.js', where you can define which environment variables to expose to the browser.
const dotenv = require('dotenv');

dotenv.config({ path: `.env.${process.env.NODE_ENV}` });

console.log('Environment:', process.env.NODE_ENV);
console.log('My Custom Variable:', process.env.CUSTOM_ENV_VARIABLE);
This code uses the 'dotenv' library to load the environment variables from a file into 'process.env'. The file is chosen based on the 'NODE_ENV' environment variable, which can be set to 'local', 'development', 'staging', or 'production'.
// package.json
{
  "scripts": {
    "dev": "NODE_ENV=development next dev",
    "build:staging": "NODE_ENV=staging next build",
    "build": "NODE_ENV=production next build",
    "start": "NODE_ENV=production next start"
  }
}
These are NPM scripts defined in the 'package.json' file that set the 'NODE_ENV' environment variable before running Next.js commands.
// .env.local
CUSTOM_ENV_VARIABLE=LocalValue
Environment-specific file '.env.local' for setting variables in a local environment.
// .env.development
CUSTOM_ENV_VARIABLE=DevelopmentValue
Environment-specific file '.env.development' for setting variables in the development environment.
// .env.staging
CUSTOM_ENV_VARIABLE=StagingValue
Environment-specific file '.env.staging' for setting variables in the staging environment.
// .env.production
CUSTOM_ENV_VARIABLE=ProductionValue
Environment-specific file '.env.production' for setting variables in the production environment.