I've been reading other questions about getting K8s environment variables to work in a Next.js app, but no accepted answer till now.
My app works fine using .env.local but it's getting an error (undefined) when deployed to K8s.
This is my next.config.js
module.exports = {
env: {
NEXT_PUBLIC_API_BASE_URL: process.env.NEXT_PUBLIC_API_BASE_URL,
},
};
K8s environment:

Can anyone help me to get that environment var works on my next.js app?
Right now I do a simple trick, that is added ARG and ENV on dockerfile, then inject it when I build the docker image
Dockerfile:
ARG NEXT_PUBLIC_API_BASE_URL
ENV NEXT_PUBLIC_API_BASE_URL=${NEXT_PUBLIC_API_BASE_URL}
You should add the ENV_VARS in a .env.local file. in form of a configMap. (https://nextjs.org/docs/basic-features/environment-variables)
In Kubernetes you create a configMap like so:
apiVersion: v1
name: env-local
data:
.env: |-
NEXT_PUBLIC_API_URL=http:/your.domain.com/api
API_URL=http://another.endpoint.com/serverSide
kind: ConfigMap
Then you mount that configMap as FILE into your deployment, it then is available at app/.env.local:
apiVersion: apps/v1
kind: Deployment
spec:
replicas: 1
selector:
matchLabels:
app: your-app
template:
metadata:
labels:
app: your-app
spec:
containers:
- image: your/image:latest
imagePullPolicy: Always
name: your-app
ports:
volumeMounts:
- mountPath: /app/.env.local
name: env-local
readOnly: true
subPath: .env.local
volumes:
- configMap:
defaultMode: 420
items:
- key: .env
path: .env.local
name: env-local
name: env-local
What also worked - for me at least - for server side vars was simply adding them as regular env vars in my deployment: https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/#define-an-environment-variable-for-a-container
apiVersion: v1
kind: Pod
metadata:
name: your-app
labels:
purpose: demonstrate-envars
spec:
containers:
- name: your-app-container
image: gcr.io/google-samples/node-hello:1.0
env:
- name: DEMO_GREETING
value: "Hello from the environment"
- name: DEMO_FAREWELL
value: "Such a sweet sorrow"
const withSvgr = require('next-svgr');
module.exports = {
// Will only be available on the server side
serverRuntimeConfig: {
API_URL: process.env.API_URL,
},
// Will be available on both server and client
publicRuntimeConfig: {
NEXT_PUBLIC_API_URL: process.env.API_URL,
},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With