middy-js

5.0.10 • Public • Published

Middy.js 🛡️

npm version License: MIT

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
# or
yarn add middy-js
# or
pnpm add middy-js

Basic Usage

const { Middy } = require('middy-js');
const express = require('express');

const app = express();
const middy = new Middy(app);

// Add middleware
middy.use((req, res, next) => {
  console.log('Request received at', new Date());
  next();
});

// Add error handler
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([
  // Authentication
  require('@middy/auth'),
  
  // Request validation
  require('@middy/validator'),
  
  // Response formatting
  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) => {
      // Pre-request logic
      req.startTime = Date.now();
      next();
    },
    after: (req, res, next) => {
      // Post-request logic
      console.log(`Request took ${Date.now() - req.startTime}ms`);
      next();
    }
  }
}

middy.use(myMiddleware({ option: true }));

Framework Adapters

// Fastify adapter
const fastify = require('fastify');
const { FastifyMiddy } = require('middy-js/adapters');

const app = fastify();
const middy = new FastifyMiddy(app);

Benchmarks

Framework Requests/sec Latency (ms)
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

Package Sidebar

Install

npm i middy-js

Weekly Downloads

566

Version

5.0.10

License

ISC

Unpacked Size

21.8 kB

Total Files

12

Last publish

Collaborators

  • millos