'Next.js env file depending deployment stage

Let's say I am deploying Next.js in different env, for example.

  1. local development
  2. staging deployment
  3. production deployment

Previously I hand used .env file with one of the framework where I could easily name the file like .env.local, .env.stage & .env.prod and when I run node app locally it would load .env.local, with export STAGE=stageframework would use.env.stage`, like wise fro productoin.

Is that such support in Next js where I can have different .env file for different stage. If it is supported then how would I specify which stage Next.js is running.



Solution 1:[1]

You can have different environments, just need to follow this

For production

// .env.production.local
// This file is for production and run with next start or npm run start
// NODE_ENV=production

For development

// .env.development.local
// This file is for development and run when next dev or npm run dev
// NODE_ENV=development

For tests

// .env.test.local
// This file is for tests with jest or cypress for example
// NODE_ENV=test

If you want know more about this, here is the complete info about environments in next js

Update:

If you want to run more environments without next standard, you can do this manually:

// package.json
"scripts": {
  ...
  "dev:staging": "APP_ENV=staging next dev",
}
...


// next.config.js
require('dotenv-flow').config({
  node_env: process.env.APP_ENV || process.env.NODE_ENV || 
   'development',
});

const env = {};
Object.keys(process.env).forEach((key) => {
  if (key.startsWith('NEXT_PUBLIC_')) {
    env[key] = process.env[key];
  }
});

module.exports = {
  env,
};

And when you run npm run/yarn dev:staging your staging environment from .env.staging.local will be loaded, my reference is from flybayer and you can read more here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1