Enabling CORS
7 min read
Enabling CORS
Browsers enforce the Same-Origin Policy, which blocks frontend JavaScript from making requests to an API on a different origin. Cross-Origin Resource Sharing (CORS) is the mechanism that lets your API opt in to cross-origin requests by sending specific HTTP headers.
bash
npm install cors
npm install --save-dev @types/corsjs
import cors from "cors";
const allowedOrigins = [
"https://myapp.com",
"https://staging.myapp.com"
];
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true
}));For development you might use cors() with no options to allow all origins, but always lock down the origin allowlist in staging and production environments.
Mount the CORS middleware before every other middleware and route, including your body parser. Preflight OPTIONS requests need to reach the CORS handler before Express routes process them.
Ready to test yourself?
Practice Express— quiz & coding exercises