I've built a nextjs app with a basic .env file and it seems the variables get injected into the build files. Despite the fact that I'm reading from process.env.
Eg.
const sample = process.env.SAMPLE;
export default async function Home() {
return (
<div>
...
Sample text: {sample}
...
</div>
}
It displays the text that is in the .env file for the variable SAMPLE after I build the image in a docker container and inject a different value for SAMPLE
. This confuses me because the documentation here and even in a github issue answer for the same issue it explicitly states: "Next.js can support both build time and runtime environment variables." and then "To read runtime environment variables, we recommend using getServerSideProps or incrementally adopting the App Router." without providing any examples. It just vaguely says that nextjs supports it without much detail.
To clarify, I'm not trying to expose variables directly to the client using the NEXT_PUBLIC
prefix. I just want specific parts of the code to be able to have values injected at runtime. Is there something I'm missing? Can it only read the env variables at runtime through the api routes or something?
Yes, that is what they mean. With dynamic rendering, routes are rendered for each user at request time.
getServerSideProps
from the Page router, is a function that can fetch server data and render the page at request time.
Similarly, in the App router, one can use different ways to ensure that the page is not cached and instead is dynamically created at every render. One way was to use no_store
(now deprecated). no_store
was used to opt out of static rendering and hence every request would recompute values including environment variables.
For the newer App router, there are different data fetching mechanisms. You can use Server Actions to fetch data for the component when you request for it, and then get the updated environment variable value.