Next.js Discord

Discord Forum

Checking only session cookie instead of DB session in middleware?

Unanswered
Florian posted this in #help-forum
Open in Discord
Does this make sense when using database sessions? I check only the session cookie and redirect to /login if it doesn't exist.

I don't do this for security, but for UX. Most of the requests in my app are handled client-side and before any user-specific data is fetched, another authorization check is done. So I mostly don't need the session inside the page.tsx.

However, when a user logs out in another tab they can still navigate the app and see a bunch of error messages (because they get 401s everywhere). So I thought this would be a lightweight way to mitigate this problem. Does it make sense?

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

export function middleware(request: NextRequest) {
  const authCookie = request.cookies.get("auth_session");

  if (!authCookie?.value) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: "/((?!login|signup|_next/static|_next/image|favicon.ico).*)",
};

0 Replies