Next.js Discord

Discord Forum

Redirect not work in try and catch for async actions

Answered
Billy posted this in #help-forum
Open in Discord
BillyOP
I'm using an async action function under "use server" directive term, this function handles the login process for the user. I wanna redirect the user if the credentials right to another route for example the /dashboard route, so I should insert the redirect('/dashboard') into the try wrapper, but it not working until I add it to out of the try and catch blocks.
is there another way to handle this process?

actions.ts
export async function handleSignIn(
  username: string,
  password: string,
  remeberMe: boolean
) {

  const FD: FormData = new FormData();
  FD.append("UserName", username);
  FD.append("Password", password);
  try {
    const res = await http.post(endpoints.auth.signin, FD);

    const token = await res.data.data.accessToken;
    const refreshToken = await res.data.data.refreshToken;
    if (token) {
      cookies().set("token", token, { path: "/", domain: "localhost" });
      cookies().set("refresh-token", JSON.stringify(refreshToken));
      console.log("token saved");
    }

    console.log("successfully logined");

    revalidatePath("/dashboard");
    redirect("/dashboard");
  } catch (error) {
    console.log(error);
  }
  //!NOTE: if I added the redirect in this scope it works fine, but it redirect the user even if his credentials wrong
  // revalidatePath("/dashboard");
  // redirect("/dashboard");
}
Answered by @ts-ignore
you rethrow the error when it is redirect error which nextjs knows how to handle internally
View full answer

14 Replies

BillyOP
@Billy Click to see attachment
if(isRedirectError(error)) throw error
BillyOP
??????????? is that the solution?
it works
how it comes?
you rethrow the error when it is redirect error which nextjs knows how to handle internally
Answer
if you catch it, there's no "NEXT_REDIRECT" error for nextjs to handle as it is handled by your catch block
BillyOP
thank you man
you saved me
I've over 10 posts this week in the @help-forum about server ,client and router issues, am I a dump or Nextjs concept is different?
the new router is hard to wrap your around me, even I have problems sometime
BillyOP
I think the app router concept is harder than page router