npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

midshield

v1.0.1

Published

Zero-dependency production middleware toolkit for Express and Node.js: rate limiting, security headers, API-key auth, request ID, response time, logger, CORS, and body size limits.

Readme

midshield

Production-ready, zero-dependency security & utility middleware toolkit for Node.js & Express.

npm version License: MIT Zero Dependencies

MidShield consolidates common API middleware into a single fast, dependency-free toolkit with full TypeScript type definitions and dual ESM/CommonJS support.


Features

  • Rate Limiter: Sliding window & token bucket algorithms, IP detection, standard RFC headers (RateLimit-*, Retry-After), and memory leak protection.
  • Security Headers: OWASP recommendations (CSP, HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, COOP, CORP) with zero overhead.
  • API Key & Bearer Auth: Constant-time verification (crypto.timingSafeEqual) defending against timing side-channel attacks, with role & metadata attachment.
  • Request ID: Distributed request tracing with standard UUIDs or custom IDs (X-Request-Id).
  • Response Time: Nanosecond precision timing (process.hrtime.bigint()) via X-Response-Time.
  • Request Logger: Dev-friendly ANSI colored output, combined format, and structured JSON logs for production observability.
  • CORS: Origin validation (wildcard, list, regex, dynamic functions), preflight OPTIONS handling, and credentials support.
  • Body Size Guard: Early Content-Length check & streaming chunk size monitoring to protect against oversized payload DoS.
  • Compose Pipeline: Cleanly chains multiple middlewares into a single handler.
  • CLI Utility: Built-in npx midshield for mocking, security auditing, and latency benchmarking.

Installation

npm install midshield

Quick Start

Express

const express = require('express');
const { midshield, rateLimiter, apiKeyAuth } = require('midshield');

const app = express();

// 1. One-line preset: Request ID, Response Time, Security Headers & Logger
app.use(midshield());

// 2. Global rate limiter (100 requests per minute)
app.use(rateLimiter({ windowMs: 60 * 1000, max: 100 }));

// 3. Public endpoint
app.get('/api/public', (req, res) => {
  res.json({ status: 'ok', requestId: req.id });
});

// 4. Protected endpoint with API key
app.get('/api/secret', apiKeyAuth({ keys: ['my-secret-key'] }), (req, res) => {
  res.json({ secret: 'classified data', auth: req.auth });
});

app.listen(3000, () => console.log('Server listening on port 3000'));

Native Node.js HTTP (No Framework Required)

const http = require('node:http');
const { compose, requestId, responseTime, securityHeaders, cors } = require('midshield');

const shield = compose(
  requestId(),
  responseTime(),
  securityHeaders(),
  cors()
);

const server = http.createServer((req, res) => {
  shield(req, res, () => {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ message: 'Hello World', reqId: req.id }));
  });
});

server.listen(4000);

API Reference

midshield(options)

All-in-one preset combining core middlewares.

  • options.requestId: boolean or RequestIdOptions
  • options.responseTime: boolean or ResponseTimeOptions
  • options.security: boolean or SecurityHeadersOptions
  • options.logger: boolean or RequestLoggerOptions
  • options.cors: boolean or CorsOptions
  • options.rateLimit: boolean or RateLimiterOptions
  • options.bodyLimit: boolean or BodyLimitOptions

rateLimiter(options)

  • windowMs (number): Window duration in ms (default 60000).
  • max (number | (req) => number): Allowed requests per window (default 100).
  • algorithm ('sliding-window' | 'token-bucket'): Default 'sliding-window'.
  • trustProxy (boolean | number): Respect proxy headers (default false).
  • keyGenerator ((req) => string): Custom key generator. Defaults to client IP.
  • skip ((req) => boolean): Bypass condition.

apiKeyAuth(options)

  • keys (string | string[] | Record<string, any>): Valid keys or map of keys to metadata.
  • header (string): Header to check (default 'x-api-key').
  • bearer (boolean): Also parse Authorization: Bearer <token> (default true).
  • validator (async (key, req) => boolean | object): Custom authentication logic.

securityHeaders(options)

  • contentSecurityPolicy: Custom directive object, string, or false.
  • hsts: HSTS options or false.
  • frameguard: 'SAMEORIGIN', 'DENY', or false.
  • noSniff: boolean (default true).
  • hidePoweredBy: boolean (default true).

requestLogger(options)

  • format: 'dev', 'json', 'combined', 'short', or custom function.
  • stream: Writable stream (default process.stdout).
  • colors: boolean (auto-detected).

cors(options)

  • origin: '*', string, array, regex, or dynamic function.
  • methods: Array or comma-delimited string of HTTP methods.
  • credentials: boolean.
  • maxAge: Preflight cache seconds.

bodyLimit(options)

  • max: Human-readable size string (e.g. '100kb', '1mb', '500b') or number of bytes.

CLI Usage

# Start an instant local mock server with MidShield active
npx midshield serve --port 3000 --cors --rate-limit 100

# Audit HTTP security headers of any website or API
npx midshield inspect https://api.github.com

# Benchmark latency and rate limits
npx midshield benchmark http://localhost:3000/api -n 50 -c 5

License

MIT