Next.js Discord

Discord Forum

Sometimes the middleware is not being triggered

Unanswered
Bombay posted this in #help-forum
Open in Discord
BombayOP
In Next.JS 13.5.6 i've a middleware setup, which works as I expected but sometimes the middleare doesn't executes. Following is the link of my screen-record.
https://drive.google.com/file/d/1XaV0j5I9YpbqN84zegkcQ_ANFTibpzJD/view?usp=sharing

In the middleware /order-confirmation is protected for only authenticated users, else they'll be redirected to login page. In the video it is visible that it works as expected first time but 2nd time it didn't, I've a console.log in the middleware, from that I'm seeing that the middleware is not ran 2nd time.
Following is the middleware
const protectedPaths = [
  routes.userProfile,
  routes.orderConfirmation, // = "/order-confirmation"
  routes.orderSuccess,
  routes.orderHistory,
  routes.reservationHistory,
];
const guestOnlyPaths = [
  routes.login,
  routes.signup,
  routes.forgetPassword,
  routes.resetPassword,
];


export function middleware(req: NextRequest) {
  const { pathname, searchParams } = req.nextUrl;
  searchParams.append('pathname', pathname);

  const redirectUrl = `/login?${searchParams.toString()}`;

  const authCookie = req.cookies.has(AUTH_COOKIE_NAME);

  // redirect to log in route if requested protected path
  console.log({
    authCookie,
    pathname,
  });
  if (!authCookie && protectedPaths.includes(pathname)) {
    return NextResponse.redirect(
      new URL(redirectUrl, req.url)
    );
  }

  // redirect to home if user is logged in & tried to visit guest only path
  if (authCookie && guestOnlyPaths.includes(pathname)) {
    return NextResponse.redirect(
      new URL(routes.home, req.url)
    );
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    // protected routes
    '/profile',
    '/order-confirmation',
    '/order-success',
    '/order-history',
    '/reservation/history',

    // guest routes
    '/login',
    '/signup',
    '/forget-password',
    '/reset-password',
  ],
};

I'm willing to provide any info needed to investigate this issue.

6 Replies

BombayOP
I've checked that the issue exists in latest versoin of next too. Created a bug on the github repo: https://github.com/vercel/next.js/issues/58025
you need to do a full reload on logout.
BombayOP
Thank you for the info, Is there any way to avoid that? I also wonder why it works after (around) 30 seconds? If this is in the docs, pls point me there.
& this is not only for logout issue, in my screencast you can see that switching between 2 routes also causes this issue where middleware is not getting executed for some time. how to deal with that?