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

next-route-middleware

v1.1.1

Published

πŸ“¦ next-route-middleware

Readme

πŸ“¦ next-route-middleware

A lightweight, Express/Koa-style middleware system for Next.js route handlers. Easily compose middlewares (auth, error handling, logging, rate limiting, etc.) in your app/ routes.

✨ Features

βœ… Express/Koa-like next() middleware flow

βœ… Type-safe with generic UserType

βœ… Works with Next.js App Router (app/ directory)

βœ… Example middlewares available in src/middlewares-examples/ for reference:

  • withError β€” catch errors and return JSON.
  • withAuth β€” authenticate requests
  • withRateLimit β€” simple rate limiting
  • withCors β€” add CORS headers
  • withCache β€” add cache headers
  • withLogger β€” log requests & responses

Note: These example middlewares are not included in the published package. They are provided as reference implementations to help you get started. Copy and customize them in your own project as needed.

πŸ“¦ Installation

npm install next-route-middleware
# or
yarn add next-route-middleware
# or
pnpm add next-route-middleware

Usage

Example Route (app/api/hello/route.ts)

import { NextRequest, NextResponse } from "next/server";
import { composeHandlers } from "next-route-middleware";
// Import your own middlewares (see "Creating Custom Middlewares" below)
import { withError, withAuth, withRateLimit, withLogger } from "@/middlewares";

async function baseHandler(
  req: NextRequest,
  params: { id: string },
  user?: { id: string; role: string }
) {
  return NextResponse.json({ message: `Hello ${user?.id}`, params });
}

// Compose middlewares around handler
export const GET = composeHandlers(
  baseHandler,
  withError,
  withLogger,
  withRateLimit,
  withAuth
);

➑️ Order matters:

  1. withAuth runs last before handler
  2. withRateLimit checks before auth
  3. withLogger logs every request
  4. withError wraps everything

Middleware Signature

export type Middleware<P = any, U = any> = (
  req: NextRequest,
  params: P,
  user: U | undefined,
  next: RouteHandler<P, U>
) => Promise<Response> | Response;
  • req β†’ Next.js NextRequest
  • params β†’ Route params (from [id] etc.)
  • user β†’ Optional user object (your type)
  • next β†’ Calls the next handler in the chain

⚑ Creating Custom Middlewares

Want to build your own? Just follow the middleware signature. Here are some examples:

Example 1: Adding Custom Headers

import type { Middleware } from "next-route-middleware";

export const withCustomHeader: Middleware = async (req, params, user, next) => {
  const response = await next(req, params, user);

  const headers = new Headers(response.headers);
  headers.set("X-Custom-Header", "My-Value");
  headers.set("X-Request-ID", crypto.randomUUID());

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers,
  });
};

Example 2: Request Validation

import { NextResponse } from "next/server";
import type { Middleware } from "next-route-middleware";

export const withValidation: Middleware = async (req, params, user, next) => {
  const contentType = req.headers.get("content-type");

  if (req.method === "POST" && !contentType?.includes("application/json")) {
    return NextResponse.json(
      { error: "Content-Type must be application/json" },
      { status: 400 }
    );
  }

  return next(req, params, user);
};

Example 3: Response Transformation

import { NextResponse } from "next/server";
import type { Middleware } from "next-route-middleware";

export const withTimestamp: Middleware = async (req, params, user, next) => {
  const response = await next(req, params, user);

  // Add timestamp to JSON responses
  const contentType = response.headers.get("content-type");
  if (contentType?.includes("application/json")) {
    const data = await response.json();
    return NextResponse.json({
      ...data,
      timestamp: new Date().toISOString(),
    });
  }

  return response;
};

Using Your Custom Middleware

export const GET = composeHandlers(
  baseHandler,
  withError,
  withCustomHeader,
  withValidation,
  withTimestamp
);

πŸ“– Example Project

To test quickly, clone the repo and run the included Next.js example:

git clone https://github.com/wisdomabioye/next-route-middleware
cd next-route-middleware/example
npm install
npm run dev

πŸ“ Roadmap

  • More example middlewares (withSession, withMetrics, etc.)
  • Better TypeScript inference for user
  • Integration tests with Next.js app/ routes

🀝 Contributing

PRs welcome! Please open an issue for discussion before submitting new example middlewares or features.

πŸ“œ License

MIT Β© 2025 β€” Built with ❀️ for the Next.js community