Next.js Discord

Discord Forum

NextResponse.redirect() doesn't working as expected in middleware after upgrading nextjs to 14.2.3

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Brown bearOP
In my middleware file LoggedIn user are redirected to callbackUrl or a destination url. This works perfectly fine with nextjs v14.1.4.

After upgrading it to 14.2.3 I am facing some issues. The NextResponse.redirect() render the ui perfectly but the url are not changing. After a refresh the url works fine. I have tried chrome and firefox.

5 Replies

Brown bearOP
import { authConfig } from '@/auth.config'; import NextAuth from 'next-auth'; import { NextResponse } from 'next/server'; import { authApiRoute, authRoute, publicRoute } from '@/lib/routes'; const { auth } = NextAuth(authConfig); export default auth(({ auth, nextUrl }) => { const isLoggedIn = !!auth?.user; const isAuthRoute = authRoute.includes(nextUrl.pathname); const isPublicRoute = publicRoute.includes(nextUrl.pathname); const isAuthApiRoute = nextUrl.pathname.startsWith(authApiRoute); if (isPublicRoute || isAuthApiRoute) { return NextResponse.next(); } if (!isLoggedIn && isAuthRoute) { return NextResponse.next(); } if (isLoggedIn && isAuthRoute) { const callbackUrl = nextUrl.searchParams.get('callbackUrl'); if (callbackUrl) { if (callbackUrl.startsWith('/')) { return NextResponse.redirect(new URL(callbackUrl, nextUrl)); } if (new URL(callbackUrl).origin === nextUrl.origin) { return NextResponse.redirect(callbackUrl); } } const newUrl = new URL('/', nextUrl); return NextResponse.redirect(newUrl); } if (isLoggedIn) { return NextResponse.next(); } if (!isLoggedIn) { const loginUrl = new URL(/login?callbackUrl=${nextUrl.pathname}, nextUrl ); return NextResponse.redirect(loginUrl); } return NextResponse.next(); }); export const config = { // https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'], };
Im having the exact problem as a workaround for now im using this one the page redirected that is not updating the url
useEffect(() => {
        console.log({ pathname });
        if (pathname !== '/auth/login') {
            router.replace('/auth/login');
        }
    }, [pathname, router]);
but Im still trying to find whats the cause
Also can confirm that switching to the older version fix the problem , sadly in my case also breaks the styling of my page
Brown bearOP
anyone please help
sorry for delivering this bad news but i think this is a bug in nextjs hence you should open an issue and downgrade nextjs for now