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.
To do this in Workers, it’ll look like this:
import { AsyncLocalStorage } from "node:async_hooks";
const asyncLocalStorage = new AsyncLocalStorage();
// get the request id from our AsyncLocalStorage// and use it in our logsasync 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 startedb75c5e19 - doStuff started4:49:07 PM GET / 200b783ff13 - doStuff finishedb75c5e19 - doStuff finished4:49:07 PM GET / 200
For more examples and information about what subset of AsyncLocalStorage is implemented by Cloudflare Workers, refer to the documentation.