1

I have a Next.js API deployed on Vercel. The API is used by multiple other domains.

When the browser send the If-None-Match header, Vercel can reply with a 304; however, the Access-Control-Allow-Origin header may contain a different origin, which causes a CORS error. I guess it's due to the fact Vercel sends the headers from the cached response.

How can I make sure the correct origin value will be specified in the Access-Control-Allow-Origin header? I think I could add some proxy for every domains consuming the API but I'd prefer to avoid that.

jub0bs
  • 60,866
  • 25
  • 183
  • 186
Luze26
  • 35
  • 6

1 Answers1

3

As I understand it, the problem is that Vercel doesn't include the request's origin in the cache key, and you get accidental Web cache poisoning. Unfortunately, Vercel doesn't seem to allow custom cache keys yet.

A long-term solution would be to put pressure on Vercel for them to add the origin to the their cache key; this is a sensible default that other CDNs, such as Cloudflare, have adopted. An alternative, short-term solution would be to make your responses to CORS requests non-cacheable according to Vercel caching rules:

{
  "name": "foo",
  "version": 2,
  "routes": [
    {
      "src": "/whatever",
      "headers": [
        { key: "Cache-Control", value: "no-cache" },
        ...
      ]
    }
  ],
  ...
}
jub0bs
  • 60,866
  • 25
  • 183
  • 186
  • 1
    Thanks for the edit and the reply. For the moment I forced the client to not use `If-None-Match`. I'll ask Vercel support for that. One thing that is weird is that there is an `authorization` header when the requests are made, so in theory Vercel should not cache them. Maybe the problem is elsewhere. – Luze26 Nov 19 '21 at 08:58
  • Weird indeed... Either there is another cache between Vercel and the client, or Vercel's documentation about its caching rules is incorrect. – jub0bs Nov 19 '21 at 10:14