Automatically revalidate KV Store cache on change with Database Webhooks in Supabase

Jon Meyers
InstructorJon Meyers
Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years ago

Supabase Function Hooks allow us to subscribe to change events in the database - such as insert, update and delete - and make a HTTP request with the changed data.

In this lesson, we refactor our revalidate route to handle inserts, updates and deletes.

Additionally, we create a Function Hook to subscribe to all change events on the articles table, and automatically send a POST request to the revalidate route of our Cloudflare Worker.

This automatically refreshes the KV store anytime a value is changed in the database, and decouples the revalidation of our cache, from our user requesting data. This means, theoretically, users should never have to wait for a request to the Supabase origin server, as the cache is automatically populated, updated and cleared to remain in sync with the database.

Code Snippets

Update Revalidate route to handle insert, update and delete
  async (request, { SUPABASE_URL, SUPABASE_ANON_KEY, ARTICLES }) => {
    const { type, record, old_record } = request.content;
    const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

    if (type === "INSERT" || type === "UPDATE") {
      await writeTo(ARTICLES, `/articles/${}`, record);

    if (type === "DELETE") {
      await ARTICLES.delete(`/articles/${}`);

    const { data: articles } = await supabase.from("articles").select("*");
    await writeTo(ARTICLES, "/articles", articles);

    return json({ received: true });

Run wrangler development server

npx wrangler dev

Publish Cloudflare Worker with Wrangler CLI

npx wrangler publish


~ 2 years ago

In the GitHub commit, withClient is not imported in index.js file

Markdown supported.
Become a member to join the discussionEnroll Today