Docs: Environment variables documentation implies they're always read at build time
See original GitHub issueWhat is the improvement or update you wish to see?
https://nextjs.org/docs/basic-features/environment-variables#loading-environment-variables
Note: In order to keep server-only secrets safe, environment variables are evaluated at build time, so only environment variables actually used will be included. This means that process.env is not a standard JavaScript object, so you’re not able to use object destructuring. Environment variables must be referenced as e.g. process.env.PUBLISHABLE_KEY, not const { PUBLISHABLE_KEY } = process.env.
The above mislead me (into using the legacy serverRuntimeConfig
/ publicRuntimeConfig
) as it says environment variables are evaluated at build time which, from my tests and speaking to users on Discord, isn’t the case if you’re reading them in API Routes or getServerSideProps
.
As I understand it, process.env.*
works just like any old regular node server does and will read from the global.process.env.*
object at the time the code is executed; so for getServerSideProps
or API Routes that’s runtime and for getStaticProps
that’s presumably build time?
It’s my understanding, the only time next.js will do something fancy with env vars is when code references process.env.NEXT_PUBLIC_*
as they’ll be inlined into the client bundle at build time? (I guess it also replaces process.env.*
with undefined).
Additionally, I’ve found that destructuring works fine even for vars which are inlined, e.g. const { NEXT_PUBLIC_FOO } = process.env
?
Is there any context that might help us understand?
I needed runtime environment variables as our current pipeline builds just a single artefact designed to be deployed to multiple environments.
Does the docs page already exist? Please link to it.
https://nextjs.org/docs/basic-features/environment-variables#loading-environment-variables
Issue Analytics
- State:
- Created a year ago
- Reactions:7
- Comments:7 (2 by maintainers)
Top GitHub Comments
We have the same problem, we needed runtime environment variables as our current pipeline builds just a single artefact designed to be deployed to multiple environments.
We used publicRuntimeConfig, but now it’s doesn’t work as expected with Output File Tracing because
Note: next.config.js is read during next build and serialized into the server.js output file. If the legacy [serverRuntimeConfig or publicRuntimeConfig options](https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration) are being used, the values will be specific to values at build time.
Also finding this confusing. For instance, I should be able to mount a secret file as .env.local in my dockerfile at runtime to specify server configurations that are different in production and staging. The documentation leads me to think that isn’t possible.