Skip to main content

Async Context Middleware

Request-scoped async context middleware that stores each request context in AsyncLocalStorage so utilities can access it anywhere in the same async call stack.

Installation

npm i remix

Functions

asyncContext()

Creates middleware that stores the request context in AsyncLocalStorage. Signature:
function asyncContext(): Middleware
Returns: A middleware function that stores the request context in AsyncLocalStorage. Example:
import { createRouter } from 'remix/fetch-router'
import { asyncContext, getContext } from 'remix/async-context-middleware'

let router = createRouter({
  middleware: [asyncContext()],
})

router.get('/users/:id', async () => {
  // Access context from anywhere in the async call stack
  let context = getContext()
  let userId = context.params.id

  return new Response(`User ${userId}`)
})

getContext()

Retrieves the request context from AsyncLocalStorage. Signature:
function getContext(): RequestContext
Returns: The current request context. Throws: Error if no request context is found (middleware not installed). Example:
import { getContext } from 'remix/async-context-middleware'

async function getUserFromContext() {
  let context = getContext()
  let userId = context.params.id
  return fetchUser(userId)
}

Usage with Router

import { createRouter } from 'remix/fetch-router'
import { asyncContext, getContext } from 'remix/async-context-middleware'

let router = createRouter({
  middleware: [asyncContext()],
})

// Helper function that can access context from anywhere
function getCurrentUserId(): string {
  let context = getContext()
  return context.params.id as string
}

router.get('/users/:id/posts', async () => {
  let userId = getCurrentUserId()
  let posts = await fetchUserPosts(userId)
  return Response.json({ posts })
})

Requirements

This middleware requires support for node:async_hooks.

Build docs developers (and LLMs) love