redirect after signout on a protected page

In Next.js, how do we redirect the user if they sign out while on a protected page?

middleware below only gets executed on initial load
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export async function middleware(request: NextRequest) {
  const sessionCookie = getSessionCookie(request);

  if (!sessionCookie) {
    return NextResponse.redirect(new URL("/", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/settings"],
};
Was this page helpful?