Next.js Discord

Discord Forum

Middleware not working correctly

Unanswered
Norwegian Forest Cat posted this in #help-forum
Open in Discord
Norwegian Forest CatOP
Hey,

I don't get console log from my middleware when visiting http://localhost:3000/auth/sign-in.
export async function middleware(request: NextRequest) {
  const response = NextResponse.next();
  const requestCookie = request.cookies.get("pb_auth");

  console.log("MIDDLEWARE");

  const cookie = await getNextjsCookie(requestCookie);
  if (cookie) {
    try {
      pb.authStore.loadFromCookie(cookie);
    } catch (error) {
      pb.authStore.clear();
      response.headers.set("set-cookie", pb.authStore.exportToCookie({ httpOnly: false }));
    }
  }

  try {
    // Get an up-to-date auth store state by verifying and refreshing the loaded auth model (if any)
    pb.authStore.isValid && (await pb.collection(PB_USERS).authRefresh());
  } catch (err) {
    // Clear the auth store on failed refresh
    pb.authStore.clear();
    response.headers.set("set-cookie", pb.authStore.exportToCookie({ httpOnly: false }));
  }

  if (pb.authStore.model && request.nextUrl.pathname.startsWith("/auth")) {
    // Already authenticated and trying to access authentication pages - redirect
    const nextUrl = request.headers.get("next-url") as string;
    if (nextUrl) {
      const redirectTo = new URL(nextUrl, request.url);
      return NextResponse.redirect(redirectTo);
    }

    const redirectTo = new URL("/workspace/dashboard", request.url);
    return NextResponse.redirect(redirectTo);
  }

  if (!pb.authStore.model && request.nextUrl.pathname.startsWith("/workspace")) {
    const redirectTo = new URL("/auth/sign-in", request.url);

    const nextPath = request.nextUrl.pathname || "/workspace/dashboard";
    redirectTo.search = new URLSearchParams({ next: nextPath }).toString();

    return NextResponse.redirect(redirectTo);
  }

  return response;
}

export const config = {
  matcher: ["/auth/:path*", "/workspace/:path*"],
};

1 Reply

Norwegian Forest CatOP
I have a middleware in which I check if I have cookie pb_auth, read that cookie and check if the JWT is valid via PocketBase sdk, based on that I redirect if needed:

Once I do my OAuth and I have cookie set it doesn't allow me to route to /auth paths as desired.
Problem is once I sign out - clean out cookie, clear my authStore and reroute back to /auth path, it doesn't allow me to. It's as if it's getting cached or something.

Note that most of my pages do "use client". Is middleware sometime that is SSR only and I just have misconception - should handle redirect through some state management instead?