DEV Community

Prathviraj H
Prathviraj H

Posted on

πŸ› οΈ Fixing CORS Errors in MERN Stack

The Issue

While developing my CampusX project, I ran into a frustrating bug:

βœ… Frontend (React) was calling the backend (Express).

❌ But I kept getting a CORS policy error in the browser console.

What is CORS?

CORS (Cross-Origin Resource Sharing) is a security feature in browsers that blocks requests from a different origin unless the server explicitly allows them.

In my case:

  • Frontend: http://localhost:3000
  • Backend: http://localhost:5000
  • The browser blocked the request because the backend didn't allow requests from the frontend’s origin.

The Root Cause

I hadn’t properly configured CORS middleware in my Express backend.

const express = require("express");
const cors = require("cors");

const app = express();

// ❌ No CORS setup -> Browser blocks cross-origin requests
app.use(express.json());

app.listen(5000, () => console.log("Server running on port 5000"));
Enter fullscreen mode Exit fullscreen mode

The Fix

I installed the cors package and added this middleware:
npm install cors

Then, in server.js (or app.js), I added:

app.use(cors({
    origin: "http://localhost:3000", // Allow frontend requests
    credentials: true, // Allow cookies & authentication headers
}));
Enter fullscreen mode Exit fullscreen mode

Now, my frontend could successfully communicate with the backend without CORS issues. πŸš€

βœ… Option 2: Handling CORS for Production

For production, I replaced localhost:3000 with the actual frontend URL:

const allowedOrigins = ["http://localhost:3000", "https://campusx.com"];

app.use(cors({
    origin: allowedOrigins,
    credentials: true,
}));
Enter fullscreen mode Exit fullscreen mode

This ensures the backend only allows requests from trusted domains.

Key Takeaways

  • CORS errors happen when the frontend and backend run on different origins.
  • Use the cors middleware in Express to allow frontend requests.
  • Always enable credentials: true if using cookies for authentication.

Top comments (0)