I have deployed my web application on vercel using github. The frontend is loaded, but api requests from the frontend are not found with 404. By the way, this is a MERN app This is my vercel.json
{ "buildCommand": "cd client && npm install && ./node_modules/vite/bin/vite.js build", "outputDirectory": "client/dist", "framework": "vite", "rewrites": [ { "source": "/api/(.*)", "destination": "/index.js" } ] }
This is index.js
const express = require("express"); const cors = require("cors"); const mongoose = require("mongoose"); const cookieParser = require('cookie-parser'); const router = require('./router/router'); const setupCronJob = require('./cron'); const fs = require('fs'); require('dotenv').config(); const app = express(); app.use(express.json()); app.use(cookieParser()); // for reading cookies const allowedOrigins = ['http://127.0.0.1:5173','https://cozy-stay.vercel.app']; const corsOptions = { credentials: true, origin: allowedOrigins, methods: 'GET, POST, PUT, DELETE', allowedHeaders: 'Content-Type, Authorization, Cookie' }; app.use(cors(corsOptions)); const port = process.env.PORT || 4000; mongoose.set("strictQuery", false); mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, serverSelectionTimeoutMS: 10000, }).then(()=> { console.log('Connected to database') }).catch(err=>{ throw err; }) setupCronJob(); app.use('/api',router); app.listen(port);
This is the directory img
The frontend is already available but the api is not working properly, I think the api is not loaded yet. Please help me
What currently seems to be happening is that
https://cozy-stay.vercel.app/api
the path request goes to the frontend server instead of the backend server as you expect:Fix01
You can use two vercel applications for frontend and backend:
Fix02
You can run a load balancer that sends all requests with the
/api
prefix to the backend and other requests to the frontend. The IDK vercel platform supports this feature.