Library for readable and manageable Next.js middleware

Overview

🧵 Next Compose Middleware

This is a library for building Next.js complex middleware declaratively. You can create highly readable and manageable middleware by composing multiple functions together.

🌟 Features

  • Path-based middleware execution (like "Nested Middleware")
  • Composition of functions divided by interest (including early exit)

🔏 Requirements

Next.js v12.2.0+ (Middleware support)

🐈 Usage

Basic

export default async function middleware(req: NextRequest) {
  /**
   * Path                : Middleware execution order
   * 
   * `/`                 : root1 -> root2
   * `/foo`              : root1 -> root2 -> foo
   * `/foo/bar/hoge`     : root1 -> root2 -> foo -> fooBar
   * `/foo/bar/xxxx/baz` : root1 -> root2 -> foo -> fooId -> fooIdBaz
   */
  return composeMiddleware(req, NextResponse.next(), {
    scripts: [root1, root2],
    '/foo': {
      scripts: [foo],
      '/bar': {
        scripts: [fooBar], 
      },
      '/[id]': {
        scripts: [fooId],
        '/baz': [fooIdBaz]
      },

      // ↓ Either writing method will work, but if you want to nest more, you have to write it in the Object
      '/qux': [fooQux]
      '/qux': {
        scripts: [fooQux]
      }
    }
  })
}

Each middleware function is a ComposableMiddleware function. This is almost identical to the Next.js middleware, differing only in that it takes additional arguments.

/**
 * type ComposableMiddleware = (
 *   req: NextRequest,
 *   res: NextResponse,
 *   handler?: {...} // explained at next section
 * ) => Promise<Response>;
 */
const fooMiddleware: ComposableMiddleware = async (req, res) => {
  res.cookies.set('foo', 'foo')
  return res;
};

Early Exit

If you want to abort whole process at a particular middleware without executing subsequent functions, use a handler that is given from third argument.

const basicAuth: ComposableMiddleware = async (req, res, { breakAll, breakOnce }) => {
  const success = validateBasicAuth(req); // returns boolean
  if (success) {
    return res;
  } else {
    return breakAll(res); // All subsequent middleware (`refreshToken`, `foo` and others) will not be executed !!

    // or
    return breakOnce(res); // Only subsequent middleware in the same hierarchy (`refreshToken`) will not be executed (`foo` will be executed).
  }
};

export default async function middleware(req: NextRequest) {
  return composeMiddleware(req, NextResponse.next(), {
    scripts: [basicAuth, refreshToken],
    '/foo': {
      scripts: [foo],
      ...
    }
  })
}
You might also like...

Render readable & responsive tables in the terminal

terminal-columns Readable tables for the terminal. Tables can be automatically responsive! Features Content wrapped to fit column width Column widths

Oct 28, 2022

A compiled-away, type-safe, readable RegExp alternative

🦄 magic-regexp A compiled-away, type-safe, readable RegExp alternative ✨ Changelog 📖 Documentation ▶️ Online playground Features Runtime is zero-dep

Jan 8, 2023

parses human-readable strings for JavaScript's Temporal API

🕑 temporal-parse What is the temporal-parse? Temporal is the next generation of JavaScript's standard Date API. It's currently proposed to TC39 (see:

Jan 2, 2023

Minimalistic configuration for TS to only extend JS with types. No TS features, no bundling. Readable maintainable code after compilation.

Minimalistic configuration for TS to only extend JS with types. No TS features, no bundling. Readable maintainable code after compilation.

ts-guideline Minimalistic configuration for TS to only extend JS with types. No TS-scpecific features, no bundling. Readable maintainable code after c

Dec 22, 2022

Wrap zod validation errors in user-friendly readable messages

zod-validation-error Wrap zod validation errors in user-friendly readable messages. Features User-friendly readable messages, configurable via options

Dec 23, 2022

Svelte component to display time distances in a human readable format.

Time Distance Display time distances in a human readable format. Based on date-fns Updates every 60 seconds View demo Usage Install package: pnpm i -D

Nov 2, 2022

A fast and optimized middleware server with an absurdly small amount of code (300 lines) built on top of Deno's native HTTP APIs

A fast and optimized middleware server with an absurdly small amount of code (300 lines) built on top of Deno's native HTTP APIs with no dependencies. It also has a collection of useful middlewares: log file, serve static, CORS, session, rate limit, token, body parsers, redirect, proxy and handle upload. In "README" there are examples of all the resources. Faster's ideology is: all you need is an optimized middleware manager, all other functionality is middleware.

Dec 28, 2022

express-like middleware system for your remix loaders and actions

remix-middleware Add an express-like middleware stack to your remix loaders and actions! yarn add remix-middleware // ./app/middleware.server.ts expor

Nov 22, 2022

🛡️ Dead-simple, yet highly customizable security middleware for Apollo GraphQL servers and Envelop 🛡️

🛡️ Dead-simple, yet highly customizable security middleware for Apollo GraphQL servers and Envelop 🛡️

GraphQL Armor 🛡️ GraphQL Armor is a dead-simple yet highly customizable security middleware for various GraphQL server engines. Contents Contents Sup

Jan 9, 2023
Releases(2.0.4)
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
High performance personalization & a/b testing example using Next.js, Edge Middleware, and Builder.io

Next.js + Builder.io Personalization & A/B Testing with Edge Middleware This is a fork of Next.js Commerce with Builder.io integrated and using Edge M

Builder.io 7 Sep 6, 2022
This is a demo of updating a map to show air quality data for the user’s current location using Next.js Advanced Middleware, powered by Netlify Edge Functions.

Show Local Air Quality Based on the User's Location Use AQI data to show the air quality near the current user. This is built using Next.js Advanced M

Jason Lengstorf 8 Nov 4, 2022
Send encrypted and decrypted messages with verifiable keys and human readable names.

zooko-msg Encrypt and decrypt messages using AES with a preshared ECDH key generated using keys associated with Handshake names. I noticed that there

Publius Federalist 31 Jul 27, 2022
An unofficial, simplified version of the @Shopify/koa-shopify-auth middleware library.

simple-koa-shopify-auth https://www.npmjs.com/package/simple-koa-shopify-auth NOTE: This package is not maintained by or affiliated with Shopify. Desc

David 20 Nov 7, 2022
⏱ Simple Alpine.js plugin to display the human-readable distance between a date and now.

⏱ Alpine TimeAgo ⏱ An Alpine.js plugin to return the distance between a given date and now in words (like "3 months ago", "about 2 hours ago" or "in a

Marc Reichel 47 Dec 22, 2022
⛲ Sort import declarations into a pleasing and readable cascade.

⛲ eslint-plugin-cascading-imports This plugin allows to automatically enforce a visual "cascading" order for import declarations. Imports in each bloc

Florent 1 Jan 20, 2022
Enhanced interval features for Node.js, such as promisified interval and human readable time parsing.

Interval-next Interval-next is a package that extends Javascript's built-in setInterval() capabilities. You have a plain and promisified interval meth

Snowy 5 Jul 28, 2022
Convert JSON to human readable HTML

json.human.js: Json Formatting for Human Beings A small library to convert a JSON object into a human readable HTML representation that is easy to sty

Mariano Guerra 955 Dec 3, 2022