'Consume Cloud Run environment variables inside Nextjs app

I've recently built a Nextjs app, which I am hosting on Google Cloud Run.

My app makes some requests to external APIs from the getStaticProps() method.

I would like to be able to point to a different API host depending on the environment (e.g prod or dev) using environment variables which would be set differently for each environment.

I know I can store these variables in environment specific files like .env.development and .env.production however I would like to be able to store these environment variables in the environment variables field in the Google Cloud console for the cloud run service and skip storing them in the files altogether.

I have tried adding in the variables to Cloud Run, but it does not work. I have also tried prefixing the variables with NEXT_PUBLIC_... With no luck.

Did anyone have any tips on how to accomplish this?



Solution 1:[1]

Ok... I think I have figured it out now. I was using Cloud Builds to build my container, and the container runs npm run build before it runs npm run start.

I assume that my Cloud Run variables aren't available at the point in time when Cloud Build is building the project.

So, I think my solution is prob to try and inject the variables at the point when it is building, using substitution variables.

EDIT: Confirmed. If I start Nextjs in dev mode, such that the page is rendered on the server for each request, then the Cloud Run environment variables are used. To build the Nextjs app for production, I include the environment variables in the Dockerfile that is built by Cloud Build

EDIT: as request, an example of a dockerfile setting the environment variable:

FROM node:16.13-alpine
RUN mkdir -p /usr/src
WORKDIR /usr/src
COPY . /usr/src

ENV NEXT_PUBLIC_MY_API_HOST='https://some.host.com'

RUN npm install -only=production
RUN npm run build
EXPOSE 3000
CMD npm run start

Then you can just reference the environment variable from within your code using process.env.NEXT_PUBLIC_MY_API_HOST

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1