Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nextjs env variable is always undefined

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

like image 308
Ganav Avatar asked Oct 11 '20 21:10

Ganav


2 Answers

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

like image 113
lissettdm Avatar answered Oct 04 '22 12:10

lissettdm


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.

like image 40
Ben Hamilton Avatar answered Oct 04 '22 13:10

Ben Hamilton