Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS: Prevent env vars to be required on build time

Tags:

docker

next.js

We are working on a Dockerized NextJS application that is thought to be built once and deployed to several environments for which we will have different configuration. This configuration is to be set in the Docker container when deployed as environment variables.

In order to achieve this, we are using next.config.js file, splitting the vars on serverRuntimeConfig and publicRuntimeConfig as suggested here, and we are getting the values for the environment variables from process.env. i.e.:

module.exports = {
  serverRuntimeConfig: {
    mySecret: process.env.MY_SECRET,
    secondSecret: process.env.SECOND_SECRET,
  },
  publicRuntimeConfig: {
    staticFolder: process.env.STATIC_FOLDER_URL,
  },
}

The problem we have is that these variables are not set on build time (when we run next build), as they are environment specific and supposed to be set on deployment. Because of this, the build fails complaining about the missing variables.

Making a build per environment is not an option: as referred before, we want to build it once (with next build), put the output of the build in a docker container, and use that docker container deploy in several environments.

Is there any way to solve this so that the application builds without environment vars and we pass them afterwards on runtime (deployment)?

like image 546
Jose Martin Avatar asked Nov 15 '22 14:11

Jose Martin


1 Answers

We finally found the issue.

We were importing code in a helper that was being used in the isomorphic side and was relaying on serverRuntimeConfig variables, being then required on build time in order to create the bundle.

Removing the import from the helper fixed the issue.

like image 146
Jose Martin Avatar answered Nov 23 '22 23:11

Jose Martin