@vitkuz/lambda-async-context
v1.0.0
Published
AsyncLocalStorage-based context framework for AWS Lambda
Maintainers
Readme
@vitkuz/lambda-async-context
An AsyncLocalStorage-based context framework for AWS Lambda. This package enables robust context hydration in deep service layers without passing variables manually through function signatures.
Using this library helps enforce strict boundaries in 3-Tier serverless functional architecture (Handlers -> Use Cases -> Services) by providing standard injection containers for Execution (initEnvContext) and Invocation (withLambdaContext).
Documentation & Handlers
AWS Lambda functions receive different shapes of event and context variables depending on their invocation trigger. Check out our detailed usage examples for each major AWS Event Source below:
- API Gateway (REST / HTTP)
- DynamoDB Streams
- Simple Notification Service (SNS)
- Simple Queue Service (SQS)
- Simple Storage Service (S3)
- CloudWatch Scheduled Events (Cron) / EventBridge Scheduler
- EventBridge / Event Bus
Advanced Integration: AWS Request ID Extractor
If you're using @vitkuz/aws-request-id-extractor to trace identifiers recursively across event payloads, we have pre-written examples combining both tools seamlessly:
- API Gateway (REST / HTTP)
- DynamoDB Streams
- Simple Notification Service (SNS)
- Simple Queue Service (SQS)
- Simple Storage Service (S3)
- CloudWatch Scheduled Events (Cron) / EventBridge Scheduler
- EventBridge / Event Bus
Example (Quick Start)
import { createLambdaContext } from '@vitkuz/lambda-async-context';
export const ctx = createLambdaContext();
async function myService() {
const { logger } = ctx.getEnvContext();
const { traceId } = ctx.getRequestContext();
logger.info(`Validating user info for request ${traceId}`);
}
// Use a factory function to build the Context Meta extraction block
const buildThisLambdaContext = () => {
return async (e, c) => {
// Init happens once per cold start, cached internally
await ctx.initEnvContext(() => ({ logger: console }));
return { traceId: c.awsRequestId };
};
};
export const handler = ctx.withLambdaContext(buildThisLambdaContext(), async (event, context) => {
await myService();
});