Here's how you can configure a proxy for your Vite project to hide the backend API URL

Posted: 17-10-2024 | Views: 55
Here's how you can configure a proxy for your Vite project to hide the backend API URL

In a Vite.js React project, you can configure the proxy differently because Vite has its own built-in proxy configuration.

Here's how you can configure a proxy for your Vite project to hide the backend API URL:

Step 1: Update vite.config.js

Vite allows you to set up a proxy in the vite.config.js file. Modify this file to include the proxy configuration.

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/proxy': {
        target: 'http://localhost:1337',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/proxy/, ''), // Removes '/proxy' from the request path
      },
    },
  },
});

This configuration will proxy requests made to /proxy on your frontend to http://localhost:1337.

Step 2: Update Your API Requests

In your React components, update the API requests to use the proxied URL:

// Example API request
const fetchCustomers = async () => {
  const response = await fetch('/proxy/api/customers'); // no need for localhost:3000
  const data = await response.json();
  console.log(data);
};

Step 3: Run Your Vite Development Server

Start your Vite development server using:

npm run dev

Your API requests to /proxy/api/customers will now be proxied to http://localhost:1337/api/customers, hiding the backend URL from the browser network tab.

Additional Notes:

  • CORS: Like before, this approach will help you avoid CORS issues since Vite will handle the proxy server-side.
  • Production: For production, this setup is not applicable. You’ll need a reverse proxy (e.g., Nginx) to handle requests securely.

This should work for your Vite.js project!

Add comment