Next.js Discord

Discord Forum

Redirect seemed to have happened, but page still remains the same.

Unanswered
dr_kakapo posted this in #help-forum
Open in Discord
Hi, here.
In my NextJS app router app. In my /verify page, a form with mobileNumber is submitted to this /api/auth/login route handler, and it should redirect to the /balance page. In the Chrome console. I see the 302 POST was assumed, but the browser still remained the /verify page. What's happening here?

import Auth from "@/lib/auth";
import { headers, cookies } from "next/headers";
import { NextResponse } from "next/server";
import { redirect } from "next/navigation";

export async function POST(req) {
  console.log("POST to /login");
  const { mobileNumber } = await req.json();

  if (!mobileNumber)
    return new NextResponse(null, {
      status: 400,
      statusText: "Mobile number is missing",
    });

  await Auth.server.createSession(mobileNumber);

  const url = req.nextUrl.clone();
  url.pathname = "/balance";

  redirect(url);
}

3 Replies

I resolved the issue already. It's not a bug or NextJS issue at all. It's a browser behavioural thing.
FYI. When you get a redirect response for an async request, you need to capture the response and redirect from the client side. Like below:
const response = await fetch("the-endpoint-url");
if(response.redirected){
   window.location.href(response.url)
}