Sunrabbit

[Next.js] Runtime Environment Variable Injection

Created: 2024-03-20

Created: 2024-03-20 14:06

In Next.js, .env variables are hardcoded during the build process.


However, there are many cases where we need to set env variables not during the build process, but when running the built image.

This is usually because we need to manage environments like local, dev, qa, and prod.


So, how can we achieve this?


Most solutions are similar to the content of the article below.



However, the above article excludes Windows.

It uses Unix syntax in the package.json script.

This means that Windows users, who are clean, honest, and considerate, cannot use this script.


Therefore, considerate Windows users need to provide a script that works on both operating systems instead, in consideration of Unix users.



The solution is simple.

We just need to use a script that does the same thing as that syntax.

Install cross-env using the above command.


Then, modify the 'start' command mentioned earlier as shown below to solve the issue.

However, the script becomes too long and difficult to read. Also, we need to add it to the 'dev' command as well.

Therefore, I have organized it as shown above.

Comments0