brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Access-Control-Max-Age lets browsers cache a CORS preflight

Web-Development
~/tips/tip-cors-access-control-max-age-preflight

curl -si -X OPTIONS \

Access-Control-Max-Age sets how long a browser may reuse a CORS preflight answer, and browsers cap it.

An OPTIONS request before nearly every API call in the browser’s network tab can simply mean the preflight cache time sits at its default. That default is five seconds.

A CORS preflight is the OPTIONS request a browser sends before a cross-origin request that needs permission. The server’s answer lists what is allowed, and Access-Control-Max-Age says for how many seconds the browser may remember that answer.

curl -si -X OPTIONS \
  -H 'Origin: https://app.example.com' \
  -H 'Access-Control-Request-Method: PATCH' \
  -H 'Access-Control-Request-Headers: content-type' \
  http://localhost:8000/items/1

curl doesn’t enforce CORS, but it can send the same preflight a browser would. A small Python test server answered with a 204 and these headers:

Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PATCH
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600

MDN says the value is the number of seconds the results may be cached, that the default is 5 seconds, and that browsers cap it. Firefox caps it at 24 hours, Chromium from version 76 at 2 hours, and Chromium before that at 10 minutes.

The caveat follows from those caps. Setting 86400 does not give you a day in Chrome. You get two hours at most, so a value of 7200 says the same thing in a more honest way.

Further reading: MDN: Access-Control-Max-Age

More Web-Development tips const ws = new WebSocket("wss://example.com/chat"); | openssl dgst -sha1 -binary | openssl base64 ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" All Web-Development tips (70) All topics

Link