Next.js Discord

Discord Forum

Middleware protected routes don't re-route when I log out

Unanswered
Ratonero Murciano de Huerta posted this in #help-forum
Open in Discord
Ratonero Murciano de HuertaOP
Heya, I'm setting up a project with auth.js and using middleware to protect my routes.

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;

  const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
  const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
  const isAuthRoute = authRoutes.includes(nextUrl.pathname);

  if (isApiAuthRoute) {
    return;
  }

  if (isAuthRoute) {
    if (isLoggedIn) {
      return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
    }
    return;
  }

  if (!isLoggedIn && !isPublicRoute) {
    return Response.redirect(new URL("/login", nextUrl));
  }
  return;
});

export const config = {
  matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};

It's the !isLoggedIn && !isPublicRoute check that's sort of working.

When I'm logged in on the /settings route (which is NOT a public route, hence !isPublicRoute) and log out, I am redirected to the login page as it says in the code, but my URL route is not changed. So if I try to immediately log in again I can't because it's on the incorrect URL route. If I hit F5 to refresh my window it updates to "/login".

So everything is working, but it doesn't update the URL route properly.

import { auth, signOut } from "@/auth";
import { Button } from "@/components/ui/button";

export default async function Settings() {
  const session = await auth();

  return (
    <section className="container mx-auto">
      <h2 className="text-2xl text-center mt-10 text-white">Settings page</h2>
      <p className="text-white">{JSON.stringify(session)}</p>
      <form
        action={async () => {
          "use server";
          await signOut();
        }}
      >
        <Button type="submit">Sign out</Button>
      </form>
    </section>
  );
}

This is the settings page where I log out.

2 Replies

Ratonero Murciano de HuertaOP
When I changed the sign out from "use server" to a client component with signOut from next-auth/react it works. So it doesn't seem to be working when I'm using server. Any thoughts?
im having the same problem, my workaroudn was using
 useEffect(() => {
        console.log({ pathname });
        if (pathname !== '/auth/login') {
            router.replace('/auth/login');
        }
    }, [pathname, router]);
on the login page , but still trying to find the cause , it seems like we followd the same tutorial tho , that could be the origin of the problem if its not a bug