Dynamic Environment Variables for Different Stages
Provide an example of dynamically setting environment variables based on different deployment stages (development, staging, production) in Next.js.
module.exports = (phase, { defaultConfig }) => {
// phase is one of the strings 'development', 'production build', or 'production',
// which allows you to customize the config per build type
// Create a map of environments to their custom variables
const envConfig = {
development: {
ENV_VAR: 'development-value',
ANOTHER_ENV_VAR: 'another-development-value',
},
staging: {
ENV_VAR: 'staging-value',
ANOTHER_ENV_VAR: 'another-staging-value',
},
production: {
ENV_VAR: 'production-value',
ANOTHER_ENV_VAR: 'another-production-value',
},
};
// Determine the current stage based on phase
const currentStage = phase === 'development' ? 'development' : (process.env.STAGE === 'staging' ? 'staging' : 'production');
// Merge environment variables with the default config
return {
...defaultConfig,
env: {
...envConfig[currentStage],
},
};
};
This piece of code is a Next.js configuration file that exports a function receiving the 'phase' and a 'defaultConfig'. Based on the phase and an optional STAGE environment variable, it dynamically sets environment variables for different deployment stages such as development, staging, and production. It defines a mapping of stages to their environment variables and then merges the stage-specific variables into the default configuration.