Search code examples
javascriptreactjsproxyvitemern

Proxy is not working in Vite js project and request is not getting redirected to the proper api


I have a basic MERN stack application which I have deployed using vercel.
The frontend is at "https://ticketify-silk.vercel.app/".
The backend is at "https://ticketify-api.vercel.app/".


In the frontend code, I have used vite and also proxy to fetch data from api. Following is the code in the vite config file.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    proxy: {
        '/api': {
          target: 'https://ticketify-api.vercel.app',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      },
  },
  plugins: [react()],
});

In the backend code as well, I have defined the following code to avoid the CORS error.

app.use(
  cors({
    origin: ["https://ticketify-silk.vercel.app"],
    methods: ["GET", "POST", "PUT", "UPDATE"],
    credentials: true,
    allowedHeaders: ["Content-Type", "Authorization"],
  })
);

When I send a request from the frontend, instead of going to "https://ticketify-api.vercel.app/" it is going to "https://ticketify-silk.vercel.app/". This is the error that I am getting ->

enter image description here

So basically, the proxy is not working. And everything is running fine in my local environment, where the frontend is at "http://localhost:5173" and backend is at "http://localhost:8080".

Could anyone please suggest a solution? I already tried proxy api is not working in Vite + Vue 3 project when it's deployed to Vercel, but the solutions did not work for me. Can the issue be solved by any changes to the vercel.json file? I am not sure about it because I am deploying using vercel for the first time.


Solution

  • Try making the server conf look like this:

    server: {
        proxy: {
          '/api': 'your target url'
        }
      },
    

    It worked for me!