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

@nartix/next-middleware-chain

v2.0.0

Published

A lightweight middleware chainer for Next.js

Downloads

106

Readme

next-middleware-chain

A lightweight utility for composing Next.js middleware functions in a simple and maintainable way. Using a chain-of-responsibility style, you can easily combine multiple middleware steps into a single pipeline.

Installation

npm install @nartix/next-middleware-chain

or

yarn add @nartix/next-middleware-chain

Overview

This package provides a function that takes multiple middleware handlers and executes them in sequence until one of them decides to stop the chain or until all have processed the request.

Key Features:

  • Modular: Build complex logic from simple, single-purpose middleware functions.
  • Flexible: Any middleware can terminate the chain early, returning its final response.
  • Maintainable: Clear and predictable middleware flows.

Basic Usage

Defining Your Middlewares

In this new approach, each middleware is defined as a factory function. A middleware factory takes a next function and returns an async function that will receive:

  • req: The NextRequest
  • event: The NextFetchEvent
  • incomingResponse (optional): A NextResponse passed forward from previous factories in the chain (if any)

To continue the chain, call next(req, event, response). To short-circuit, simply return a final NextResponse or a native Response (e.g., for redirects or errors).

import { NextResponse } from 'next/server';
import { MiddlewareFactory } from '@nartix/next-middleware-chain'; // or your package name

export const logRequestTimeFactory: MiddlewareFactory = (next) => {
  return async (req, event, incomingResponse) => {
    console.log('Request received at:', Date.now());
    // Continue to the next middleware
    return next(req, event, incomingResponse);
  };
};

export const addHeaderA: MiddlewareFactory = (next) => {
  return async (req, event, incomingResponse) => {
    // Use existing response if available, otherwise create a new one
    const response = incomingResponse ?? NextResponse.next();
    response.headers.set('X-Header-A', 'ValueA');
    // Continue the chain
    return next(req, event, response);
  };
};

Composing Middlewares

Use createMiddlewareChain to create a composed handler:

// middleware.ts
import { logRequestTimeFactory } from './logRequestTimeFactory';
import { addHeaderAFactory } from './addHeaderAFactory';

const factories = [
  logRequestTimeFactory,
  addHeaderAFactory
  // ...add as many middleware functions as you like
  ];

export default createMiddlewareChain(factories);

Advanced Usage

You might have a more complex scenario where you conditionally alter headers or short-circuit early based on certain conditions. For example:

// Example: A middleware that checks for an auth token.
export const checkAuth: MiddlewareFactory = (next) => {
  return async (req: NextRequest, event: NextFetchEvent, incomingResponse?: NextResponse) => {
    const token = req.headers.get('Authorization');
    if (!token) {
      // Return a 401 immediately, short-circuiting the chain
      return new Response('Unauthorized', { status: 401 });
    }

    // Otherwise, continue to the next middleware.
    // If we received a shared response, reuse it; otherwise create a new one
    return next(req, event, incomingResponse ?? NextResponse.next());
  };
};

// Example: A middleware that adds a custom header to the response.
export const addCustomHeader: MiddlewareFactory = (next) => {
  return async (req: NextRequest, event: NextFetchEvent, incomingResponse?: NextResponse) => {
    const response = incomingResponse ?? NextResponse.next();
    response.headers.set('X-Custom-Header', 'MyValue');
    return next(req, event, response);
  };
};

// Example: Calling All Subsequent Factories, Then Editing the Final Response
export const addFinalHeader: MiddlewareFactory = (next) => {
  return async (req, event, incomingResponse) => {
    // Let other factories run first
    const result = await next(req, event, incomingResponse ?? NextResponse.next());

    // If we got a NextResponse back, add a final header
    if (result instanceof NextResponse) {
      result.headers.set('X-Final-Header', 'FinalValue');
      return result;
    }

    // If it's a plain Response or no return, just pass it along
    return result;
  };
};

Happy coding! If you have questions, feel free to open an issue or submit a pull request.