GOOSE_CPT
GOOSE_CPT

Reputation: 11

Add .env variables to Client Component NextJS from docker-compose.yaml

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

Answers (1)

Unsleeping
Unsleeping

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:

  • I removed all environment variables with the NEXT_PUBLIC_ prefix to prevent them from being embedded in the build during build time.
  • I prepared an exposable public runtime environment config, wrapped it in a server action (function), and gave it a clear EXPOSED_ prefix.
  • I set up a secret environment config (secretEnv) for runtime environment variables on the server.
  • I wrapped both configs in envsafe for runtime validation and type safety.
  • I cleared all unnecessary entries from .env.production / .env.development. All defaults/devDefaults were handled through envsafe.
  • For 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).
  • Any exposable env vars used on the server were duplicated in secretEnv to avoid making server action calls and directly use the server config instead.
  • In the app layout, I added a context provider where I fetch the public env config from a server action and store it in the context. I initialize the config with 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

Related Questions