CORS
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different origin than the one that served the page, unless the server explicitly allows it.
APIs intended to be consumed by browser-based frontends on different domains must configure CORS headers correctly.
How CORS works
The server includes headers like `Access-Control-Allow-Origin` to tell browsers which origins are permitted to access the resource.
Using the cors package
The `cors` npm package is Express middleware that automatically sets the correct CORS headers based on configuration.
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors({ origin: 'https://myfrontend.com' }));This allows only https://myfrontend.com to make cross-origin requests to this API.
app.use(cors());Access-Control-Allow-Origin: *Calling cors() with no options allows requests from any origin (useful for public APIs).
Key points
- CORS is enforced by browsers, not servers themselves.
- Access-Control-Allow-Origin controls which origins are permitted.
- The cors npm package simplifies configuring these headers in Express.
- Restrict CORS to trusted origins in production for security.
