Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing next.config.js variables after build

I created an application using nextjs and I used next.config.js publicRuntimeConfig for variables that can be changed. I store something like Page default titles and/or my site configurations.

This application can be installed for different customers with different settings.

For example, I have an AGENCY_NAME property inside publicRuntimeConfig which is obviously different for different customers.

One can be "Company 1" and the other can be "Company 2".

I build this application once and move it to my server and then for every new customer I copy the same folder and create a host for it.

But when I try to change the variables inside the next.config.js it doesn't affect the values and the value remains the same. it only takes effect if I rebuild the application which I don't want to do.

So, is it possible to make some workaround about this or are there any other ways to achieve this? I just want to have some variables that can be changed later in production.

Note: variables use both on server and client-side.

like image 687
M.R.Safari Avatar asked Oct 31 '25 21:10

M.R.Safari


1 Answers

Ok! I figured it out after 3 days.

here is the steps to achieve this.

  1. install dotenv package using npm i dotenv or yarn add dotenv

  2. create .env.local file in the project root

  3. add your variables inside .env file

  4. create next.config.js and your variables in publicRuntimeConfig like this

    publicRuntimeConfig: {
        FIRST_VAR: process.env.NEXT_PUBLIC_FIRST_VAR,
        SECOND_VAR: process.env.NEXT_PUBLIC_SECOND_VAR,
    }
    
  5. create a build using npx next build

  6. simply change .env.local file when you need to change the variables

honestly, I have no idea why installing dotenv package fix this. my best guess is, it changes how nextjs behave and use .env files.

like image 159
M.R.Safari Avatar answered Nov 04 '25 08:11

M.R.Safari