@sprout-idws/sprout-context
v1.0.2
Published
Reusable NestJS request context (AsyncLocalStorage) for auth and propagation
Downloads
5
Maintainers
Readme
@sprout-idws/sprout-context
Request-scoped context for NestJS using Node’s AsyncLocalStorage: store and read userId, roles, and related auth data for the current HTTP request without explicit parameter threading.
Purpose
- Share authentication context with services, guards, and interceptors deep in the call stack.
- Encode/decode context for propagation (for example across internal boundaries) via base64 JSON helpers.
Installation
npm install @sprout-idws/sprout-contextPeer dependency: @nestjs/common (v10+).
Usage
1. Register the global module
import { Module } from '@nestjs/common';
import { ContextModule } from '@sprout-idws/sprout-context';
@Module({
imports: [ContextModule],
})
export class AppModule {}ContextModule is @Global() and provides ContextService and ContextMiddleware.
2. Apply the middleware
Mount ContextMiddleware on your HTTP app (for example in main.ts) so each request runs inside a context store. @sprout-idws/sprout-nestjs-application applies this middleware when you use SproutApiApplicationModule.
3. Use ContextService
run(context, callback)— execute code with a fresh ALS store.set(partial)— merge into the current store (orenterWithif none).getContext()/getRequiredContext()— readAuthContext; required variant throwsUnauthorizedExceptionif missing.getCurrentEncodedContext()/getDecodedContext/getEncodedContext— serializeAuthContextas base64 JSON for optional propagation.
AuthContext shape:
interface AuthContext {
userId?: string;
roles?: string[];
}Relationship to other Sprout packages
@sprout-idws/sprout-nestjs-application— JWT guard sets context after successful auth.@sprout-idws/sprout-redis— depends onContextModulefor user-scoped behavior where applicable.
Repository
sprout-typescript-backend — packages/sprout-context.
