npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@aragaoi/context-storage

v1.2.2

Published

Generic AsyncLocalStorage wrapper for context management

Readme

@aragaoi/context-storage

Coverage Version

Documentation: This package is a wrapper around Node.js AsyncLocalStorage. For a detailed explanation of how AsyncLocalStorage works, see our AsyncLocalStorage Guide.

  • 🔒 Type-safe: Full TypeScript support with generics
  • 🚀 Zero dependencies: Only uses Node.js built-ins
  • 🧹 Automatic cleanup: Context is automatically cleaned up after async operations
  • 🎯 Simple API: Easy to use with minimal boilerplate
  • 🔄 Async support: Works seamlessly with async/await

Installation

npm install context-storage

Quick Start

Basic Usage

import { ContextStorage } from "context-storage";

// Create a context storage for user data
const userContext = new ContextStorage(() => ({
  userId: "",
  role: "guest"
}));

// Use context in your application
userContext.runWithContext(() => {
  // Set user data
  userContext.updateContext({ userId: "user-123", role: "admin" });
  
  // Access context anywhere in this scope
  const user = userContext.getContext();
  console.log(user); // { userId: "user-123", role: "admin" }
});

Request Context (Pre-configured)

import { requestContextStorage } from "context-storage";

// Use the pre-configured request context
requestContextStorage.runWithContext(() => {
  // Add user info to context
  requestContextStorage.updateContext({
    userId: "user-123",
    tenantId: "tenant-456"
  });
  
  // Access request context anywhere
  const context = requestContextStorage.getContext();
  console.log(context.requestId); // Unique request ID
  console.log(context.userId); // "user-123"
});

API Reference

ContextStorage

Constructor

new ContextStorage<T>(contextFactory: () => T, contextName?: string)

Methods

  • runWithContext<T>(callback: () => T): T - Run code within a context
  • getContext(): T | null - Get current context (nullable)
  • getContextOrThrow(): T - Get current context (throws if missing)
  • updateContext(partial: Partial<T>): void - Update current context

RequestContext

Pre-configured context type for HTTP requests:

type RequestContext = {
  requestId: string;
  userId?: string;
  tenantId?: string;
  startedAt: string;
  startedAtTimestamp: number;
  token?: string;
};

Examples

Express.js Middleware

import { requestContextStorage } from "context-storage";

app.use((req, res, next) => {
  requestContextStorage.runWithContext(() => {
    // Add request data to context
    requestContextStorage.updateContext({
      userId: req.user?.id,
      token: req.headers.authorization
    });
    
    next();
  });
});

// In your route handlers
app.get("/api/data", (req, res) => {
  const context = requestContextStorage.getContextOrThrow();
  console.log(`Request ${context.requestId} from user ${context.userId}`);
  // ... handle request
});

Database Operations

import { ContextStorage } from "context-storage";

const dbContext = new ContextStorage(() => ({
  transactionId: "",
  userId: ""
}));

async function createUser(userData: any) {
  return dbContext.runWithContext(async () => {
    dbContext.updateContext({
      transactionId: generateId(),
      userId: userData.id
    });
    
    // All database operations have access to context
    await db.beginTransaction();
    await db.insertUser(userData);
    await db.logActivity("user_created");
    await db.commit();
  });
}

Requirements

  • Node.js 16.0.0 or higher
  • TypeScript (recommended)

License

MIT