Preflight request
lastmod 2022-09-23created 2022-09-231 edits
Caching CORS for performance and cost
What is a CORS preflight?
- Before sending a complex request, first asking via OPTIONS whether you have permission
- But in practice most requests need this (having a JSON/XML body, including credentials, etc.)
- The reason this is bad is that it increases the time the actual request takes
- OPTIONS requests cannot be cached by default, so CDNs usually don't handle them either and the request reaches the server
- These values are cached on the client and kept for only 5 seconds by default.
- That is, if a web page polls an API every 10 seconds, a preflight happens once every 10 seconds
How to cache preflight responses
- Cache in the browser so it doesn't send unnecessary identical preflight requests
- Cache at the CDN layer so these requests are answered without the actual backend server having to handle them
CORS caching for browsers
- Add the following header to the preflight response: Access-Control-Max-Age: 86400
- Firefox allows up to 86400 (24 hours), but Chromium-based browsers have a maximum of 7200 (2 hours)
CORS caching for CDNs
- To cache at a CDN or proxy, add the following headers
- Cache-Control: public, max-age=86400
- Vary: origin
- The important thing is that OPTIONS is not meant to be cached by default, so this is not standard. But most CDNs support it
Configuration examples
- Caching CORS with AWS Lambda
- Caching CORS in Node.js
- Caching CORS in Python
- Caching CORS with Java Spring
See also
Favorite site
Pages that link here