Next.js Discord

Discord Forum

Environment Variables Not Working Client-Side in Docker

Unanswered
Willow shoot sawfly posted this in #help-forum
Open in Discord
Willow shoot sawflyOP
Hello, I have a containerized environment with NextJS 12 pages router and I am trying to get an environment variable recognized client-side. So far the only way I've been able to do so is by caching the environment variables in getInitialProps (which I realize isn't ideal). This works with both NEXT_PUBLIC prefixing of the variable and not (since it's cached server-side). I've tried just using process.env client side with NEXT_PUBLIC and it does not work:

console.log(PUBLIC: ${process.env.NEXT_PUBLIC_WEBSITE_NAME});

Which gives me in the client console:

PUBLIC: undefined

It is defined in the environment as:

NEXT_PUBLIC_WEBSITE_NAME=My Website

Does anyone have any suggestions for getting this working in the pages router? The project is 98% complete and I'd like to get it released and then incrementally migrate to app router.

The weird thing is everything works fine in both a non-containerized production environment (build/start) and the development environment (dev). The caching was the only way I could get the containerized one to work.

Thanks in advance for any advice! 🙂

1 Reply

Willow shoot sawflyOP
The working (less than ideal) solution, works regardless of NEXT_PUBLIC:

MyApp.getInitialProps = async (context: any) => {
const clientEnvs = {
WEBSITE_NAME: process.env.WEBSITE_NAME,
}
return { clientEnvs, ...App.getInitialProps(context) };
}