commoneventframework
v1.0.21
Published
Common Event Framework for Lambda AWS
Readme
Common Event Framework (CEF)
A Node.js framework for AWS Lambda that normalizes different AWS event types (API Gateway v1/v2, S3, SQS, SNS, direct invocation) into a single CommonEvent object, and automatically routes requests to handlers declared in an OpenAPI YAML file.
Installation
npm install commoneventframeworkAfter install, the package exposes executable commands via npx or npm scripts (see Framework CLI).
Framework CLI
These commands are declared in the commoneventframework package bin field. Run them from your Lambda project root (where package.json and src/ live).
| Command | Purpose |
|--------|---------|
| cef-init | Scaffolds a new project: src/index.ts, src/root.yaml, src/handlers/, sample HandlerRegistry, tsconfig.json, etc. |
| cef-gen-handlers | Reads src/root.yaml and regenerates src/generated/HandlerRegistry.ts (static imports + HandlerRegistry.register()). Required so esbuild bundles every handler referenced in YAML. |
| cef-build | Runs codegen (unless --skip-codegen), then esbuild on src/index.ts → dist/index.js, copies root.yaml and package.json into dist/, and writes dist/build-info.json (Node version, build time, author — CodeBuild initiator when the build runs there). |
| cef-build --full | Same as cef-build, then zips the whole dist/ folder to dist/dist.zip for Lambda upload. |
Typical flags
| Flag | Applies to | Meaning |
|------|------------|---------|
| --yaml <path> | cef-gen-handlers | OpenAPI file (default: src/root.yaml) |
| --out <path> | cef-gen-handlers | Output TS file (default: src/generated/HandlerRegistry.ts) |
| --skip-codegen | cef-build | Skip regenerating HandlerRegistry.ts (e.g. YAML unchanged, faster CI step) |
Example package.json scripts
{
"scripts": {
"codegen": "cef-gen-handlers",
"build": "cef-build",
"build:full": "cef-build --full"
}
}npm run codegen— refresh the handler registry only (useful right after editingroot.yamlbefore running TypeScript or tests).npm run build— codegen + bundle;npm run build:full— codegen + bundle + zip.
Handler registry generation
For a single-file Lambda bundle, every handler and input parser referenced in root.yaml must be reachable through static import. The framework cannot rely on dynamic require("handlers/...") after esbuild.
What gets generated
cef-gen-handlersparsespaths.*.*inroot.yaml, collects everyx-handlerandx-inputParservalue (strings likehandlers/foo#bar), and writessrc/generated/HandlerRegistry.ts.That file defines a class
HandlerRegistrywithstatic register(), which callsregisterHandlerRefs(...)from the framework with one entry per ref, using namespace imports (import * as __cef_handlers_* from "../handlers/...").The generated file ends with
HandlerRegistry.register()so your entry point only needs:import "./generated/HandlerRegistry";(after
await loadEnv()orconst envReady = loadEnv()), in addition to your main handler logic.
Workflow
- Add or change routes in
src/root.yaml(x-handler/x-inputParserpointing at existing exports undersrc/handlers/). - Run
npx cef-gen-handlersornpm run codegen, or letcef-buildrun codegen for you. - Implement the handler/parser in TypeScript; keep the
file#exportNamestring in YAML in sync with the file path and export. - Run
cef-build/npm run buildbefore deploy.
Do not hand-edit HandlerRegistry.ts — it is overwritten on the next codegen. Commit it to git if you want CI and IDEs to see a consistent file without running codegen on every clone (optional; many teams regenerate in CI).
Initialize a project
The cef-init command automatically scaffolds a ready-to-use project structure:
npx cef-initThis creates the following files in the current directory:
my-lambda/
├── src/
│ ├── index.ts # Lambda entry point
│ ├── generated/
│ │ └── HandlerRegistry.ts # AUTO-GENERATED class (cef-gen-handlers / build)
│ ├── root.yaml # OpenAPI route definitions
│ └── handlers/
│ ├── types.ts # HandlerFn / InputParserFn types
│ └── hello.ts # Example handler (GET /hello, GET /hello/:name)
├── .env
├── package.json
└── tsconfig.jsonExisting files are not overwritten. Use --force to overwrite:
npx cef-init --forceThen:
npm install
npm run codegen # optional: refresh HandlerRegistry from root.yaml (also runs inside npm run build)
npm run dev # local server on localhost:8888
npm run build:full # codegen + bundle + ZIP for AWS LambdaQuick start (manual)
1. Create the root.yaml file
Create a root.yaml file next to your entry point (src/index.ts). It is a standard OpenAPI 3.0 document, extended with two custom properties:
x-handler: reference to the handler function using thefile#functionformatx-inputParser(optional): reference to the input parsing/validation function
openapi: 3.0.3
info:
title: My API
version: 1.0.0
paths:
/hello:
get:
x-handler: handlers/hello#getHello
summary: Returns a welcome message
responses:
'200':
description: Success
/users/:id:
get:
x-handler: handlers/users#getUser
x-inputParser: handlers/users#parseGetUserInput
summary: Get a user by ID
parameters:
- in: path
name: id
required: true
schema:
type: string
responses:
'200':
description: User found
'400':
description: Missing parameter
'404':
description: User not foundNote: path parameters use the
:paramsyntax (e.g./users/:id), compatible with thepath-parsermatching engine.
2. Create the entry point src/index.ts
Register generated handlers (see Handler registry generation); then wire the main Lambda handler:
import { loadEnv } from "commoneventframework";
const envReady = loadEnv();
import "./generated/HandlerRegistry";
import {
APIGatewayProxyStructuredResultV2,
Context,
buildCommonEvent,
getRouteConfig,
resolveHandlerRef,
Response,
setLambdaContext,
startDevServer
} from "commoneventframework";
import { CommonEvent, LambdaEvent } from "commoneventframework/dist/types/commonEvent";
export const handler = async (
event: LambdaEvent,
context: Context
): Promise<APIGatewayProxyStructuredResultV2> => {
await envReady;
await setLambdaContext(context);
const commonEvent: CommonEvent = await buildCommonEvent(event);
try {
const routeConfig = getRouteConfig(commonEvent);
if (!routeConfig || !routeConfig.handler) {
return new Response(404, { error: "Route not found" });
}
const handlerFn = resolveHandlerRef(routeConfig.handler);
const parserFn = routeConfig.inputParser
? resolveHandlerRef(routeConfig.inputParser)
: undefined;
if (!handlerFn) {
return new Response(500, { error: `Handler "${routeConfig.handler}" not found` });
}
const input = parserFn ? parserFn(commonEvent) : {};
if (input instanceof Response) return input;
const result = await handlerFn(input, commonEvent);
if (result && 'statusCode' in result) {
return result as APIGatewayProxyStructuredResultV2;
}
return new Response(200, result as object);
} catch (err) {
return new Response(500, err as object);
}
};
// Local development server
if (process.argv.includes("--local")) {
startDevServer(handler);
}3. Define handlers
Each handler is a TypeScript file in src/handlers/ that exports a handler function and optionally an inputParser function. Whenever you add or change x-handler / x-inputParser in root.yaml, run cef-gen-handlers (or cef-build) so src/generated/HandlerRegistry.ts stays in sync — see Handler registry generation.
Types
import { CommonEvent } from "commoneventframework/dist/types/commonEvent";
import { APIGatewayProxyStructuredResultV2 } from "commoneventframework";
type InputParserFn = (event: CommonEvent) => any;
type HandlerFn = (input: any, event: CommonEvent) => Promise<APIGatewayProxyStructuredResultV2 | object>;Example: src/handlers/hello.ts
import { HandlerFn } from "./types";
export const getHello: HandlerFn = async () => {
return { message: "Hello, World!" };
};The result is automatically wrapped in a Response(200, ...) by the entry point.
Example with inputParser: src/handlers/users.ts
import { CommonEvent } from "commoneventframework/dist/types/commonEvent";
import { Response } from "commoneventframework";
import { InputParserFn, HandlerFn } from "./types";
interface GetUserInput {
id: string;
}
export const parseGetUserInput: InputParserFn = (event: CommonEvent) => {
const id = event.pathParameters?.id;
if (!id) {
return new Response(400, { error: "Missing path parameter: id" });
}
return { id } as GetUserInput;
};
export const getUser: HandlerFn = async (input: GetUserInput) => {
// ... business logic
return { user: { id: input.id, name: "John" } };
};Validation: if the inputParser returns a
Responseinstance (e.g.new Response(400, ...)), it is sent directly to the client without calling the handler.
Key concepts
CommonEvent
All AWS events are normalized into a CommonEvent object:
type CommonEvent = {
path: string;
method: string;
body: string | null;
pathParameters: { [name: string]: string | undefined } | undefined;
queryStringParameters: { [name: string]: string | undefined } | undefined;
headers: { [name: string]: string | undefined } | undefined;
cookies?: { [name: string]: string | undefined } | undefined;
isBase64Encoded?: boolean;
version: string;
};The version field indicates the event source ("1.0" for API Gateway v1, "2.0" for v2, "commonEvent" for the dev server, etc.).
Supported events
| AWS Source | method | path |
|---------------------|-------------------|-------------------------|
| API Gateway v1 | HTTP method | Resource path |
| API Gateway v2 | HTTP method | Route key |
| SQS | PUT | /sqs/{queueName} |
| S3 | PUT | /s3/{bucketName} |
| SNS -> S3 | PUT | /s3/{bucketName} |
| Direct invocation | PUT | path from the event |
file#function resolution
References in root.yaml use the same string for handlers and input parsers, e.g. handlers/search#searchProducts.
Bundled Lambda: use the generated registry — see Handler registry generation and the Framework CLI (cef-gen-handlers, cef-build). After const envReady = loadEnv(), import the generated module:
import "./generated/HandlerRegistry";cef-build accepts --skip-codegen if you bundle without regenerating HandlerRegistry.ts.
Fallback: if a ref is not registered, the framework tries require() from the entry directory, then parent directories, then process.cwd().
Response class
Wrapper around APIGatewayProxyStructuredResultV2 that automatically adds CORS headers:
import { Response } from "commoneventframework";
new Response(200, { data: "ok" });
new Response(400, { error: "Bad request" });
new Response(500, { error: "Internal error" }, { "X-Custom": "value" });Default CORS headers:
Access-Control-Allow-Origin: value ofprocess.env.FRONT_END_URLor*Access-Control-Allow-Methods:OPTIONS,GET,POST,PUT,DELETEAccess-Control-Allow-Credentials:trueContent-Type:application/json
Built-in routes
The framework automatically registers these routes:
| Route | Description |
|---------------------|-----------------------------------------------|
| GET /doc | Swagger UI (powered by Scalar) |
| GET /doc/spec | OpenAPI specification as JSON |
| GET /context | Lambda context information |
| GET /dependencies | Project dependencies from package.json |
| GET /info | Build snapshot: Node version, when it was built, and who started it |
| POST /parameter-store/flush | Clears the Parameter Store alias cache and reloads SSM |
| POST /parameter-store/reload | Force-reloads one key (?key=NAME) or every key from SSM |
GET /info reads dist/build-info.json, written by cef-build and included in dist/dist.zip. The Node version is the one that ran the build. builtAt is the time cef-build wrote the file. builtBy is CODEBUILD_INITIATOR when CodeBuild started the build (IAM user, codepipeline/<name>, or the integration that triggered it). A webhook also stores codebuild.webhookActorAccountId. Outside CodeBuild, builtBy is the OS user (USERNAME or USER) and codebuild is null.
{
"nodeVersion": "v22.14.0",
"builtAt": "2026-11-11T14:06:00.000Z",
"builtBy": "codepipeline/my-pipeline",
"codebuild": {
"buildId": "my-project:abc123",
"initiator": "codepipeline/my-pipeline",
"startedAt": "2026-11-11T14:05:12.000Z",
"sourceVersion": "main",
"resolvedSourceVersion": "a1b2c3d",
"region": "eu-west-1"
}
}Local development
The framework includes an HTTP server that simulates API Gateway.
Start the server
node dist/index.js --local
# or with ts-node / nodemon
npx ts-node src/index.ts --local --port 8088The server starts on localhost:8888 by default (configurable via the 3rd process.argv argument).
Simulate different event types
The dev server intercepts special URLs to simulate AWS event sources:
| Server URL | Simulated event type |
|------------------|-------------------------|
| POST /invoke | Direct Lambda invocation|
| POST /sqs | SQS message |
| POST /s3event | S3 event |
| Any other URL | API Gateway (CommonEvent)|
Build and deployment
Summary: cef-build = codegen + esbuild + copy root.yaml and package.json into dist/ + write dist/build-info.json; cef-build --full = same + dist/dist.zip. Details: Framework CLI, Handler registry generation.
npx cef-build
npx cef-build --full
npx cef-build --skip-codegenRecommended package.json scripts:
{
"scripts": {
"codegen": "cef-gen-handlers",
"build": "cef-build",
"build:full": "cef-build --full"
}
}The build regenerates src/generated/HandlerRegistry.ts from root.yaml, bundles src/index.ts → dist/index.js, copies src/root.yaml → dist/root.yaml and package.json → dist/package.json (so GET /dependencies can read dependency metadata when the Lambda handler is dist/index.js), writes dist/build-info.json (so GET /info can report the Node version, build time and author), then optionally creates dist/dist.zip for AWS Lambda.
Utilities
The package also exposes a few utilities:
loadEnv()
Loads .env and .env.local from the current working directory. Must be called before any import that depends on environment variables.
loadEnv() is async. On local development, it also loads AWS Parameter Store parameters when enabled. On Lambda, Parameter Store is loaded later via setLambdaContext (alias taken from the invocation).
import { loadEnv } from "commoneventframework";
const envReady = loadEnv();
export const handler = async (event, context) => {
await envReady;
await setLambdaContext(context);
// ...
};Existing process.env values (.env, Lambda console) are never overwritten by Parameter Store values.
setLambdaContext(context)
Stores the Lambda context (built-in route GET /context), applies alias-prefixed environment variables, and when Parameter Store is enabled, caches SSM parameters for dev, prod, and the alias of the current invocation (extracted from context.invokedFunctionArn, e.g. prod, staging). Only the invocation alias is copied into process.env.
await setLambdaContext(context);dev, prod, and the active alias are each loaded once per warm container. A later invoke only switches which cached alias is applied.
Alias-prefixed environment variables
Store environment-specific values in .env using the {alias}_{VARIABLE} naming convention. At runtime, CEF resolves them for the active alias and exposes the unprefixed name in process.env.
.env example
ALIAS=dev
dev_URL_de_la_database=localhost
prod_URL_de_la_database=prod-db.example.comWith ALIAS=dev, after loadEnv():
process.env.URL_de_la_database→localhost(fromdev_URL_de_la_database)
On Lambda invoked via alias prod, after setLambdaContext(context):
process.env.URL_de_la_database→prod-db.example.com(fromprod_URL_de_la_database)
Unprefixed values already set (.env, Lambda console, SSM) are not overwritten.
Read a value explicitly
import { getAliasEnvValue } from "commoneventframework";
const dbUrl = getAliasEnvValue("URL_de_la_database"); // uses current alias
const prodDbUrl = getAliasEnvValue("URL_de_la_database", "prod"); // force alias "prod", including values cached from Parameter StoreWhen resolution runs
| Step | Alias source |
|------|----------------|
| loadEnv() | ALIAS / STAGE / ENV, default local |
| setLambdaContext(context) | Lambda alias from invokedFunctionArn |
getEnvValue(key, fallback?)
Retrieves an environment variable. Throws an error if the variable is missing and no fallback is provided.
import { getEnvValue } from "commoneventframework/dist/utils/getEnvValue";
const dbHost = getEnvValue("DB_HOST", "localhost");AWS Parameter Store (SSM)
Optional integration with AWS Systems Manager Parameter Store. Parameters are injected into process.env at runtime.
Disabled by default — set PARAMETER_STORE_ENABLED=true to activate.
Parameter path layout
/{alias}/{lambdaName}/{VARIABLE_NAME}| Segment | Source |
|---------|--------|
| alias | Lambda alias from invocation (invokedFunctionArn), or ALIAS / STAGE / ENV locally, default local |
| lambdaName | AWS_LAMBDA_FUNCTION_NAME on Lambda, or LAMBDA_NAME in .env locally |
| VARIABLE_NAME | Stored in the alias cache. The active alias is also copied to process.env.VARIABLE_NAME |
Examples
| Parameter Store name | Where it lands |
|----------------------|----------------|
| /local/my-api/DB_HOST | Cache alias local. Copied to process.env.DB_HOST only while local is active |
| /dev/my-api/API_KEY | Cache alias dev, even when another alias is active |
| /prod/my-api/API_KEY | Cache alias prod, even when another alias is active |
Parameter names must start with / and use only letters, numbers, ., -, _ in each path segment.
Environment variables
| Variable | Required | Description |
|----------|----------|-------------|
| PARAMETER_STORE_ENABLED | Yes (to enable) | true or 1 |
| AWS_REGION | Yes (when SSM enabled) | AWS region |
| LAMBDA_NAME | Local only | Lambda name for the SSM path |
| ALIAS | Local only (optional) | Defaults to local |
| AWS_LAMBDA_FUNCTION_NAME | Lambda (automatic) | Set by AWS |
On Lambda you do not need ALIAS in environment variables — the alias comes from the Lambda alias used at invoke time.
Loading flow
loadEnv()(module startup):.env/.env.local. When Parameter Store is enabled, caches/dev/{lambdaName}/,/prod/{lambdaName}/, and/{activeAlias}/{lambdaName}/. Locally, the active alias is applied toprocess.env. On Lambda, that apply waits forsetLambdaContext.setLambdaContext(context): applies the invocation alias from the cache. If that alias was not preloaded (staging,local, …), its path is loaded first.
dev and prod are always cached, whichever alias is active. Every parameter under those paths is kept. A later invoke with an alias already in the cache does not call SSM again; it only reapplies that alias to process.env. POST /parameter-store/flush clears the cache and reloads dev, prod, and the active alias. Values the framework injected for the active alias are refreshed. Values already set before SSM (.env, Lambda console) are left unchanged. getAliasEnvValue(key, "prod") reads the prod cache even when dev is the alias applied to process.env.
If SSM fails (expired credentials, missing IAM permission, etc.), the framework logs a warning and continues with .env / existing variables — startup is not blocked. The failed alias is still cached; call POST /parameter-store/flush to retry.
Local setup (.env)
PARAMETER_STORE_ENABLED=true
LAMBDA_NAME=my-api
ALIAS=local
AWS_REGION=eu-west-1Valid AWS credentials are required locally (aws configure, aws sso login, etc.).
Lambda setup
Environment variables
PARAMETER_STORE_ENABLED=true
AWS_REGION=eu-west-1IAM role — add at minimum:
{
"Effect": "Allow",
"Action": ["ssm:GetParametersByPath", "ssm:GetParameter"],
"Resource": [
"arn:aws:ssm:REGION:ACCOUNT:parameter/dev/my-api/*",
"arn:aws:ssm:REGION:ACCOUNT:parameter/prod/my-api/*"
]
}dev and prod are always read. Add the same permission for any other alias you invoke (staging, local, …). Add kms:Decrypt on the SSM KMS key if parameters are SecureString.
Create parameters (AWS CLI)
aws ssm put-parameter \
--name "/prod/my-api/DB_HOST" \
--value "prod-db.example.com" \
--type String \
--region eu-west-1Verify parameters (AWS CLI)
aws ssm get-parameters-by-path \
--path "/local/my-api/" \
--recursive \
--region eu-west-1Migration from previous versions
If you upgrade from a CEF version before Parameter Store / async loadEnv, update your src/index.ts as follows.
1. Async loadEnv()
Before
import { loadEnv } from "commoneventframework";
loadEnv();After
import { loadEnv } from "commoneventframework";
const envReady = loadEnv();
export const handler = async (event, context) => {
await envReady;
// ...
};2. Async setLambdaContext(context)
Before
setLambdaContext(context);After
await setLambdaContext(context);setLambdaContext now also loads Parameter Store parameters for the Lambda alias when PARAMETER_STORE_ENABLED=true.
3. Local dev server import
Before
const { startDevServer } = require("commoneventframework");
startDevServer(handler);After
import { startDevServer } from "commoneventframework";
// ...
startDevServer(handler);4. Full handler example (current recommended pattern)
import { loadEnv } from "commoneventframework";
const envReady = loadEnv();
import "./generated/HandlerRegistry";
import {
buildCommonEvent,
getRouteConfig,
resolveHandlerRef,
Response,
setLambdaContext,
startDevServer,
} from "commoneventframework";
export const handler = async (event, context) => {
await envReady;
await setLambdaContext(context);
const commonEvent = await buildCommonEvent(event);
// ...
};
if (process.argv.includes("--local")) {
startDevServer(handler);
}5. Parameter Store (optional)
No change required if you do not use SSM. To enable it, set PARAMETER_STORE_ENABLED=true and follow AWS Parameter Store (SSM).
6. CommonEvent type
CommonEvent now includes optional fields:
cookies?: { [name: string]: string | undefined }isBase64Encoded?: boolean
No breaking change for existing handlers that do not use these fields.
7. Parameter Store cache flush
Parameter Store caches dev, prod, and the active alias for the life of the process. A warm Lambda invoke does not call SSM again; it applies the invocation alias from the cache onto process.env.
POST /parameter-store/flush clears that cache and reloads Parameter Store immediately. Only keys the framework itself injected for the active alias are refreshed. Values already set before SSM (.env, Lambda console) stay as they are. A key the framework injected that no longer exists in Parameter Store is removed from process.env. The other aliases stay available through getAliasEnvValue.
No application code change is required. The route is registered with the other built-in routes. flushParameterStoreCache() is also exported if you need to clear the cache without HTTP.
{
"flushedAliases": ["dev", "prod"]
}If an earlier SSM call failed, that alias stays cached so startup is not retried on every invoke. Call POST /parameter-store/flush to try again.
8. Parameter Store force reload
POST /parameter-store/reload bypasses the cache and reads Parameter Store again. Unlike flush, a value for the alias currently applied to process.env overwrites that variable, including a value that came from .env or the Lambda console.
| Call | Effect |
|------|--------|
| POST /parameter-store/reload | Reloads every key of dev, prod, and the active alias |
| POST /parameter-store/reload?key=DB_HOST | Reloads DB_HOST on those aliases |
| POST /parameter-store/reload?key=DB_HOST&alias=prod | Reloads that key on prod only |
| POST /parameter-store/reload?alias=prod | Reloads every key of prod only |
key and alias can also be sent as a JSON body: { "key": "DB_HOST", "alias": "prod" }.
The response lists updated, removed, and missing keys. It does not include the secret values. appliedAlias is the alias written into process.env, or null when the reloaded alias is not the one currently applied (the cache is still updated).
import { reloadParameterStore } from "commoneventframework";
await reloadParameterStore(context); // every key
await reloadParameterStore(context, { key: "DB_HOST" }); // one key
await reloadParameterStore(context, { key: "DB_HOST", alias: "prod" });9. GET /info (build snapshot)
cef-build now writes dist/build-info.json next to the bundle (and inside dist/dist.zip). GET /info returns that file:
- Node version that ran
cef-build - When the file was written (
builtAt). On CodeBuild,codebuild.startedAtisCODEBUILD_START_TIME - Who started the build:
CODEBUILD_INITIATORwhen the build runs on CodeBuild (IAM user,codepipeline/<name>, or the integration that triggered it). A webhook also storescodebuild.webhookActorAccountId. Outside CodeBuild,builtByis the OS user andcodebuildisnull
No application code change is required. Rebuild with cef-build (or cef-build --full) so the file is produced. Without it, GET /info responds 404.
Recommended project structure
my-lambda/
├── src/
│ ├── index.ts # Lambda entry point + main handler
│ ├── generated/
│ │ └── HandlerRegistry.ts # Generated by cef-gen-handlers / cef-build
│ ├── root.yaml # Route definitions (OpenAPI + x-handler)
│ └── handlers/
│ ├── types.ts # HandlerFn and InputParserFn types
│ ├── hello.ts # Example handler
│ └── users.ts # Handler with inputParser
├── dist/ # Build output (esbuild)
├── .env # Environment variables
├── package.json
└── tsconfig.json