How does NextResponse.redirect work?
Unanswered
Polar bear posted this in #help-forum
Polar bearOP
I'm trying to handle user logout in a route handler and then redirect to the login page.
I send the request in a client component:
And respond to the request in the route handler:
User is logged out, but the client is not redirected to the login page. Doesn't matter if I use
I send the request in a client component:
async function handleLogout() {
const response = await fetch('/auth/logout', {
method: 'POST',
});
}And respond to the request in the route handler:
// /auth/logout/route.ts
import { NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
// handle logout business...
return NextResponse.redirect(new URL('/login', request.url));
}User is logged out, but the client is not redirected to the login page. Doesn't matter if I use
${request.url.origin}/login as the URL. In the client component the response object's redirected is true. The /login URL is valid, I can navigate there if I enter it manually.2 Replies
to send redirect on server, you need to use server actions, but as it is not stable yet, you should use
useRouter.push to redirect after fetch requestPolar bearOP
I see. Thanks for then info!