Next.js Discord

Discord Forum

How to set environment variables when the app starts?

Unanswered
Rusty Blackbird posted this in #help-forum
Open in Discord
Rusty BlackbirdOP
In a production environment, how can I set environment variables when the application starts and then read them on the page?

2 Replies

Arboreal ant
Not sure what you mean
Roseate Spoonbill
@Rusty Blackbird Next (and in fact React in most setups as well) buillds many variables into the project during build step. Not only that, the logic around them is being simplified during build - ifs and ternary operators may even be removed if next compiler deduces, that certain path will not be taken, because e.g. some variable is missing. This means, that once built, you cannot really change classical NEXT_PUBLIC_* variables e.g. when docker container starts with your project. I had this issue many times when dealing with projects that after build are launched in multiple environments.

Normally you'd have to rebuild the project to re-inject the client-side variables. Ofc that is not the best solution for many reasons in dynamic setups. The best way around it is to use dedicated package like https://www.npmjs.com/package/next-runtime-env.

You can also write your own solution that works this way. Something that collects certain environment variables on the server and injects them into the client-side (with dedicated store, window object, or context). You'd have to probably go for SSR instead of Static Generation (in case you use it), but with proper data caching you'd hardly notice performance impact.