How to use diferent .env files with nextjs?
Next 9.4 has built-in support for .env files: https://nextjs.org/docs/basic-features/environment-variables
But, in case you want to have multiple .env files, like:
- .env.development
- .env.staging
- .env.prestaging
- .env.production
It would be impossible to do with a built-in env variables support. There's only 3 environments that officially supported for now, it's: "development", "test", "production". With next dev
you use "development", next build && next start
uses "production" environment.
If you need to build for production environment, but using ".env.staging" for example, then you need to add env-cmd package, and add this line to your package.json:
"build:staging": "env-cmd -f .env.staging yarn build && yarn start"
Next would make a production build with ".env.staging" variables.
npm i dotenv
Then add below code to next.config.js
, restart the application and you are good to go!
// next.config.js
require('dotenv').config()
const webpack = require('webpack')
module.exports = {
webpack: (config) => {
config.plugins.push(
new webpack.EnvironmentPlugin(process.env)
)
return config
}
}
If your .env file is not located in same folder as next.config.js
add path to your config like below,
require('dotenv').config({ path: 'path/to/.env' })
You can have different .env files in nextjs with following two ways:
1. Using env-cmd package
Provide the path to your environment file in the scripts like:
"scripts": {
"start": "env-cmd path/to/prod/env/file next start",
"start:dev": "env-cmd path/to/prod/env/file next dev",
"build:dev": "env-cmd path/to/dev/env/file next build",
"build:test": "env-cmd path/to/test/env/file next build",
"build:stage": "env-cmd path/to/stage/env/file next build",
"build": "env-cmd path/to/stage/prod/file next build",
},
2. Using dotenv package
In your next.config.js file add following:
require("dotenv").config({ path: `${process.env.ENVIRONMENT}` });
module.exports = {
// your configs
}
and in your scripts, provide that ENVIRONMENT variable like:
"scripts": {
"start": "ENVIRONMENT=path/to/prod/env/file next start",
"start:dev": "ENVIRONMENT=path/to/dev/env/file next dev",
"build:dev": "ENVIRONMENT=path/to/dev/env/file next build",
"build:test": "ENVIRONMENT=path/to/test/env/file next build",
"build:stage": "ENVIRONMENT=path/to/stage/env/file next build",
"build": "ENVIRONMENT=path/to/stage/prod/file next build",
},
NOTE: The thing is do not to put your .env* files in the root folder, otherwise NEXT will auto-pick from your .evn* files and it only supports production and development stages. So it'll ignore other .env.my-stage files.