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 first npm run build
and then npm run start
)
args:
NEXT_PUBLIC_URL: arbitrary_value
in Dockerfile
of the nextjs put these commands
ARG 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 to console.log(process.env.NEXT_PUBLIC_URL)
in index.js
the value is always undefined
. Any ideas what is wrong, also checked the docs but the result was still undefined
https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration
https://nextjs.org/docs/api-reference/next.config.js/environment-variables
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
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.
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