Next.js building in container, all .env variables which not starting with NEXT_PUBLIC_ are undefined (on the server side) – Next.js

by
Ali Hasan
boot2docker github-actions next.js

Quick Fix: In your Dockerfile, copy the .env file before running the yarn build command. This ensures that the environment variables are available when Next.js builds the application.

The Problem:

You are deploying a Next.js application in a Docker container, and the environment variables not prefixed with NEXT_PUBLIC_ are undefined on the server side. You have checked that the .env file is properly created in the Docker image. On inspecting the container logs, you observe that only variables prefixed with NEXT_PUBLIC_ are defined, while others remain undefined.

The Solutions:

Solution 1: Copy .env file before building

Next.js loads environment variables at build time and not at runtime. So, the .env file must be in place before initiating the `yarn build` command. Copy the .env file to the root of the project in the Dockerfile, as shown below:

# ...
FROM node:16-alpine as builder
WORKDIR /my-project
COPY . .
COPY --from=dependencies /my-project/node_modules ./node_modules
COPY ./.env ./.env  # copy the .env file to the root of the project
RUN yarn build
# ...

Q&A

What causes the issue that environment variables are only visible on the client side?

The environment variables are loaded into the Next.js application at build time. Changes after the build won’t be reflected.

What is the solution for making env variables accessible during the build?

Ensure that your environment variables are available before the yarn build command is run.

Video Explanation:

The following video, titled "How to add Environment Variables in Next.JS | Using dot-files(.env ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

the best video for env on nextJS but still it does not work for me specifically for priority points like running on the development server ...