Search code examples
cachingnext.jscorsvercelhttp-status-code-304

Vercel cache CORS headers issue for multiple domains


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.


Solution

  • 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 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" },
            ...
          ]
        }
      ],
      ...
    }