Nextjs env variable is always undefined
Solution 1
You can access env
variables using public runtime config property:
next.config.js
module.exports = {
publicRuntimeConfig: {
NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
}
};
then:
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.NEXT_PUBLIC_URL);
If it doesn't work, make sure the env variables are created inside docker container
Solution 2
While NextJs has many pros, this is the one con that I have found with it. Because of their feature, Advanced Static Optimization
(https://nextjs.org/docs/advanced-features/automatic-static-optimization) env vars are converted into their values at build time. This is not very well documented on their site, but after a lot of testing I figured out the solution.
So you have to tell your docker image that when it starts up to npm run build
before npm run start
It will consume the env vars currently in the docker image and optimize them into the build with the values you wanted.
Cheers.
Related videos on Youtube
Ganav
Updated on June 04, 2022Comments
-
Ganav almost 2 years
My project setup is like this:
project-ci (only docker) nextjs backend
Staging and Production are the same so I pass in
docker-compose.yml
file of staging only this argument (both environments are built with these commands firstnpm run build
and thennpm run start
)args: NEXT_PUBLIC_URL: arbitrary_value
in
Dockerfile
of the nextjs put these commandsARG NEXT_PUBLIC_URL ENV NEXT_PUBLIC_URL=$NEXT_PUBLIC_URL
so variable will then be accessible in nextjs with
process.env.NEXT_PUBLIC_URL
. So far if I try toconsole.log(process.env.NEXT_PUBLIC_URL)
inindex.js
the value is alwaysundefined
. Any ideas what is wrong, also checked the docs but the result was stillundefined
https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration
https://nextjs.org/docs/api-reference/next.config.js/environment-variables
-
objectclass almost 3 yearsdo you have any dockerfile example for this? Strange there isn´t any good documentation for these scenarios over at the NextJS site.
-
Ben Hamilton over 2 years@objectclass At the bottom of my docker file I have
CMD [ "yarn", "start:docker" ]
and in my package.json I have"start:docker": "next build && next start"
which will instruct the docker image to build before starting.