How to pass a URL to client side from server side in a Next.JS project?

257 views Asked by At

So. I have a react / next.js project that I want to host in separate environments for separate customers. The project is the same for all customers, but they have separate databases/APIs. I want to be able to build my project once "npm run build" and then deploy several instances of it with different environment variables to determine what API each deployment should target. I am trying to use process.env.CUSTOMER to do so.

The problem is that I can only access this variable from my server side files, and I need to put the correct URL for my API on the client side files. I can not seem to find a way to have my client side get a proper value from my server side post-build.

This is what I have tried so far, and why it did not work.

  1. I tried to prefix my environment variable with PUBLIC_NEXT_, this actually does allow me to access it from client side - however, it does not let me change this after I've built my project.
  2. I've tried to add a .txt file with the correct url to my start script. However it seems I can only read .txt files from server side files, so it is more or less the same problem.
  3. I tried adding a mapping function in my next.config.js, which does have access to process.env.CUSTOMER. I then try to export the correct url through module.exports.env. I did actually get the right URL this way, however - when I try to change my CUSTOMER variable (post-build) and start my project again it does get the right CUSTOMER value in my config, but the mapping feature does not update and still feeds my client side whichever URL my CUSTOMER variable was pointing to when I built the project.
  4. I tried researching api routes, but eventually I came to the realization that for api routes to work, the (client side of the) application has to know where it is hosted - and that is what I am trying to figure out. So I can't really fetch something from an API I don't know where is (and then ask where I can find my API).

Does anyone know any other approaches I could take? Like can I have my client-side ask my back-end files (without knowing the domain/url)? All I gotta do is send one tiny variable from one end to the other.

0

There are 0 answers