🌐
Security & Performance

CORS in Express

Cross-Origin Requests Allow karna
💡 CORS EK BUILDING ka VISITOR REGISTER hai — browser puchta hai "kya main is dusri building se aaye bande ko andar bhej sakta hoon?" aur server whitelist dekhkar haan ya na kehta hai.

CORS restriction BROWSER lagata hai, server nahi — isi liye Postman se request chalti hai lekin browser se "blocked by CORS policy" aata hai. Server ko Access-Control-Allow-Origin header bhejkar permission deni hoti hai.

cors package ye headers set karta hai. Production mein origin: "*" mat rakho — specific origins ki list do. Agar cookies bhejni hain to credentials: true chahiye, aur tab wildcard origin allowed hi nahi hai.

const cors = require("cors");

app.use(cors({
  origin: ["https://app.code10x.in", "http://localhost:3000"],
  credentials: true,                      // cookies ke liye
  methods: ["GET", "POST", "PUT", "DELETE"],
}));
🌐
CORS EK BUILDING ka VISITOR REGISTER hai — browser puchta hai "kya main is dusri building se aaye bande ko andar bhej sakta hoon?" aur server whitelist dekhkar haan ya na kehta hai.
1 / 2
⚡ Quick Recap
  • CORS browser-side restriction hai, isliye Postman se error nahi aata
  • cors package Access-Control-* headers set karta hai
  • Production mein specific origins do, cookies ke liye wildcard allowed nahi
Is page mein (2 subtopics)

Non-simple requests (custom headers, PUT/DELETE, JSON content-type) se pehle browser ek OPTIONS "preflight" request bhejta hai. Server ko Access-Control-Allow-Methods aur -Allow-Headers ke saath jawab dena hota hai — cors package ye automatically handle kar deta hai.

app.use(cors({
  origin: "https://app.code10x.in",
  allowedHeaders: ["Content-Type", "Authorization"],
  maxAge: 86400,          // preflight result 1 din cache
}));

Agar allowed origins database ya env se aate hain, to origin ke liye function do. Isse multi-tenant setups mein per-request decide kiya ja sakta hai ki request allow karni hai ya nahi.

const allowed = process.env.ALLOWED_ORIGINS.split(",");
app.use(cors({
  origin: (origin, cb) =>
    !origin || allowed.includes(origin)
      ? cb(null, true)
      : cb(new Error("Not allowed by CORS")),
  credentials: true,
}));