Short Answer
- Put your dev-env secrets in
.env.dev
- Put your prod-env secrets in
.env.prod
- Don't save secrets in
.env.local
. They will be brought there next.
- Add following to your
package.json
script.
"build-dev": "cp .env.dev .env.local && yarn build",
"build-prod": "cp .env.prod .env.local && yarn build"
- Upvote & Enjoy if it worked.
Additionally,
- You may want to add a variable
APP_ENV
.
- Set it to
development
and production
based on file.
- Access
process.env.APP_ENV
based on your script invocation.
Keep in mind, process.env.NODE_ENV
will always be production
in all the 3 scripts above.
And don't store your env files in standard format that nextjs's build command can detect.
Perhaps use .env.dev
, .env.stg
, .env.prod
Long Answer
Well this is Mid-2023 and I wish there was a straightforward solution. Here's what works for me coming from React/vite to Nextjs with 2 different environments file.
Using Rodrigo's answer I first renamed
.env.development
to .env.dev
.env.production
to .env.prod
so that next.js doesn't pick them automatically during builds but they stay on local system.
If I don't do that then precedence kicks in and picks .env.production
during deployment to my dev
environment which I don't want.
Next I modified my scripts in package.json as
"build":"yarn build"
"predeploy": "cp .env.dev .env.local",
"deploy": "firebase use development && firebase hosting:channel:deploy dev",
"predeployprod": "cp .env.prod .env.local",
"deployprod": "firebase use production && firebase deploy -P production"
Read about Next JS Precedence Order briefly.
What this does is based on my "invocation" whether I want to deploy to dev/prod env it supplies the right secrets to the .env.local
file.
For example, Say I want to deploy to dev.
I run yarn deploy
-> automatically runs yarn predeploy
first setting my dev-secrets to .env.local
. Secondly it runs the build.
You might wonder where's nextjs's build command?
firebase deploy
takes care of that and runs it behind the scene.
If you aren't using firebase following could suffice.
"build-dev": "cp .env.dev .env.local && yarn build",
"build-prod": "cp .env.prod .env.local && yarn build"