Next.js Discord

Discord Forum

`router.push()` doing nothing

Answered
PepeW posted this in #help-forum
Open in Discord
Avatar
I have a sign-in form and when the form is submitted I want to redirect the user using a router.push().

Here's my code:
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(t("error_signin"))
      } else {
        const urlToBeRedirected = searchParams.get("callbackUrl")
        if (urlToBeRedirected) {
          // GET TRIGGERED BUT DOESN'T DO ANYTHING
          router.push(urlToBeRedirected)
        } else {
          router.push("/")
        }
      }
    } catch (error) {
      setOpenModal(true)
      setErrorModal(t("error_signin"))
    }
    setIsLoading(false)
  }


The problem is that even though router.push() is triggered every time, I somehow get redirected 1/5th of the time.

PS: I've tried using the callbackUrl property but I never get redirected.
Answered by PepeW
Ok I think the redirect: false was at fault.

Here's the new code:
async function onSubmit(formValues: z.infer<typeof formSchema>) {
    setIsLoading(true)
    try {
      const response = await signIn("credentials", {
        email: formValues.email,
        password: formValues.password,
        callbackUrl: searchParams.get("callbackUrl") || "/",
      })
      if (response?.error) {
        setOpenModal(true)
        setErrorModal(t("error_signin"))
      }
    } catch (error) {
      setOpenModal(true)
      setErrorModal(t("error_signin"))
    }
    setIsLoading(false)
  }
View full answer

2 Replies

Avatar
European sprat
Is it the submit handler for the form? Do you need to preventDefault?
Avatar
Ok I think the redirect: false was at fault.

Here's the new code:
async function onSubmit(formValues: z.infer<typeof formSchema>) {
    setIsLoading(true)
    try {
      const response = await signIn("credentials", {
        email: formValues.email,
        password: formValues.password,
        callbackUrl: searchParams.get("callbackUrl") || "/",
      })
      if (response?.error) {
        setOpenModal(true)
        setErrorModal(t("error_signin"))
      }
    } catch (error) {
      setOpenModal(true)
      setErrorModal(t("error_signin"))
    }
    setIsLoading(false)
  }
Answer