Runtime environment variables in Next.js - build reusable Docker images #87229
Replies: 1 comment 1 reply
-
|
LOL You hit on a massive pain point. The conflict between "Docker images should be immutable artifacts" and "Next.js inlines NEXT_PUBLIC_ vars at build time" is a huge struggle for teams moving to containerized setups. One pattern I've found incredibly robust for the "Build Once, Deploy Anywhere" philosophy (avoiding messy sed/replacement scripts in the entrypoint) is the Runtime Injection Strategy. Instead of relying on Next.js to inline build-time replacements, you need to do these: Keep your Docker build generic (no environment variables baked in). In your RootLayout (App Router) or _document (Pages), you read the safe public variables from process.env on the server. Inject them into a <script> tag that assigns them to a global object like window.__ENV. Use a configuration helper: it reads process.env on the server and window.__ENV on the client. There is a library called next-runtime-env that abstracts this effectively. It completely decouples the build artifact from the configuration, allowing the exact same image SHA to run in Staging and Prod just by changing the docker run -e flags (or K8s ConfigMaps). |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I felt confusion and a lack of clarity about environment variables in Next.js. The typical scenario was going through the docs, reading about
NEXT_PUBLIC_,.env.*loading order, and similar topics, but still ending up with build-time variables scattered across GitHub Actions,Dockerfile, scripts, and other places, resulting in a generally messy deployment configuration.Like an important chapter - a clear, obvious guide was missing from the docs. You can see this reflected in the popularity and number of comments on environment variable related threads in the Next.js GitHub repository.
I got fed up with it and was determined to get it straight. I invested time and effort, read everything available on managing environment variables in Next.js apps, and consolidated all of my findings into an article that provides a comprehensive overview of all viable options. Before writing it, I tested everything in practice in my own sandbox project.
Here is the link to the article:
https://nemanjamitic.com/blog/2025-12-13-nextjs-runtime-environment-variables
Give it a read and share your opinions and experiences. Is there anything I missed, or are there even better ways to manage environment variables with Next.js and Docker? I look forward to the discussion.
Beta Was this translation helpful? Give feedback.
All reactions