Nextjs env variable is always undefined

11,339

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.

Share:
11,339

Related videos on Youtube

Ganav
Author by

Ganav

Updated on June 04, 2022

Comments

  • Ganav
    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 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

  • objectclass
    objectclass almost 3 years
    do you have any dockerfile example for this? Strange there isn´t any good documentation for these scenarios over at the NextJS site.
  • Ben Hamilton
    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.