Ryan Florence released this a few months ago:

A lightweight, type-safe async context management system for JavaScript applications. Perfect for server-side applications where you need to share request-scoped values across components and functions.

This is a small wrapper on top of AsyncLocalStorage to provide a simple and type-safe API for request scoped values.

This is expected to be the recommended solution for type-safe context in upcoming React Router middleware.

import { createContext, provide, pull } from "@ryanflorence/async-provider";

// 1. ✅ Create your contexts
let userContext = createContext<User>();
let dbContext = createContext<Database>();

async function myHandleRequest(req: Request) {
  // setup context values
  let user = await myAuthenticateUser(req);
  let db = myCreateDatabaseConnection(user);

  // 2. ✅ Provide contexts
  let html = await provide(
    new Map([
      [userContext, user],
      [dbContext, db],
    ]),
    async () => {
      // run your app code within this context
      let result = await renderApp();
      // Can return values from provider callback
      return result;
    },
  );

  return new Response(html, {
    headers: { "Content-Type": "text/html" },
  });
}

// 3. ✅ Pull context from anywhere
function renderApp() {
  let user = pull(userContext);
  let db = pull(dbContext);

  // Use user and db...
}

Leave a Reply

Your email address will not be published. Required fields are marked *

More Technology Knowledge Updates…