I have a NextJS "^11.1.2" app, which gets build in a Dockerfile and deployed to production via CI/CD. But my process.env variables are not rendered
I have this in my client side code, which should be rendered at runtime:
const PublicApiUrl = process.env.NEXT_PUBLIC_API_URL;
In my (Gitlab) CI/CD Pipeline I added via AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS some --build-args, as well ENV and ARG:
AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS --build-arg=NEXT_PUBLIC_API_URL=https://my.api.com --build-arg=NEXT_PUBLIC_API_URL=https://my.api.com --build-arg=NEXT_PUBLIC_BUILDER_KEY=XXXXXX
NEXT_PUBLIC_API_URL=https://my.api.com
API_URL=https://my.api.com
Dockerfile
ARG API_URL
ENV API_URL=$API_URL
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ARG NEXT_PUBLIC_BUILDER_KEY
ENV NEXT_PUBLIC_BUILDER_KEY=$NEXT_PUBLIC_BUILDER_KEY
RUN npm run build # which resolves in "build": "next build"
This values below are definitely picked up (I did a RUN env and can see the variables are there).
This is my configMap at Kubernetes which mounts the .env.local file into the container:
apiVersion: v1
kind: ConfigMap
metadata:
name: frontend-env-local
annotations:
"helm.sh/resource-policy": keep
data:
.env: |-
NEXT_PUBLIC_API_URL=https://my.api.url
API_URL=https://my.api.url
This is my deployment which mounts the configMap into the container as .env.local:
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
labels:
app: frontend
spec:
replicas: 1
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
volumes:
- configMap:
defaultMode: 420
items:
- key: .env
path: .env.local
name: frontend-env-local
name: frontend-env-local
imagePullSecrets:
- name: gitlab-credentials
containers:
- name: frontend
image: "registry.gitlab.com/myapp:latest"
imagePullPolicy: Always
ports:
- name: http
containerPort: 5000
protocol: TCP
volumeMounts:
- mountPath: /app/.env.local
name: frontend-env-local
readOnly: true
subPath: .env.local
When I locally build next build it works and my variable is rendered.
But when I push, build and deploy it and run the app, its an empty string:
const PublicApiUrl = "";
Why is the variable not recognized by NextJS?
I logged into production (Kubernetes pod) terminal and run env. The variables are present too.