Next.js Discord

Discord Forum

router.push() need to be called twice in order to work

PepeW posted this in #help-forum
Open in Discord
First of all I would clarify the fact that a normal signin is working fine in my app.

The problem takes place when I need to signin when trying to access an unauthorized page.

I get redirected (thanks to middleware.ts) to the signin page. Here I have 2 scenarios to highlight this bug:
1. I press the signin button, nothing happen, I press a second time and now I get redirected to the callback url.
2. I reload the signin page, press the signin button and now I get redirected to the callback url.

// middleware.ts
export async function middleware(request: NextRequest) {
  const session = await getToken({ req: request })
  const pathname = request.nextUrl.pathname

  const isNotAuthorizedToNavigate = ...
  if (isNotAuthorizedToNavigate) {
    const callbackUrl = request.nextUrl.pathname
    const loginUrl = new URL("/connexion", request.url)
    loginUrl.searchParams.set("callbackUrl", callbackUrl)
    return NextResponse.redirect(loginUrl)

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

// SigninForm.tsx
async function onSubmit(formValues: z.infer<typeof formSchema>) {
    try {
      const response = await signIn("credentials", {
        password: formValues.password,
        redirect: false,
      if (response?.error) {
      } else {
        console.log(searchParams.get("callbackUrl") || "/") // Here I have the right callback (even on the first click)
        router.push(searchParams.get("callbackUrl") || "/")
    } catch (error) {

I have no errors in the VSCode console neither in the browser console.

0 Replies