router.push() need to be called twice in order to work
Unanswered
PepeW posted this in #help-forum
PepeWOP
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
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.
I have no errors in the VSCode console neither in the browser console.
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>) {
setIsLoading(true)
try {
const response = await signIn("credentials", {
email: formValues.email,
password: formValues.password,
redirect: false,
})
if (response?.error) {
setOpenModal(true)
setErrorModal(translationsAuthentication.error_signin)
} else {
console.log(searchParams.get("callbackUrl") || "/") // Here I have the right callback (even on the first click)
router.push(searchParams.get("callbackUrl") || "/")
}
} catch (error) {
setOpenModal(true)
setErrorModal(translationsAuthentication.error_signin)
}
setIsLoading(false)
}
...
I have no errors in the VSCode console neither in the browser console.