Loading...
save

redirect() inside a Server Action doesn’t work, the catch block runs instead

clock icon

asked 4 hours ago

message icon

0

eye icon

3

I have a Server Action that creates a post and should then redirect to the new page. The post is saved in the database, but the redirect never happens. The catch block runs instead and logs an error called NEXT_REDIRECT.

ts

1"use server";
2
3import { redirect } from "next/navigation";
4
5export async function createPost(formData: FormData) {
6 try {
7 const post = await db.post.create({
8 data: { title: formData.get("title") as string },
9 });
10
11 redirect(`/posts/${post.id}`);
12 } catch (error) {
13 console.error("Something went wrong:", error);
14 return { error: "Could not create post" };
15 }
16}
1"use server";
2
3import { redirect } from "next/navigation";
4
5export async function createPost(formData: FormData) {
6 try {
7 const post = await db.post.create({
8 data: { title: formData.get("title") as string },
9 });
10
11 redirect(`/posts/${post.id}`);
12 } catch (error) {
13 console.error("Something went wrong:", error);
14 return { error: "Could not create post" };
15 }
16}

The form shows “Could not create post”, even though the post exists. If I remove the try/catch, the redirect works fine.

Why is redirect() being caught as an error? And what’s the clean way to keep the error handling and still redirect afterwards?

I’m on Next.js 15 with the App Router.

0 Answers

Empty state illustration

No Answers Found

The answer board is empty. Make it rain with your brilliant answer.

1

Write your answer here

Top Questions