Simplifies the handling of Cross-origin Resource Sharing (CORS).
- Use CORS as a middleware in Express.
- Set the CORS headers of an HTTP response.
- Configure CORS not only for the entire server, but also for individual routes.
Note
This is a lightweight alternative library to cors with no dependencies.
The Same-Origin Policy (SOP) is a browser security mechanism that restricts some HTTP requests made between different origins. It helps isolate potentially malicious documents and reducing possible attack vectors. Two URLs are part of the same origin if they have the same scheme, host, and port.
The following interactions are not affected by SOP: links, redirects, form submissions and HTML embedding.
The CORS consists of a set of HTTP headers that indicates whether a request can be shared cross-origin.
- A CORS request includes the
Origin
header, which indicates the URI that caused the request. - The
Origin
header is also included for all requests whose method is neitherGET
norHEAD
. - The server must properly set the
Access-Control-Allow-Origin
header. - A response to a CORS request can use any status code.
A preflight request is a "light" HTTP request using the OPTIONS
method that checks to see if the CORS protocol is understood in order to determine if the actual request is safe to send, this also helps to prevent the server from unnecessarily performing actions from untrusted origins.
- A preflight request also includes the
Access-Control-Request-Method
header, which indicates the HTTP method that will be used when the actual request is made. - The server must properly set the
Access-Control-Allow-Methods
andAccess-Control-Allow-Headers
headers, and optionally theAccess-Control-Max-Age
header. - A response to a preflight request request is restricted to an ok status (typically
200
). - For a preflight request, credentials mode is always same-origin (it excludes credentials), but for any subsequent CORS requests it might not be. Support therefore needs to be indicated as part of the HTTP response to the preflight request as well.
Requests that meet all of the following conditions do not trigger a preflight request:
- One of the allowed methods:
GET
,HEAD
orPOST
. - The request contains headers automatically set by the user agent, forbidden headers and CORS-safelisted headers.
- The Content-Type header can contain one of the following values:
text/plain
,application/x-www-form-urlencoded
ormultipart/form-data
. - No event listeners are registered on any
XMLHttpRequestUpload
object. - No ReadableStream object is used in the request.
Note
If the user agent does not trigger a preflight request (i.e. the request meets the criteria for a simple request), the server will not have the possibility to block the actual request beforehand, which will cause the request to be processed normally, although the response will be blocked by the browser if it does not satisfy the CORS.
The Access-Control-Expose-Headers
and Access-Control-Allow-Credentials
headers can also be included in both types of requests.
The Access-Control-Allow-Credentials
header works in conjunction with the credentials mode of the Fetch API.
- Tells browsers whether to expose the response to the frontend JavaScript code.
- In a preflight request, indicates whether the actual request can be made using credentials.
Note
- Credentials are cookies, authorization headers, or TLS client certificates.
- Credentials are used when the user agent should send or receive them in cross-origin requests.
- By default, credentials are sent if the request is on the same origin as the calling script.
- Some cookies may still be sent if the request is same-site, regardless of whether it is cross-origin or not.
// Using Fetch with credentials.
await fetch('http://example.com/', {
credentials: 'include'
});
Warning
Sharing responses and allowing requests with credentials is rather unsafe, and extreme care has to be taken to avoid the confused deputy problem. See CORS protocol and credentials.
In addition to CORS, the HTTP Content Security Policy (CSP) response header extends an additional level of resource-level security to a website by preventing content from another source from being loaded. This helps guard against Cross-site Scripting (XSS) attacks.
Further reading:
- https://github.com/flipeador/node-http-cookies
- https://jub0bs.com/posts/2021-01-29-great-samesite-confusion
- https://jub0bs.com/posts/2022-08-04-scraping-the-bottom-of-the-cors-barrel-part1
npm i flipeador/node-http-cors#semver:^1.0.0
import express from 'express';
import cors from '@flipeador/node-http-cors';
const app = express();
app.use(cors({
// Indicates the allowed origins.
// The wildcard (*) cannot be used with credentials.
origin: [
/^https?:\/\/localhost:\d+/u,
/^https?:\/\/192.168.\d+.\d+:\d+/u,
'https://www.example.com'
],
// Allows cross-origin credentials.
// await fetch(..., { credentials: 'include' });
credentials: true
}));
app.use(express.json());
app.listen(8080, () => {
console.log('Server is running!');
});
This project is licensed under the Apache License 2.0. See the license file for details.