The async_hooks library in Node.js allows developers to track the lifecycle of asynchronous resources. It provides hooks that trigger at different stages of an asynchronous operation, enabling context propagation and better debugging. In the Azion Runtime, it’s available through Node.js compatibility, and AsyncLocalStorage is a common use case for carrying request-scoped data, such as a request ID, across asynchronous calls in a function.

The example below shows how to use the async_hooks module in a function:

/**
* An example of using the Node.js Async Hooks API in an Azion Function.
* @module runtime-apis/nodejs/async-hooks/main
* @example
* // Execute with Azion Bundler:
* npx edge-functions build
* npx edge-functions dev
*/
import { AsyncLocalStorage } from "node:async_hooks";
const requestId = new AsyncLocalStorage();
function logAsyncContext(state) {
console.log(`${requestId.getStore()} - ${state}`);
}
function doSomething() {
logAsyncContext("log from sync function");
setTimeout(() => doSomethingElse(), 100);
}
function doSomethingElse() {
logAsyncContext("log from setTimeout callback");
}
/**
* Example of using the Node.js Async Hooks API
* @param {*} event
* @returns {Promise<Response>}
*/
async function main(event) {
const id = event.request.headers.get("X-Request-Id") ?? "unknown";
return requestId.run(id, () => {
doSomething();
logAsyncContext("log from another sync function");
return new Response("ok");
});
}
export default main;