Home > Software design >  How to change the URL prefix for fetch calls depending on dev vs prod environment?
How to change the URL prefix for fetch calls depending on dev vs prod environment?

Time:03-20

This is a follow-up to my previous question.

I'm using Vite, and the dev server comes with a proxy server, such that I can specify a proxy like this:

proxy: {
  '/v1': {
    target: 'https://127.0.0.1:8080',
    changeOrigin: true
  }
}

And then a fetch call called like this:

fetch("/v1/get-users");

Will effectively be transformed into this:

fetch("https://127.0.0.1:8080/v1/get-users");

This works perfectly, because that is where my API server is hosted on my dev environment.

However, this will fail on prod, because there my API server is instead hosted at https://api.mysite.com

Ideally I could just somehow express that my prod prefix should instead be https://api.mysite.com instead of https://127.0.0.1:8080, but apparently Vite does not use a proxy server with its build output.

How do people normally handle this? The only thing I could think of is perhaps something like this, but it seems a bit gross:

function getPrefix() {
  return location.hostname === "mysite.com" ? "https://api.mysite.com" : "";
}

fetch(getPrefix()   "/v1/get-users");

But it just seems kind of messy, and cumbersome to have to add that to every fetch call.

I could make a fetch wrapper as well, but I'm just wondering if this sort of thing is how people solve this to begin with, or if there is a more "best-practice" solution for this common problem.

CodePudding user response:

The simplest (and cleanest) solution I can think of is to replace the values in your code. This is often done for things like process.env.NODE_ENV or the like, but this is certainly a standard usecase.

You can use rollup-replace-plugin vite-plugin-replace, which allows you to replace values in your code.

Change vite.config.js to:

// ...
import { replaceCodePlugin } from "vite-plugin-replace";

export default {
  // ...
  plugins: [
    replaceCodePlugin({
      replacements: [
        {
          from: "__SITE_BASE__",
          to: process.env.NODE_ENV === "production"
                ? "https://api.mysite.com" // production site
                : "" // development proxy,
        }
      ],
    }),
  ],
});

In your code, you would do:

fetch("__SITE_BASE__/v1/get-users");

This would be advantageous over your current approach, as firstly, you can easily change your site base (instead of digging in your code to find that function), secondly, it's easier to write, and lastly you have static data, so you don't have to call the function every time the user loads the page, which is better for performance anyways.

  • Related