Middy.js 🛡️

The Modern Node.js Middleware Toolkit - A lightweight, modular middleware system for Express and beyond.
Features ✨
- 🧩 Plugin-based architecture - Compose middleware like building blocks
- ⚡ Performance optimized - Low overhead middleware execution
- 🔌 Universal adapter - Works with Express, Fastify, and vanilla Node.js
- 📦 Batteries included - Common middleware utilities included
- 🛠️ TypeScript ready - Full type definitions out of the box
Installation
npm install middy-js
yarn add middy-js
pnpm add middy-js
Basic Usage
const { Middy } = require('middy-js');
const express = require('express');
const app = express();
const middy = new Middy(app);
middy.use((req, res, next) => {
console.log('Request received at', new Date());
next();
});
middy.onError((err, req, res, next) => {
console.error(err);
res.status(500).send('Something broke!');
});
app.get('/', (req, res) => {
res.send('Hello Middy!');
});
app.listen(3000);
Core Concepts
Middleware Chains
middy.use([
require('@middy/auth'),
require('@middy/validator'),
require('@middy/format-response')
]);
Built-in Middleware
Middy.js comes with several useful middleware:
bodyParser - Parse JSON/URL-encoded bodies
cors - Cross-Origin Resource Sharing
helmet - Security headers
logger - Request logging
rateLimit - Rate limiting
const { bodyParser, cors } = require('middy-js/middleware');
middy.use([
cors(),
bodyParser()
]);
Advanced Usage
Custom Middleware
function myMiddleware(config) {
return {
before: (req, res, next) => {
req.startTime = Date.now();
next();
},
after: (req, res, next) => {
console.log(`Request took ${Date.now() - req.startTime}ms`);
next();
}
}
}
middy.use(myMiddleware({ option: true }));
Framework Adapters
const fastify = require('fastify');
const { FastifyMiddy } = require('middy-js/adapters');
const app = fastify();
const middy = new FastifyMiddy(app);
Benchmarks
| Plain Express | 15,678 | 1.21 |
| Middy.js | 14,892 | 1.34 |
| Connect | 14,120 | 1.45 |
Benchmarks run on Node 18, 2.4GHz Quad-Core Intel Core i5
Ecosystem
Official plugins:
@middy/auth - Authentication utilities
@middy/cache - Request/response caching
@middy/validator - Request validation
@middy/swagger - OpenAPI/Swagger integration