4

I'm working on a Next.js project and trying to implement multiple middleware in my application. While I've found examples of using a single middleware in Next.js using the next-connect package, I prefer to achieve this without relying on any external packages.

I have a middleware.ts file where I would like to define and use multiple middlewares. Here's the code snippet from my middleware.ts file:

import { NextResponse, NextRequest } from 'next/server';

export function middleware(request: NextRequest) {

  const userId = request.cookies.get('userId')

  if (!userId) {
    return NextResponse.redirect(new URL('/auth/login', request.nextUrl.origin).href);
  }
  return NextResponse.next();
}

export const config = {
    matcher:'/profile/:path*',
};

Her's what i tried:

import { NextResponse, NextRequest } from "next/server";

export function profileMiddleware(request: NextRequest) {
  const userId = request.cookies.get("userId");

  if (!userId) {
    return NextResponse.redirect(
      new URL("/auth/login", request.nextUrl.origin).href
    );
  }
  return NextResponse.next();
}

export function authMiddleware(request: NextRequest) {
  const userId = request.cookies.get("userId");

  if (userId) {
    return NextResponse.redirect(
      new URL("/", request.nextUrl.origin).href
    );
  }
  return NextResponse.next();
}

export default {
  middleware: [
    {
      matcher: '/profile/:path*',
      handler: profileMiddleware,
    },
    {
      matcher: '/auth/:path*',
      handler: authMiddleware,
    },
  ],
};
  • 1
    According to this article: [How to Chain Multiple Middleware Functions in NextJS](https://reacthustle.com/blog/how-to-chain-multiple-middleware-functions-in-nextjs), you need to write your own middleware that will stack the other middleware, there is no builtin feature to combine middlewares. – jcubic Jul 03 '23 at 09:37
  • https://nextjs.org/docs/messages/middleware-upgrade-guide – Naveen Nizam Jul 03 '23 at 11:55
  • Hey, I have two middlewares and two configs, how to combine them? – Mykyta Aug 31 '23 at 12:58

0 Answers0