Type-safe ESM server framework for Node 24+. The same routes run as an AWS Lambda Web Function (the function is a real HTTP server), as a Lambda Event Function (API Gateway HTTP API v2) and on a plain Node HTTP server, with WebSockets, middleware, routing and HTML sanitization built in.
Upgrading? See MIGRATION.md for the 10.x -> 11.0 checklist (renames:
lambdaEvent->eventFunction,LambdaProxyRouter->EventFunctionProxy) and the consolidated 6.x -> 10.x one, or CHANGELOG.md for the full history.
- ✅ Full TypeScript support with comprehensive type definitions
- ✅ ESM (ES Modules) compatible
- ✅ Three deployment modes, one router: Lambda Web Function, Lambda Event Function, plain Node server — see Deployment Modes
- ✅ Trustworthy
clientIpandrequestIdon every request, in every mode - ✅ Secure error handling with automatic sensitive data protection
- ✅ WebSocket server with message formatting and event handling
- ✅ Flexible routing system with URL pattern matching
- ✅ Static file serving with MIME type detection
- ✅ Built-in middleware support (request logging, etc.)
- ✅ Application state management
- ✅ Event system with pub/sub pattern
- ✅ HTML sanitization utilities
- ✅ Comprehensive test coverage with Vitest
- ✅ Modern async/await API
npm install @designofadecade/serverOr using other package managers:
# Yarn
yarn add @designofadecade/server
# pnpm
pnpm add @designofadecade/server
# Bun
bun add @designofadecade/server- Node.js >= 24.0.0
- ES Modules support (package uses
"type": "module") - TypeScript >= 5.0 (if using TypeScript)
import { Router, Routes, WebFunction, type RouterRequest } from '@designofadecade/server';
class HelloRoutes extends Routes {
constructor(router: Router) {
super(router);
this.addRoute('/hello/:name', 'GET', this.hello);
}
async hello(req: RouterRequest) {
return { status: 200, body: { hello: req.params.name, from: req.clientIp } };
}
}
const router = new Router({ initRoutes: [HelloRoutes] });
// Locally: listens on port 3000.
// As a Lambda Web Function: binds AWS_LAMBDA_HTTP_ENDPOINT and drains on SIGTERM.
const server = WebFunction.serve(router, { port: 3000 });
await server.ready;
console.log(`Server running on http://localhost:${server.address.port}`);The same router serves a Lambda Event Function with
export const handler = (event) => router.eventFunction(event);. Choosing
between the two: docs/deployment-modes.md.
The server is composed of several modular components:
- Server: HTTP server with error events, graceful shutdown and Lambda Web Function detection
- WebFunction:
WebFunction.serve(router, options)— one entry point for local and Lambda Web Function - Router: URL pattern-based routing;
nodeJSRequestfor HTTP,eventFunctionfor API Gateway events - Routes: Route collection and management
- WebSocketServer: WebSocket connection management
- WebSocketMessageFormatter: Message serialization/deserialization
- RequestLogger: HTTP request logging middleware
- StaticFileHandler: Static file serving with caching
- HtmlSanitizer: XSS protection for HTML content
- HtmlRenderer: Server-side HTML rendering
- AppState: Application-wide state management
- Events: Event emitter with type-safe event handling
- EventsManager: Event subscription and lifecycle management
- Local:
Local.EventFunctionProxyruns a Lambda Event Function handler behind a local HTTP server. By default it serves only clients connecting from this machine (decided from the socket address, not theHostheader), only loopbackHostnames, and grants CORS to loopback origins only; bind it withlisten(3000, '127.0.0.1'). See docs/local.md to opt in LAN devices (allowedPeers) or tunnel hosts (allowedHosts)
- Slack: Slack notifications integration
- ApiClient: HTTP client for external APIs
import { Router, Routes, type RouterRequest, type RouterResponse } from '@designofadecade/server';
class UserRoutes extends Routes {
static basePath = '/api';
constructor(router: Router) {
super(router);
this.addRoute('/users/:id', 'GET', this.getUser);
}
async getUser(req: RouterRequest): Promise<RouterResponse> {
return { status: 200, body: { userId: req.params.id } };
}
}
const router = new Router({ initRoutes: [UserRoutes] });
// Plain Node server or Lambda Web Function
await router.nodeJSRequest(req, res, { cors: ['https://app.example.com'] });
// Lambda Event Function (API Gateway HTTP API v2)
export const handler = (event) => router.eventFunction(event);import { WebSocketServer } from '@designofadecade/server';
const wsServer = new WebSocketServer({
port: 8080,
allowedOrigins: ['https://app.example.com'], // others refused with 403
// Runs at upgrade time; null/false, a throw or a timeout refuse with 401
// before any socket opens. Do not authenticate in the 'connection' handler.
authenticate: async (req) => sessionFrom(req.headers.cookie),
});
wsServer.on('message', (parsed, ws, req, session) => {
// `session` is what authenticate returned for the sending connection
console.log(`${session.userId} sent`, parsed.type);
});See WebSocket for the security model.
import { StaticFileHandler } from '@designofadecade/server';
const staticHandler = new StaticFileHandler('./public', {
cacheControl: 'public, max-age=3600',
});
// Resolves to { status, headers, body }; paths outside ./public get 403.
const response = await staticHandler.serve('/assets/style.css');EventsManager routes WebSocket messages to handlers by their type:
import { Events, EventsManager, WebSocketServer } from '@designofadecade/server';
class UserEvents extends Events {
constructor(manager: EventsManager) {
super(manager);
this.addListener('user:login', async (msg, ws, req, auth) => {
manager.broadcast('user:online', msg.payload);
});
}
}
const wss = new WebSocketServer({ port: 8080, allowedOrigins: ['https://app.example.com'] });
const manager = new EventsManager({
registerWebSocketServer: wss,
initEvents: [UserEvents],
});Comprehensive documentation is available in the docs/ directory on GitHub:
- Deployment Modes - Lambda Web Function vs Event Function vs plain server: decision table, entry files, production checklist
- Logger Documentation - CloudWatch Logger with AWS Lambda integration, sensitive data redaction, and performance tracking
- API Documentation - OpenAPI/Swagger documentation generation guide
- New Features - Performance benchmarks, pre-commit hooks, and recent additions
- Changelog - Version history and release notes
- Contributing Guide - How to contribute to the project
npm installnpm test # Run tests once
npm run test:watch # Run tests in watch mode
npm run test:ui # Open Vitest UI
npm run test:coverage # Generate coverage reportnpm run build # Build once
npm run build:watch # Build in watch modenpm run lint # Run ESLint
npm run format # Format code with Prettier
npm run typecheck # Type-check without emittingsrc/
├── client/ # API client utilities
├── context/ # Request context handling
├── docs/ # OpenAPI/Swagger documentation generators
├── events/ # Event system with pub/sub pattern
├── local/ # Local proxy for Lambda Event Function handlers
├── logger/ # Logging utilities with CloudWatch support
├── middleware/ # Request middleware (logging, etc.)
├── notifications/ # Notification integrations (Slack, etc.)
├── router/ # Routing system with URL pattern matching
├── sanitizer/ # HTML sanitization for XSS protection
├── server/ # HTTP server and Lambda Web Function entry point
├── state/ # Application state management
├── types/ # TypeScript type definitions
├── utils/ # Utilities and helpers
└── websocket/ # WebSocket server implementation
Full API documentation is available in the docs directory:
- Deployment Modes - Choosing and configuring a deployment mode
- Server - Core server setup,
WebFunction.serve, shutdown - Router - Routing and request handling
- Local Development - Running Event Function handlers locally
- WebSocket - WebSocket server and messaging
- Logger - CloudWatch logging and performance tracking
- Events Manager - Event system usage
- API Documentation - OpenAPI/Swagger setup
- State & Context - State management
- Utilities - Helper functions and utilities
This package includes built-in security features:
- HTML Sanitization - XSS protection for user-generated content
- Type Safety - Full TypeScript support for compile-time safety
- Input Validation - URL pattern matching and parameter validation
- Unforgeable client identity -
request.clientIpnever comes from a client-controlledX-Forwarded-Forvalue, andrequest.requestIdis only taken from Lambda's header in Web Function mode - Verified JWTs -
request.authorizeris populated only from a token whose signature has been checked
If you discover a security vulnerability, please send an email to info@designofadecade.com instead of using the issue tracker.
This project follows Semantic Versioning. For available versions, see the tags on this repository or the npm registry.
See CHANGELOG.md for a history of changes.
- Documentation: GitHub Repository
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Contributions are welcome! Please see CONTRIBUTING.md for details on:
- Code of Conduct
- Development workflow
- Pull request process
- Coding standards
- Testing requirements
This project is licensed under the MIT License - see the LICENSE file for details.
Design of a Decade
Email: info@designofadecade.com
Website: designofadecade.com
Built with:
- TypeScript - Type-safe JavaScript
- Vitest - Unit testing framework
- ws - WebSocket implementation
Made with ❤️ by Design of a Decade