CORS
Cross-origin resource sharing for HTTP routes, answered before routing.
Cors is a middleware that follows the Fetch specification's CORS protocol. It is declared on the pre-dispatch stage, so it answers a preflight before routing, including for a path with no route. The example is examples/17-http-pre-dispatch.
fn register(&self, m: &mut ModuleDef<'_>) {
m.meta::<PreDispatch>()
.apply_value(Cors::new().allow_origin("https://app.example").allow_methods([Method::GET]));
}PreDispatch is module metadata, so the module implements Module by hand. Middleware shows the full module.
What it does
- A preflight, an
OPTIONSrequest carryingOriginandAccess-Control-Request-Method, is answered 204 with theAccess-Control-Allow-*headers and never reaches routing or any later entry. In the example, a preflight for a path with no route is still answered, and the API-key entry behind it does not run. - Every response it passes gets
Vary: Origin, including responses to requests without anOrigin, so a cache does not hand an undecorated response to a cross-origin request. - A response to a request whose origin is allowed carries
Access-Control-Allow-Originwith that origin echoed. A request from another origin is still served. Only the CORS headers are absent. - A path the app refuses before the stage runs (a
.or..segment, or a\) answers 400 carrying the headers of eachCorsdeclared withapply_value. ACorsapplied by type adds nothing to that 400.
Options
Cors::new() allows nothing until configured.
| Method | Effect |
|---|---|
allow_origin(origin) | one allowed origin, echoed back when it matches; call it again for more |
allow_any_origin() | Access-Control-Allow-Origin: * |
allow_methods(methods) | Access-Control-Allow-Methods on a preflight |
allow_headers(names) | Access-Control-Allow-Headers on a preflight, from the list |
allow_any_header() | reflects the preflight's Access-Control-Request-Headers |
expose_headers(names) | Access-Control-Expose-Headers on responses |
allow_credentials(bool) | Access-Control-Allow-Credentials: true |
max_age(duration) | Access-Control-Max-Age on a preflight |
The specification forbids * together with credentials, and the server refuses that combination at startup with a CorsError rather than sending it.
Order among other entries
Entries run in the order written. A CORS entry declared before an authentication entry decorates the 401 the authentication entry's Err became, because the outer entry receives the inner response. A browser needs that to read the status. An unscoped tower layer declared before Cors also wraps the preflight answer, which is why the example's x-served-by header appears on it.