Expose request scoped AsyncLocalStorage API #76529
Jussinevavuori
started this conversation in
Ideas
Replies: 1 comment
-
|
For my use case (tracking external API errors for logging) I would also like to make this storage visible to Express middleware in case when Next.js runs in an Express server. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Goals
Non-Goals
request: Requestto the developerBackground
I am working on an authorization framework, which would allow for setting a request scoped "onPermissionDenied" handler, such that any component or function that fails an auth check has access to that function.
I initially implemented this as follows:
This was a hack and not the intended use for
React.cache, however I have seen a lot of people do this to share context across a request.This does not work in server actions and API routes, as they are outside of the react rendering lifecycle. (For now, I am using a combination of
React.cacheand wrapping server actions inAsyncLocalStoragein an ugly manner to overcome this limitation).Since Next.js exposes so many execution contexts, having a single API to share values across a request in each context would eradicate all hacks using
React.cache(() => ({ current }))with an even stronger primitive.Proposal
API for creating a new request scoped shared value.
API for calling from RSC
Equivalent API for calling from server action.
Equivalent API for calling from route handler.
For implementation, I believe using
AsyncLocalStorage(similarly as forcookies()andheaders()) should be achievable. The store could have the shape of a mutableMap<string /* store ID */, unknown /* store current value */>, where each store gets its own unique ID at creation. The AsyncLocalStorage context is then provided to each Next.js request in every execution context.Beta Was this translation helpful? Give feedback.
All reactions