Cloudflare Workers - using AsyncLocalStorage for request context

Cloudflare Workers recently implemented a subset of Node modules, one of these is AsyncLocalStorage!

One of the most common examples out there is using AsyncLocalStorage to add request context, like an ID for log items, to identify log messages that are related to the same request which can be hard when you have concurrent requests.

Let's recreate it in Workers.

import { AsyncLocalStorage } from "node:async_hooks";

const asyncLocalStorage = new AsyncLocalStorage();

// get the request id from our AsyncLocalStorage
// and use it in our logs
async function doStuff(ms: number) {
  const id = asyncLocalStorage.getStore();

  console.log(`${id} - doStuff started`);

  await scheduler.wait(ms);

  console.log(`${id} - doStuff finished`);
}

export default {
  async fetch() {
    // use the first segment of a UUID as our request id
    const reqId = crypto.randomUUID().substring(0, 8);

    // place the request id in the AsyncLocalStorage
    // and return "Hello World!" once 'doStuff' has finished.
    return asyncLocalStorage.run(reqId, async () => {
      await doStuff(1000);

      return new Response("Hello World!");
    });
  },
};

If we publish this Worker and look at the live logs whilst hitting it with concurrent requests, we can see they are being handled at the same time but have their own unique ID associated with them.

b783ff13 - doStuff started
b75c5e19 - doStuff started
4:49:07 PM GET / 200
b783ff13 - doStuff finished
b75c5e19 - doStuff finished
4:49:07 PM GET / 200

For more examples and information about what subset of AsyncLocalStorage is implemented by Cloudflare Workers, refer to the documentation.