Reputation: 11
Is there a way to add env variables to a NextJS app from docker compose, I have it working with adding the .env variable to the Dockerfile (prefixed with NEXT_PUBLIC_).
I am currently passing a server URL .env variable from the Docker-compose.yaml file and using the app router to make a call to that function which then uses that server URL to make the API call which I ideally want to make from a client component.
Upvotes: 0
Views: 117
Reputation: 578
To read environment variables at runtime, you need to fetch a public config from the server during the component's mount on the client side and store it in a context or any state manager.
You can explore this approach: https://www.vorillaz.com/nextjs-docker-env
Here’s the approach I generally use:
NEXT_PUBLIC_
prefix to prevent them from being embedded in the build during build time.EXPOSED_
prefix.secretEnv
) for runtime environment variables on the server.envsafe
for runtime validation and type safety..env.production
/ .env.development
. All defaults/devDefaults were handled through envsafe
.next.config.ts
, I kept reading directly from process.env
(otherwise, the linter would fail if I tried to read from the server-only secretEnv
).secretEnv
to avoid making server action calls and directly use the server config instead.ssrRuntimeEnv
passed from the server to avoid flickering during hydration.Ensure that you dynamically generate the config by reading the runtime environment at the moment, rather than returning the config result created during the app build.
Upvotes: 0