Skip to content

CORS

  • CORS = Cross Origin Resource Sharing.
  • It’s a browser security feature that restricts requests from one origin(domain, protocol, port) to another.
  • 👉 Example:
    • Frontend (React) running on http://localhost:3000.
    • Backend (Express API) running on http://localhost:5000
  • By default, the browser blocks requests from frontend -> backend because they are different origins.
  • CORS allows us to say :
    • “This backend trusts requests from this frontend”.
  • Eg:
// Frontend (http://localhost:3000)
fetch("http://localhost:5000/api/data")
.then(res => res.json())
.then(data => console.log(data));
  • If the backend doesn’t allow it, the browser throws:
  • Output:
Access to fetch at 'http://localhost:5000/api/data'
from origin 'http://localhost:3000' has been blocked by CORS policy.
  • ✅ Option 1: Using the cors middleware (recommended).

    • Install npm install cors package.
    • Usage:
    // Allow all origins (not recommended for production)
    app.use(cors());
    // Allow specific origin
    app.use(cors({
    origin: "http://localhost:3000"
    }));
  • ✅ Option 2: Manual headers (less common, more control)

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // allow only React app
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
  • For POST, PUT, DELETE request, the browser sends a preflight OPTIONS request to check if the server allows it.
  • cors middleware handles its automcatically.
  • If doing manually :
    app.options('*", (req, res)=>{
    res.send(200)
    })
  • Don’t use app.use(cors()) with * in production.
  • Always restrict origin to trusted domains (like your frontend).
  • Use credentials: true if sending cookies or tokens.
app.use(cors({
origin: "https://myapp.com",
credentials: true
}));
  • CORS = allows controlled cross-origin requests.
  • In Express → use cors middleware (easy) or set headers manually.
  • Always restrict origins in production for security.