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

Async Local Storage is Here to Help You

Dec 22, 2024 pm 10:22 PM

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>()
Copy after login
Copy after login
Copy after login

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)
Copy after login
Copy after login
Copy after login

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();
}
Copy after login
Copy after login
Copy after login

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>()
Copy after login
Copy after login
Copy after login
  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)
Copy after login
Copy after login
Copy after login
  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();
}
Copy after login
Copy after login
Copy after login
  1. Initialize a Fastify instance and add a utility for error handling:
npm install fastify
Copy after login
Copy after login

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>;
Copy after login
Copy after login

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>();
Copy after login
Copy after login

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... */
Copy after login
Copy after login

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... */
Copy after login

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>()
Copy after login
Copy after login
Copy after login

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)
Copy after login
Copy after login
Copy after login

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();
}
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login

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>;
Copy after login
Copy after login
  1. Add a component for managing cookies:
import { AsyncLocalStorage } from "async_hooks";
import { Context } from "./types";

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

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... */
Copy after login
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Apr 04, 2025 pm 02:09 PM

Data update problems in zustand asynchronous operations. When using the zustand state management library, you often encounter the problem of data updates that cause asynchronous operations to be untimely. �...

See all articles