For Vite React applications, I’ve found that the following works most excellently for me:
You can use the proxy
option in your vite.config.js
file. The proxy option allows you to redirect certain requests to a different server during development. This is useful, for example, when your frontend application needs to communicate with a backend API running on a separate server.
Inside the vite.config.js
file, define the proxy
option:
/// <reference types="vite/client" />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://your-backend-api-server.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
});
In this example, we’re setting up a proxy for requests starting with /api
. Any requests that match this pattern will be redirected to http://your-backend-api-server.com
.
If you want the get the API URL from an env variable, then you can write it like this
/// <reference types="vite/client" />
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/
export default ({ mode }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
const config = {
plugins: [react()],
server: {
proxy: {
'/api': {
target: process.env.VITE_BASE_URL,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
};
return defineConfig(config);
};
Here the VITE_BASE_URL is your API URL
If you liked this post don’t forget to click the heart below :).