fetch-apibrowser-cachehttp-caching

http 307 redirect cacheability


Can 307 redirect be cached by browser?

I have a simple service, which redirects all requests to another URL using the 307 Temporary Redirect status code.

curl localhost:8081 -v
*   Trying 127.0.0.1:8081...
* Connected to localhost (127.0.0.1) port 8081 (#0)
> POST / HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.0.1
> Accept: */*
>
< HTTP/1.1 307 Temporary Redirect
< location: http://localhost:8080
< cache-control: private, max-age=60
< access-control-allow-credentials: true
< vary: origin
< vary: access-control-request-method
< vary: access-control-request-headers
< content-length: 0
< date: Wed, 30 Aug 2023 17:41:17 GMT

According to my understanding of rfc9111, browsers should cache the redirect response based on the provided max-age in the cache-control header. However, I observe that the browser always makes two requests: first to the original URL and then to the redirected URL. (Actually 3 because of cors, but it's not a point of question.)

I have checked both chrome and Firefox using this code:

const options = {
  cache: 'force-cache',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: '{"some:"data"}'
};

for (let step = 0; step < 1000; step++) {
  fetch('http://localhost:8081/', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));
}

Solution

  • Fetch spec doesn't mention cache for redirects. RFC 9111 specifies that a client "MAY store" a response with a cache-control: private directive. This means that a browser or client is allowed to cache the response, but is not obligated to do so.