Repository navigation
Replies: 53 comments 86 replies
|
any update ? |
|
Guys its bothering me also, the same problem. Fighting with it for like a weak now, tried a lot of stuff. Any news how nextjs can swallow .env file and make client side env variables work? |
|
You cannot switch I guess you could expose those variables in Also, your variables won't be embedded anymore, and may or may not be correctly crawled if you have a fallback page ( |
|
Why canβt you execute a bash script to generate at run time?
β¦On Sat, Oct 24, 2020 at 5:17 AM Alexei Gaidulean ***@***.***> wrote:
@balazsorban44 <https://github.com/balazsorban44> Man thanks. I've read
your comment carefully, re-read docs and actually made it working.
// pages/_app.tsxTestAutoApp.getInitialProps = async (appContext: AppContext) => {
const appProps = await App.getInitialProps(appContext)
const {
publicRuntimeConfig: { PROJECT_API },
} = getConfig()
console.log('PROJECT_API', PROJECT_API) // Here project API is available
return { ...appProps }}
The idea is to opt-out of this
https://nextjs.org/docs/advanced-features/automatic-static-optimization
β
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#17641 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AHNS74M5QRLWOM2EAGEWWYTSMKSSDANCNFSM4SFJ2QOQ>
.
|
|
@firefart did you find out any workaround for this issue? I am also into the same phase now. |
This comment was marked as spam.
This comment was marked as spam.
|
Hi! @firefart Maybe you can use this approach, first set enviroment variable with a specific string in build time and then use an entrypoint file to replace this string with the docker enviroment variabless value. I don't know if you lose some benfits of next.js Docker file: entrypoint.sh Docker run: |
|
might be an old question but I solved this issue using Docker build arguments (ARG) When building my image When checking the image the .env.production content: This way doesn't affect static optimization and doesn't require custom config file. |
|
Have you tried using Docker BuildKit Secrets? They pretty much solve this use case, if your build system/CI can support BuildKit which is a relatively new Docker feature. Using a command like... RUN --mount=type=secret,id=env,dst=/path/to/your/next/app/.env.production.local...you can mount the env file in your Next application temporarily during the build process, then remove it later. This causes Next to compile in the |
|
My approach is to dynimc create a |
|
Here's the way i'm doing it at the moment that I'm comfortable with: @andrewmclagan pointed out that his package solves this problem in a similar manner but it seems to be directly embedding the https://github.com/andrewmclagan/react-env/ Setupyarn add @beam-australia/react-enventrypoint.sh #!/bin/sh
set -e
# Generate env for runtime use
yarn react-env --env APP_ENV
# Execute any subsequent command
exec "$@"
Dockerfile FROM node:alpine
WORKDIR /app
(...) truncated, all the other build tasks
# You can choose to put the entrypoint with yarn react-env here
# but I've chosen to use an entrypoint script instead
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
CMD ["yarn", "start"]__document.js <Head>
<script type="text/javascript" src="/__ENV.js" />
</Head>.env.staging REACT_APP_SECRET=sekretpage.js import env from '@beam-australia/react-env';
<p>{env('SECRET')}</p>Builddocker build -t next-app -f Dockerfile .UsageAt this point we have an image with no environment values in the built image. Assuming we're deploying for the staging environment, running the following will allow us to:
docker run -p 8080:3000 --env APP_ENV=staging -v $(pwd)/.env.staging:/app/.env.staging next-appAfter running the command, the
|
|
Here's another workaround to insert environment variables for runtime client-side rendering: https://github.com/sparanoid/env.sh This is simply a bash version of react-env, which does not require you to build your project inside the container. The benefit of this method can help you avoid multistage Dockerfile. You can build your Next.js project in GitHub Actions. And only # A simplified version of https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile
FROM node:16-alpine AS runner
# Install bash for env.sh
RUN apk add --no-cache bash
WORKDIR /app
# You only need to copy next.config.js if you are NOT using the default configuration
COPY next.config.js ./
COPY public ./public
COPY package.json .env env.sh ./
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY .next/standalone ./
COPY .next/static ./.next/static
EXPOSE 3000
ENV PORT 3000
RUN chmod +x ./env.sh
ENTRYPOINT ["./env.sh"]
CMD ["node", "server.js"] |
|
I'm replacing environment variables during runtime using the entrypoint technique that replaces the values (#17641 (comment)). It mostly works but I have a weird behavior. Here is what I check in a component: It logs So I checked the built file (after the value injection) to retrieve this log: Why doesn't it print out I'm suspecting static generation, but I'm not sure to understand. Can someone explain to me? |
|
This solution worked for me: https://raphaelpralat.medium.com/system-environment-variables-in-next-js-with-docker-1f0754e04cde |
|
The solid examples above are useful for getting the env variables from .env files or in the docker container.. but having trouble tackling a case where the docker container is built and deployed to ec2/fargate, and the env variables are passed into the |
|
I just deployed my next js application on my K8s server. After setting up ingress, it works fine. And now, I would like to use ConfigMap to mount the .env to redefine the env that I define when the image was being built. |
|
@vorillaz's solution seems to be working relatively well. The idea is to have the environment variables exported from server side to client side components. I made a little bit tweak on his above solution to ensure that the environment variables are initialized only once. To use the provider: You might want to do something like this in layout.tsx: On Docker / K8S side, set |
|
The solution from the following link: https://dev.to/vorillaz/nextjs-with-public-environment-variables-in-docker-4ogf worked very well for me, especially the one from the subtitle: "A More Consistent Approach." |
|
And how do you handle statics contents generated at build time ? 1/ Statics contents will be generated, for example, in a github/gitlab pipeline with test env |
|
So i am writing (on monday) after three days[Friday, Saturday & Sunday] of unsuccessful attempts. on top of the server side file where you are referencing the variables dynamically. This is the code which I made working with above. and this is the client side code which I am using to call the above and it works now in production. |
|
For those still interest, you can also use global exposed variables both to client and server components with proper validation as well. |
|
I've been following this topic for a while and I found a solution that worked for my case: This is what I have. My import { env, PublicEnvScript } from "next-runtime-env"
export default function RootLayout(){
const publicEnv = env("NEXT_PUBLIC_ENV_TEST")
return (
<html>
<head>
<PublicEnvScript />
</head>
<body>
<p>public env test: {publicEnv}</p>
</body>
</html>
)
}My # Use Docker's Node Alpine Linux image as the base Image
FROM node:alpine3.20 AS base
# Set the working directory inside the container
WORKDIR /app
# Copy `package.json` & `package-lock`.json to the root folder
COPY package*.json ./
# Install the node module dependencies
RUN npm install
# Copy everything else
COPY . .
# Build the Next.js app
RUN npm run build
# Set the environment
ENV NODE_ENV=production
# Expose the port Next.js needs
EXPOSE 3000
# Run the server!
CMD ["node", ".next/standalone/server.js"]My services:
nextjs:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- NEXT_PUBLIC_ENV_TEST="hello world"Now you only need to build the container the first time! If you change the |
|
Hi @leerob, Iβd really appreciate some guidance on what feels like a recurring pain point: handling environment variables for a Dockerized Next.js app with a single image and multiple environmentsβspecifically without relying on platforms like Vercel. The Next.js docs touch on the basics, but they donβt provide enough detail for this use case. For example:
If the image is built once and then deployed to multiple environments (e.g., staging, production), whatβs the recommended approach for injecting the correct variables at runtime? Most solutions Iβve found feel hacky or overly complex like using a script that replaces the variables, using a npm library just to use runtime environments or having to call any of the Dynamic APIs to opt in into runtime environments (exclusively for server side components). Would love to hear your thoughts on this (or see it covered in the docs more in depth). I know Iβm not alone in struggling with this. Thanks! |
|
I took a crack at using the instrumentation file to try and create a better solution for runtime env vars, but ultimately found that it doesn't really help with the core problem of how public environment variables are handled. My approach going forward is going to be to avoid using the |
|
I had to use docker |
|
I just think Vercel forces us to do these tricky stuff for such a simple feature just to get us use their platform instead of self-host. God damn using nextjs, coolify and docker was nothing but hardship! |
|
I read this and all other environment variable related discussions. For me, the solution was to remove all I started implementing it manually in my project, but after reviewing the source of this package, I realized it already handles everything well. There was no need to reinvent the wheel, so I ended up using it: https://github.com/alizeait/next-public-env Additionally, I consolidated all of my findings about managing environment variables in Next.js with Docker into a blog article: https://nemanjamitic.com/blog/2025-12-13-nextjs-runtime-environment-variables I hope it can be useful to someone by providing clarity on the subject and saving time and effort. |
|
For anyone coming here because they want one Docker image that can move from dev β staging β prod without rebuilding just to change Repo: https://github.com/RuachTech/rep Important distinction: REP does not make At runtime the gateway injects an inert JSON payload into HTML: <script id="__rep__" type="application/json">...</script>Then client code can read public runtime config synchronously: 'use client'
import { rep } from '@rep-protocol/sdk'
const apiUrl = rep.get('API_URL')
const envName = rep.get('ENV_NAME')
const flags = rep.get('FEATURE_FLAGS')The container receives those values as REP_PUBLIC_API_URL=https://api.example.com # read as rep.get('API_URL')
REP_PUBLIC_ENV_NAME=production # read as rep.get('ENV_NAME')
REP_PUBLIC_FEATURE_FLAGS=dark-mode,new-checkout # read as rep.get('FEATURE_FLAGS')Example 1: Next standalone container behind the REP gatewayThis works well with # next.config.js / next.config.mjs should use:
# output: 'standalone'
FROM node:22-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-alpine AS runner
WORKDIR /app
COPY --from=ghcr.io/ruachtech/rep/gateway:latest /usr/local/bin/rep-gateway /usr/local/bin/rep-gateway
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
EXPOSE 8080
ENTRYPOINT ["/docker-entrypoint.sh"]#!/bin/sh
set -e
NODE_ENV=production node /app/server.js &
exec /usr/local/bin/rep-gateway \
--mode proxy \
--port "${REP_GATEWAY_PORT:-8080}" \
--upstream "localhost:3000"Build once: docker build -t my-next-app:runtime-config .Run the exact same image for staging: docker run --rm -p 8080:8080 \
-e REP_PUBLIC_API_URL=https://api.staging.example.com \
-e REP_PUBLIC_ENV_NAME=staging \
-e REP_PUBLIC_FEATURE_FLAGS=dark-mode,beta-checkout \
my-next-app:runtime-configRun the exact same image for production: docker run --rm -p 8080:8080 \
-e REP_PUBLIC_API_URL=https://api.example.com \
-e REP_PUBLIC_ENV_NAME=production \
-e REP_PUBLIC_FEATURE_FLAGS=dark-mode \
my-next-app:runtime-configNo rebuild, no Example 2: static/CSR export served directly by the gatewayFor apps that are fully static or mostly CSR, the gateway can serve the built files directly: FROM node:22-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
COPY . .
RUN npm run build
FROM scratch
COPY --from=ghcr.io/ruachtech/rep/gateway:latest /usr/local/bin/rep-gateway /rep-gateway
COPY --from=builder /app/out /static
EXPOSE 8080
ENTRYPOINT ["/rep-gateway", "--mode", "embedded", "--static-dir", "/static", "--port", "8080"]docker build -t my-static-next-app:runtime-config .
docker run --rm -p 8080:8080 \
-e REP_PUBLIC_API_URL=https://api.example.com \
-e REP_PUBLIC_ENV_NAME=production \
-e REP_PUBLIC_FEATURE_FLAGS=dark-mode,new-checkout \
my-static-next-app:runtime-configA useful rule of thumb:
So this does not replace server-side secrets, and it does not change how Next.js build-time env inlining works. It gives Docker/Kubernetes deployments a runtime config layer for the values that genuinely need to be browser-readable. |
|
Not sure whether it was mentioned already, but what do you think about "abusing" the inlining limititations mentioned here?
One could probably just declare all |
|
For this use case, I would avoid trying to replace
If the goal is to build one Docker image and deploy it to dev/staging/prod with different runtime configuration, keep the environment-specific values as normal server-side environment variables and expose only the values that are intentionally public through a runtime server endpoint. For example, with the App Router: // app/api/runtime-config/route.ts
export const dynamic = 'force-dynamic';
export async function GET() {
return Response.json({
apiUrl: process.env.API_URL,
stripePublicKey: process.env.STRIPE_PUBLIC_KEY,
recaptchaSiteKey: process.env.RECAPTCHA_SITE_KEY,
});
}Then the client fetches process.env.NEXT_PUBLIC_API_URLThis gives the desired deployment model: The important point is that I would prefer this over Also, these values must be treated as public because anything returned to the browser can be inspected by the user. Secrets should never be returned from this endpoint. For applications that are completely static/client-only, a runtime-generated |

Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi,
I'm currently trying to dockerize a next.js app which will be built using github actions, the image is pushed to githubs container registry and after that it is deployed to our kubernetes cluster. We use the same image for multiple stages in our environment (dev, staging, prod) and all configuration values are passed to the docker image via secrets or env variables upon start.
Now a problem arises when using browser exposed env variables in next.js with
NEXT_PUBLIC_....(in our case needed for google recaptcha and stripe.js):It seems like all
NEXT_PUBLIC_env vars need to be defined at build time, as thenext buildcommand replaces them with the actual values in the generated JS code. But as the env keys differ for each environment (test has other public keys as prod), we can't provide them at build time to the image without having to build separate images for each env which we would like to prevent.Is there a clean way of providing these env vars at runtime instead? The docs at https://nextjs.org/docs/basic-features/environment-variables are not really helpful in this case.
Putting the
next buildstep in the entrypoint of the dockerfile so it will be executed upon start is also no option, as the build steps take a huge amount of memory.Thanks!
Dockerfile example:
All reactions