javascriptreactjsnode.jsvercelastrojs

How to prevent cached responses with Astro on Vercel?


I am trying to fetch data on the client side in Astro, but I keep getting a cached response.

From my endpoint in src/pages/api/spotify.ts I am sending:

export const prerender = false;
...
export const GET: APIRoute = async () => {
  ...
  return new Response(
    JSON.stringify({
      currentlyPlaying:
        currentlyPlayingTrack && formatTrack(currentlyPlayingTrack),
      topTracks: userTop.items.map(formatTrack),
    } satisfies APIResponse),
    {
      headers: {
        "Cache-Control": "public, s-maxage=60, stale-while-revalidate=30",
      },
    },
  );
};

Then in src/pages/index.astro I load my React component:

<SpotifyTrackList client:load />

Inside SpotifyTrackList.tsx I have:

export function SpotifyTrackList() {
  const { data } = useStore($spotifyData);

  return (
    <>
      {data?.currentlyPlaying && (

Where $spotifyData is:

import { nanoquery } from "@nanostores/query";

export const [createFetcherStore, createMutatorStore] = nanoquery({
  fetcher: (...keys: Array<string | number | true>) =>
    fetch(keys.join("")).then((r) => r.json()),
});

export const $spotifyData = createFetcherStore<APIResponse>(["/api/spotify"]);

Locally it works fine and I confirmed I get the latest data, but on Vercel I keep getting a cached response. I have also tried adding a vercel.json file:

{
  "headers": [
    {
      "source": "/api/spotify",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "public, s-maxage=60, stale-while-revalidate=30"
        }
      ]
    }
  ]
}

Finally, my astro.config.ts contains:

output: "hybrid",
adapter: vercel({
  webAnalytics: {
    enabled: true,
  },
  imageService: true,
}),

When I inspect my route responses, I keep getting the following headers (this was without my vercel.json file):

HTTP/2 304 
cache-control: public, max-age=0, must-revalidate
date: Fri, 05 Jul 2024 18:30:55 GMT
server: Vercel
x-vercel-cache: HIT
x-vercel-id: fra1::9k9pw-1720204255073-11f1e9dc8577
X-Firefox-Spdy: h2

Solution

  • Fixed by using maxage instead of s-maxage (How does stale-while-revalidate interact with s-maxage in Cache-Control header?).