![translation](https://cdn.durumis.com/common/trans.png)
This is an AI translated post.
[Next.js] Runtime env injection
- Writing language: Korean
- •
-
Base country: All countries
- •
- Information Technology
Select Language
Summarized by durumis AI
- In Next.js, .env is set at build time, but there are cases where environment variables need to be set according to the operating environment (local, dev, qa, prod) after the build.
- Windows users cannot use existing Unix-based scripts, so they need to install cross-env to write scripts that work on both Windows and Unix environments.
- Cross-env was applied to the start and dev commands to set environment variables and the script was simplified to improve readability.
In Next.js, .env is hardcoded during the build time.
However, there are many needs to set env when running the built image, not during build time.
This is usually because we handle them as local, dev, qa, prod.
So how can we achieve that?
Most of the context is similar to the article below.
However, the article above rejects Windows.
It can be seen that the Unix grammar is included in the script of package.json.
This means that Windows users who do not use dirty Unix, are clean, honest, and full of consideration, cannot use the script above.
Therefore, clean and considerate Windows users need to consider Unix users and put a script that runs properly on both operating systems instead.
The solution is simple.
Just put a script that does the same thing as the grammar.
Install cross-env with the command above.
And the start command mentioned above is solved by modifying it as follows.
However, the script is too long to read, and it needs to be added to the dev command.
{
"dev": "npm run _env:-local && next dev",
"dev:dev": "npm run _env:dev && next dev",
"start": "npm run _env:-local && next start",
"_env:-local": "cross-env-shell node ./utils/cli.js next-env -e $APP_ENV",
"_env:dev": "node ./utils/cli.js next-env -e dev"
Therefore, I organized it as above.