Use waitUntil to perform work after Cloudflare Worker returns response

Jon Meyers
InstructorJon Meyers
Share this video with your friends

Social Share Links

Send Tweet

The waitUntil function allows us to continue performing work in our Cloudflare Worker, after a response has been sent back to the client.

In this lesson, we modify the revalidate route to send a response immediately, and then continue on to fetch new data and refresh our KV store.

Finally, we use the Thunder Client extension to simulate a POST request to the revalidate route, and confirm that this receives a response before the cache is updated.

Code Snippets

Update Revalidate route to respond immediately

router.post(
  "/revalidate",
  withContent,
  async (request, { SUPABASE_URL, SUPABASE_ANON_KEY, ARTICLES }, context) => {
    const updateCache = async () => {
      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.id}`, record);
      }

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

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

    context.waitUntil(updateCache());

    console.log("sending response");

    return json({ received: true });
  }
);

Run wrangler development server

npx wrangler dev

Resources

Instructor: [0:00] Currently, when Supabase calls our revalidate route, it needs to wait around while we update our caches and even make a callback to Supabase to get fresh articles before we send back this response that's acknowledging that we received the request. [0:12] Since this response doesn't rely on any of that work to have happened, we could send the acknowledgement straight away and then perform the work. Back up in our handler function for this route, we receive a third parameter called context.

[0:26] Context has a function called wait until which we can use to continue performing work after a response is sent back from our Cloudflare worker. Let's wrap our cache revalidation logic in a function called update cache. This is going to be an asynchronous function. We want to move everything up until our context.wait until call into this function.

[0:47] We can then call our update cache function inside our call to the wait until function to perform this logic after this response has been sent back to the client. We can test this by adding a console log that we are sending response and then add another console log at the end of our function that says updated cache.

[1:06] We can test this is working locally by running npx wrangler dev and using the Thunder Client extension to make a request. We want to make a post request localhost:8787/revalidate, and we can pass a JSON body with the type set to skip to skip over any logic like the insert update or delete, which requires us to pass across a record or an old record.

[1:29] We can now send that request from Thunder Client. We can see that we received that response almost immediately. If we open up the console, we can see that we first sent back the response and then continued on to update the cache.