I am having trouble running a GCP Cloud Build for my Docker Image using a NextJS app. Since my application is using API keys, I am using GCP Secret Manager to load my environment variables at build time, which I can confirm from logging are populated, but when my NextJS loads at runtime with the build, there is an error being thrown because the env variables are not populating.
I know NextJS can set env variables at build (next.config.ts) or runtime (.env file), but can't figure out where the disconnect is with NextJS not capturing these values.
In addition, since some API keys are secrets, I would not prefer to expose them to the client side with NEXT_PUBLIC_ unless I'm misinterpreting the security of that approach.
Here is my cloudbuild.yml file:
steps:
- name: 'gcr.io/cloud-builders/docker'
entrypoint: 'bash'
args:
- '-c'
- |
echo "GHOST_CONTENT_API environment variable: $$GHOST_CONTENT_API"
echo "GA4_MEASUREMENT_ID environment variable: $$GA4_MEASUREMENT_ID"
docker build -t us-central1-docker.pkg.dev/${PROJECT_ID}/repo/repo-website .
secretEnv: ['GHOST_CONTENT_API', 'GA4_MEASUREMENT_ID']
availableSecrets:
secretManager:
- versionName: projects/${PROJECT_ID}/secrets/GHOST_CONTENT_API/versions/1
env: 'GHOST_CONTENT_API'
- versionName: projects/${PROJECT_ID}/secrets/GA4_MEASUREMENT_ID/versions/1
env: 'GA4_MEASUREMENT_ID'
Which at build, correctly logs the values from secretManager:
BUILD
Already have image (with digest): gcr.io/cloud-builders/docker
GHOST_CONTENT_API environment variable: #####
GA4_MEASUREMENT_ID environment variable: GTM-####
The error comes in when a module in the NextJS using the GHOST_CONTENT_API is missing the key at runtime.
Here is my Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN npm install --omit=dev --production
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]
Finally I tested with layout.tsx to see if the client or server side version of the ENV is loaded and both come back undefined:
console.log('ENV Variables - Layout.tsx')
console.log('Client ENV') // undefined
console.log(process.env.NEXT_PUBLIC_GHOST_CONTENT_API)
console.log('Server ENV') // undefined
console.log(process.env.GHOST_CONTENT_API)