logo My Digital Garden

NestJS 13 series - Middleware chaining

By James Kolean on Nov 22, 2023
Source repository: https://gitlab.com/jameskolean/next-explore
Demo: https://next-explore-liart.vercel.app/

Unleashing the Power of Higher Order Components in Next.js Middle Chaining Today, we’re exploring the superhero duo of middle chaining and higher order components (HOCs). If you’ve ever wondered how to seamlessly chain middleware functions in a way that feels like assembling your own Avengers, you’re in for a treat!

The Lowdown on HOCs Before we dive into the action, let’s quickly talk about Higher Order Components. They’re like the Batman utility belt of React – reusable functions that wrap around your existing components, enhancing their abilities. In our case, they’re going to be the secret sauce for our Next.js middle chaining.

Crafting the Middleware HOCs In the middlewares folder, let’s turn our middleware functions into HOCs:

// src/middlewares/withLogger.ts
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { MiddlewareFactory } from "./middlewareFactory";

export const withLogger: MiddlewareFactory = (next) => {
  return async (request: NextRequest, _next: NextFetchEvent) => {
    const pathname = request.nextUrl.pathname;
    return next(request, _next);

We’ve transformed our middleware functions into HOCs that take a WrappedComponent as an argument and return a new component with the middleware logic applied.

Chaining HOCs Now, let’s assemble our superhero squad in the middleware.js file:

// middleware.js
import {
} from "@/middlewares/MiddlewareChain";
import {
} from "@/middlewares/withLogger";
import {
} from "@/middlewares/withInternationalization";

const middlewares = [withLogger, withInternalization];
export default middlewareChain(middlewares);
export const config = {
    matcher: [
         * Match all request paths except for the ones starting with:
         * - api (API routes)
         * - _next/static (static files)
         * - _next/image (image optimization files)
         * - _next/assets (asset files)
         * - favicon.ico (favicon file)

Higher Order Components in Next.js middle chaining provide a neat and organized way to enhance your components with specific functionalities. It’s like having a customizable toolkit for your components, and chaining them is as straightforward as ordering your favorite pizza toppings.

© Copyright 2023 Digital Garden cultivated by James Kolean.