# node:async_hooks

The `node:async_hooks` module tracks the lifecycle of asynchronous resources, as the [Node.js async\_hooks documentation](https://nodejs.org/api/async_hooks.html) describes. Its hooks fire at each stage of an asynchronous operation, for context propagation and debugging. In Azion Runtime, the module is available through Node.js compatibility. Its common use in a function is `AsyncLocalStorage`, which carries request-scoped data, such as a request ID, across asynchronous calls.

In a deployed function and under `azion dev`, `AsyncLocalStorage` keeps its store across an `await` and into a `setTimeout` callback, and outside `run()`, `getStore()` returns no value. `AsyncResource` works too: `runInAsyncScope()` runs its callback and returns the callback's value.

---

## Example

The function below reads the `X-Request-Id` header, stores it with `AsyncLocalStorage`, and logs it from functions that do not receive it as an argument:

```javascript
/**
 * An example of using the Node.js Async Hooks API in an Azion Function.
 * @example
 * // Build and run locally with the Azion CLI:
 * azion build
 * azion 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;
```

A request with the header `X-Request-Id: req-1` receives the body `ok`. While the request runs, the function logs these lines:

```text
req-1 - log from sync function
req-1 - log from another sync function
```

---

## Related resources

- [Node.js APIs](/en/documentation/devtools/runtime/node.md): Every Node.js module Azion Runtime resolves, and how each one behaves.
- [node:timers](/en/documentation/devtools/runtime/node/timers.md): The timer functions, such as the setTimeout call this sample schedules.
- [Use Node.js APIs through polyfills](/en/documentation/guides/application-development/functions-and-runtime/use-polyfills.md): How the build resolves Node.js APIs through polyfills, shown in a JavaScript project.
- [Handlers](/en/documentation/devtools/runtime/api-reference/handlers.md): The recommended handler shape, and the notice `azion build` prints for the `export default main` shape this sample uses.
