CodePark/ questions / Server Actions
START PRACTICINGPRACTICE
Frontend question · Next.js › Server Actions

Which Server Action correctly redirects after a successful save?

// Version A
try {
  await db.post.create({ data });
  redirect("/posts");
} catch (e) {
  return { error: "Failed to save" };
}

// Version B
try {
  await db.post.create({ data });
} catch (e) {
  return { error: "Failed to save" };
}
redirect("/posts");
Version B, because redirect() throws a special error that the catch in Version A would swallow

Version B is correct. redirect() works by throwing a special framework error, so it never returns. In Version A the catch block catches that error and returns an error result instead of redirecting. So call redirect() after the try/catch. The tempting "Version A, because redirect must run inside the try block" is wrong for exactly that reason.