Home >Web Front-end >JS Tutorial >Async Local Storage is Here to Help You

Async Local Storage is Here to Help You

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 22:22:14700browse

When you hear the phrase "Async Local Storage," what comes to mind? You might initially think it refers to some magical implementation of browser-based local storage. However, this assumption is incorrect. Async Local Storage is neither browser-related nor a typical storage mechanism. Probably one or two libraries you have used use it under the hood. In many cases, this feature can save you from dealing with messy code.

What is Async Local Storage?

Async Local Storage is a feature introduced in Node.js, initially added in versions v13.10.0 and v12.17.0, and later stabilized in v16.4.0. It is part of the async_hooks module, which provides a way to track asynchronous resources in Node.js applications. The feature enables the creation of a shared context that multiple asynchronous functions can access without explicitly passing it. The context is available in every (and only) operation executed within the callback passed to the run() method of the AsyncLocalStorage instance.

A pattern for using AsyncLocalStorage

Before diving into the examples, let’s explain the pattern we will be using.

Initialization

import { AsyncLocalStorage } from "async_hooks";
import { Context } from "./types";

export const asyncLocalStorage = new AsyncLocalStorage<Context>();

// export const authAsyncLocalStorage = new AuthAsyncLocalStorage<AuthContext>()

In the module above, we initialize an instance of AsyncLocalStorage and export it as a variable.

Usage

asyncLocalStorage.run({ userId }, async () => {
  const usersData: UserData = await collectUsersData();
  console.log("usersData", usersData);
});

// (method) AsyncLocalStorage<unknown>.run<Promise<void>>(store: unknown, callback: () => Promise<void>): Promise<void> (+1 overload)

The run() method takes two arguments: storage, which contains the data we want to share, and callback, where we place our logic. As a result, the storage becomes accessible in every function call within the callback, allowing for seamless data sharing across asynchronous operations.

async function collectUsersData() {
  const context = asyncLocalStorage.getStore();
}

To access the context, we import our instance and call the asyncLocalStorage.getStore() method. The great thing is that the storage retrieved from getStore() is typed because we passed the Context type to AsyncLocalStorage during initialization: new AsyncLocalStorage().

Async Local Storage as an auth context

There is no web application without an authentication system. We must validate auth tokens and extract user information. Once we obtain the user identity, we want to make it available in the route handlers and avoid duplicating code in each one. Let’s see how we can utilize AsyncLocalStorage to implement an auth context while keeping our code clean.

I chose fastify for this example.

According to the documentation fastify is:

Fast and low overhead web framework, for Node.js

Ok, let's get started:

  1. Install fastify:
import { AsyncLocalStorage } from "async_hooks";
import { Context } from "./types";

export const asyncLocalStorage = new AsyncLocalStorage<Context>();

// export const authAsyncLocalStorage = new AuthAsyncLocalStorage<AuthContext>()
  1. Define type for our auth context:
asyncLocalStorage.run({ userId }, async () => {
  const usersData: UserData = await collectUsersData();
  console.log("usersData", usersData);
});

// (method) AsyncLocalStorage<unknown>.run<Promise<void>>(store: unknown, callback: () => Promise<void>): Promise<void> (+1 overload)
  1. Initialize an instance of AsyncLocalStorage, assign it to a variable, and export the variable. Remember to pass the relevant type: new AsyncLocalStorage().
async function collectUsersData() {
  const context = asyncLocalStorage.getStore();
}
  1. Initialize a Fastify instance and add a utility for error handling:
npm install fastify

Now comes the very important part. We are going to add an onRequest hook to wrap handlers with the authAsyncLocalStorage.run() method.

type Context = Map<"userId", string>;

After successful validation, we call the run() method from our authAsyncLocalStorage. As the storage argument, we pass the auth context with the userId retrieved from the token. In the callback, we call the done function to continue with the Fastify lifecycle.

If we have authentication checks that require asynchronous operations, we should add them to the callback. This is because, according to the documentation:

the done callback is not available when using async/await or returning a Promise. If you do invoke a done callback in this situation unexpected behavior may occur, e.g. duplicate invocation of handlers

Here's an example of how that might look:

import { AsyncLocalStorage } from "async_hooks";
import { Context } from "./types";

export const authAsyncLocalStorage = new AsyncLocalStorage<Context>();

Our example has only one protected route. In more complex scenarios, you might need to wrap only specific routes with the authentication context. In such cases, you could either:

  1. Wrap the onRequest hook in a custom plugin that's applied only to specific routes.
  2. Add route distinction logic within the onRequest hook itself.

All right, our context is set and we can now define a protected route:

import Fastify from "fastify";

/* other code... */

const app = Fastify();

function sendUnauthorized(reply: FastifyReply, message: string) {
  reply.code(401).send({ error: `Unauthorized: ${message}` });
}

/* other code... */

The code is pretty straightforward. We import authAsyncLocalStorage, retrieve the userId, initialize UserRepository, and fetch data. This approach keeps the route handler clean and focused.

Exploring How Next.js uses Async Local Storage

In this example, we'll reimplement the cookies helper from Next.js. But wait—this is a post about AsyncLocalStorage, right? So why are we talking about cookies? The answer is simple: Next.js uses AsyncLocalStorage to manage cookies on the server. That's why reading a cookie in a server component is as easy as:

import Fastify from "fastify";
import { authAsyncLocalStorage } from "./context";
import { getUserIdFromToken, validateToken } from "./utils";

/* other code... */

app.addHook(
  "onRequest",
  (request: FastifyRequest, reply: FastifyReply, done: () => void) => {
    const accessToken = request.headers.authorization?.split(" ")[1];
    const isTokenValid = validateToken(accessToken);
    if (!isTokenValid) {
      sendUnauthorized(reply, "Access token is invalid");
    }
    const userId = accessToken ? getUserIdFromToken(accessToken) : null;

    if (!userId) {
      sendUnauthorized(reply, "Invalid or expired token");
    }
    authAsyncLocalStorage.run(new Map([["userId", userId]]), async () => {
      await new Promise((resolve) => setTimeout(resolve, 2000));
      sendUnauthorized(reply, "Invalid or expired token");
      done();
    });
  },
);

/* other code... */

We use the cookies function exported from next/headers, which provides several methods for managing cookies. But how is this technically possible?

Now it's time to start our re-implementation"

First, I want to mention that this example is based on the knowledge I gained from a great video, by Lee Robinson and diving in the Next.js repository.

In this example, we'll use Hono as our server framework. I chose it for two reasons:

  1. I just wanted to give it a try.
  2. It offers solid support for JSX.

First install Hono:

import { AsyncLocalStorage } from "async_hooks";
import { Context } from "./types";

export const asyncLocalStorage = new AsyncLocalStorage<Context>();

// export const authAsyncLocalStorage = new AuthAsyncLocalStorage<AuthContext>()

Now, initialize Hono and add middleware:

asyncLocalStorage.run({ userId }, async () => {
  const usersData: UserData = await collectUsersData();
  console.log("usersData", usersData);
});

// (method) AsyncLocalStorage<unknown>.run<Promise<void>>(store: unknown, callback: () => Promise<void>): Promise<void> (+1 overload)

The code resembles the middleware from the Fastify example, does it? To set the context, we utilize setCookieContext, which is imported from the cookies module — our custom simple implementation of the cookies function. Let's follow the setCookieContext function and navigate to the module from which it was imported:

async function collectUsersData() {
  const context = asyncLocalStorage.getStore();
}

The setCookieContext function (whose return value we passed to cookieAsyncLocalStorage.run() in the Hono middleware) extracts cookies from the c parameter, which represents the hono context, and bundles them with closures that provide utility functions for managing cookies.

Our cookies function replicates the functionality of the cookies from next/headers. It utilizes the cookieAsyncLocalStorage.getStore() method to access the same context that is passed to cookieAsyncLocalStorage.run() when it is called.

We wrapped the return of our cookies function in a promise to mimic the behavior of the Next.js implementation. Prior to version 15, this function was synchronous. Now, in the current Next.js code, the methods returned by the cookies are attached to a promise object, as shown in the following simplified example:

npm install fastify

Another point worth mentioning is that in our case, using cookies.setCookie and cookies.deleteCookie always throws an error, similar to the behavior observed in Next.js when setting cookies in a server component. We hardcoded this logic because, in the original implementation, whether we can use setCookie or deleteCookie depends on the phase(WorkUnitPhase) property stored in the storage called RequestStore(this is the implementation of AsyncLocalStorage and also stores cookies). However, that topic is better suited for another post. To keep this example simple, let's omit the simulation of WorkUnitPhase.

Now we need to add our React code.

  1. Add the App component:
type Context = Map<"userId", string>;
  1. Add a component for managing cookies:
import { AsyncLocalStorage } from "async_hooks";
import { Context } from "./types";

export const authAsyncLocalStorage = new AsyncLocalStorage<Context>();

The usage of cookies is similar to how it is used in Next.js React server components.

  1. Add a route handler to render the template:
import Fastify from "fastify";

/* other code... */

const app = Fastify();

function sendUnauthorized(reply: FastifyReply, message: string) {
  reply.code(401).send({ error: `Unauthorized: ${message}` });
}

/* other code... */

Our template is rendered by the html method from the hono context. The key point here is that the route handler runs within the asyncLocalStorage.run() method, which takes cookieContext. As a result, we can access this context in the DisplayCookies component through the cookies function.

It is not possible to set cookies inside React server components, so we need to do it manually:

Async Local Storage is Here to Help You

Let's refresh a page:

Async Local Storage is Here to Help You

And here we are, our cookies are successfully retrieved and displayed.

Conclusions

There are many more use cases for asyncLocalStorage. This feature allows you to build custom contexts in nearly any server framework. The asyncLocalStorage context is encapsulated within the execution of the run() method, making it easy to manage. It’s perfect for handling request-based scenarios. The API is simple and flexible, enabling scalability by creating instances for each state. It is possible to seamlessly maintain separate contexts for things like authentication, logging, and feature flags.

Despite its benefits, there are a few considerations to keep in mind. I've heard opinions that asyncLocalStorage introduces too much 'magic' into the code. I'll admit that when I first used this feature, it took me some time to fully grasp the concept. Another thing to consider is that importing the context into a module creates a new dependency that you’ll need to manage. However, in the end, passing values through deeply nested function calls is much worse.

Thanks for reading, and see you in the next post!?

PS: You can find the examples(plus one bonus) here

Bog Post source: https://www.aboutjs.dev/en/async-local-storage-is-here-to-help-you

The above is the detailed content of Async Local Storage is Here to Help You. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn