Next.js Discord

Discord Forum

Redirect in middleware doesnt update URL in browser

Unanswered
cheka posted this in #help-forum
Open in Discord
Using the following code in middleware and AuthJS , after logging out , the middleware redirects to /auth/login , the page contents does change but the URL on the browser doesnt change. The logout is a server action
import { auth } from "@/auth";
import { DEFAULT_LOGIN_REDIRECT, apiAuthPrefix, authRoutes, publicRoutes } from "@/routes";
import { NextResponse } from "next/server";

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);

    console.log({ nextUrl, isLoggedIn, isApiAuthRoute, isPublicRoute, isAuthRoute });

    if (isApiAuthRoute) {
        return NextResponse.next();
    }

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

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

    return NextResponse.next();
});

export const config = {
    matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)',],
};
 

5 Replies

If I refresh the page I get the correct url , also the first redirect return NextResponse.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl)); works fine and updates the url in the browser, when return NextResponse.redirect(new URL("/auth/login", nextUrl)); is called to go back to login after logout is when the problem occurs
for now im doing this as a workaround
  useEffect(() => {
        console.log({ pathname });
        if (pathname !== '/auth/login') {
            router.replace('/auth/login');
        }
    }, [pathname, router]);

 
any advice would be helpful, including if my workaround could cause any problem in the future
Sloth bear
@cheka I just ran into this issue and wondered if you had found a solution.
@Sloth bear <@147102287033008129> I just ran into this issue and wondered if you had found a solution.
i haven't tested the new versions if it was fixed , but what I did was the workaround posted before this
js   useEffect(() => {
        console.log({ pathname });
        if (pathname !== '/auth/login') {
            router.replace('/auth/login');
        }
    }, [pathname, router]);

 
that update the url on the browser and it doesnt reload the entire page