hapijs / hapijs/hapi

How to use AsyncLocalStorage?

Open
#4,516 3 comments 0 reactions 0 assignees View on GitHub
feature
Dominant language
JavaScript
Stars
14.8k
Forks
1.4k
Avg merge
22d 3h
Merged PRs (30d)
1

Description

### Runtime

Node.js

### Runtime version

18.17.1

### Module version

21.3.10

### Used with

Hapi application

### Any other relevant information

_No response_

### What problem are you trying to solve?

I'm looking into using [AsyncLocalStorage](https://nodejs.org/api/async_context.html#class-asynclocalstorage) to make certain values accessible throughout my application logic, without explicitly passing it as a parameter everywhere.

As far as I can tell, this is a poor fit for Hapi: Hapi lifecycle methods and plugins offer extension points, for invoking arbitrary logic at different points in the application. However, AsyncLocalStorage wants to be invoked with an asynchronous callback, so it can see the start-to-finish execution of amethod; I can't find a way for a Hapi plugin to wrap a request or handler method start-to-finish.

Similar questions come up with instrumentation and monitoring frameworks such as Sentry or OpenTelemetry; OpenTelemetry's Hapi instrumentation currently uses [complex runtime patching](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/9dc55da3b856e6bc147d59547582f0bf056384a1/plugins/node/opentelemetry-instrumentation-hapi/src/instrumentation.ts#L366) to accomplish its goals.

### Do you have a new or modified API suggestion to solve the problem?

Hapi could offer a new lifecycle method / extension point that's invoked with a callback, so it can see the entire method start to finish.

Alternatively, Hapi could add explicit support for one or more AsyncLocalStorage instances.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.