What CORS Is
Cross-Origin Resource Sharing (CORS) is a browser security mechanism that blocks a web page from making requests to a different origin (domain, port, or protocol) unless the server explicitly allows it via response headers.
Enabling CORS in Express
npm install corsBasic CORS Setup
Console Output
Click “Run” to see the console output here.
Common CORS Options
| Option | Purpose |
|---|---|
| origin | Which origin(s) are allowed to call this API |
| methods | Which HTTP methods are allowed cross-origin |
| credentials | Whether cookies/auth headers are allowed cross-origin |
CORS is a Browser Protection, Not a Server Firewall
CORS only affects requests made from a browser via JavaScript — it does not stop a server-to-server request, a curl command, or a mobile app from calling your API. It protects users from malicious websites making requests on their behalf, not your API from all unauthorized access.
Security Headers with Helmet
helmet is a middleware that sets a collection of HTTP response headers known to reduce common web vulnerabilities — like preventing your API's responses from being embedded in a malicious iframe, or telling browsers not to guess (sniff) content types.
Adding Security Headers
Console Output
Click “Run” to see the console output here.
Best Practice
Enable helmet() and a properly scoped CORS policy (a specific origin, not a wildcard, for any API handling authenticated requests) as two of the very first middleware registered in any production Express app.