Cache Busting or Invalidation, is the process of clearing stale data from a cache. After the first request, the response data from Supabase is cached in our KV store, and never fetched again. This means if data in the database changes, our KV store will never be updated.
In this lesson, we create a revalidate
route, which fetches fresh data from Supabase and updates the cache.
Revalidate cache for articles route
router.get(
"/revalidate",
async (request, { SUPABASE_URL, SUPABASE_ANON_KEY, ARTICLES }) => {
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
const { data: articles } = await supabase.from("articles").select("*");
await writeTo(ARTICLES, "/articles", articles);
return json({ received: true });
}
);
Run wrangler development server
npx wrangler dev
Instructor: [0:00] Currently, we only fetch fresh data from Supabase the first time a route is visited. Every time we refresh after that, we're getting that value from the cache. This is great for performance, but if one of the rows in our database changes, for example, our second blog becomes our cool second blog, no matter how many times we refresh, we're never going to get that new title. [0:19] We're always going to see the title second blog. Let's create a new route in our worker to handle revalidating pages that have become stale. We'll say router.get. The path for this is going to be /revalidate.
[0:32] Our handler function is going to have the same signature as our previous requests where we have a request, our environment variables for Supabase URL, and a non key, and our KV store for articles. Inside this handler function, we want to create a new Supabase client and then make a request for all of the articles.
[0:50] Then we want to await a call to write to our articles store at the path/articles with that data that we got back from Supabase. This will overwrite that stale data in our cache with that fresh data from Supabase.
[1:05] We can then return a JSON response with the key received set to true.
[1:12] We can check this is working by going back to the browser and refreshing, seeing that we've still got that second blog, then navigating to our revalidate route, and then back to articles and confirming that the title for our second blog has been updated.