Home  >  Q&A  >  body text

How to use a different base URL

During development, I used Vite for the React client for HMR on http://localhost:5173/ and used the Node backend to handle API calls and resources.

For production builds, Node will provide the frontend services, so I want to use /whatever/endpoint. So I need an overridden way to map / to http://my.api.host:3000/ when served by Vite.

I'm sure this must be a common operation, but I don't know how to do it. According to the documentation, I think this should be done:

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

export default defineConfig({
    plugins: [react()],
    server: {
        origin: 'http://my.api.host:3000'
    },
    base: 'http://my.api.host:3000'
})

But this:

backgroundImage: 'url(/img/backgrounds/main.jpg)'

Still trying to serve from http://localhost:5173.

P粉805922437P粉805922437248 days ago388

reply all(1)I'll reply

  • P粉556159786

    P粉5561597862024-01-17 17:22:07

    To rewrite the API endpoints and serve resources from the correct location when using Vite for production, you can use the proxy option in the Vite configuration. Here's an example of how to configure it:

    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react-swc';
    
    export default defineConfig({
      plugins: [react()],
      server: {
        proxy: {
          '/whatever/endpoint': {
            target: 'http://my.api.host:3000',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/whatever\/endpoint/, ''),
          },
        },
      },
      base: 'http://my.api.host:3000/',
    });

    The 'rewrite' function is used to remove the /whatever/endpoint prefix from the request path before forwarding it to the target.

    reply
    0
  • Cancelreply