Next.js Discord

Discord Forum

Chaining middleware?

Unanswered
Entlebucher Mountain Dog posted this in #help-forum
Open in Discord
Entlebucher Mountain DogOP
Could we implement chaining middleware like nodejs - experss - middleware?
P/S: I've read this post, Is this valid to use in Nextjs?
https://reacthustle.com/blog/how-to-chain-multiple-middleware-functions-in-nextjs

1 Reply

Japanese jack mackerel
I came here with the same question but specifically regarding Next 13. The post you linked was written with 12 in mind.
I tried a similar approach to manage multiple middlewares kept in their own domains and only combine them in the root middleware.ts.
export interface Middleware {
  (request: NextRequest, response: NextResponse): void
}

interface MiddlewareStack {
  (request: NextRequest): void
}

const combineMiddleware = (...middleware: Middleware[]): MiddlewareStack  => {
  const response = NextResponse.next()

  if (middleware.length === 0) {
    return (() => response) as MiddlewareStack
  }

  if (middleware.length === 1) {
    return (request: NextRequest) => middleware[0](request, response)
  }

  const middlewareStack = middleware.reduce((a, b) => (request: NextRequest) => {
    a(request, response)
    b(request, response)
  })

  return (request: NextRequest) => middlewareStack(request, response)
}

But this only leads to hard to understand and follow redirect loops. It seems to me that 13's middleware was designed to be kept in a single root/middleware.ts but I can't find anything to explicitly prove this.

I would love some more info on that.