Answer
In Next.js 15, `redirect()` inside a server action throws an error, which is caught by the `try/catch` block. To handle redirects cleanly, use `throw new RedirectError()` instead of `redirect()`, and catch it specifically: ```typescript async function createPost(formData: FormData) { 'use server' try { await db.insertPosts.values({ title: formData.get('title') }); throw new RedirectError('/posts'); } catch (err) { if (err instanceof RedirectError) { throw err; // Let Next.js handle the redirect } return { error: 'Failed to create post' }; } } ``` This pattern allows you to handle redirects while still catching other errors.
9d9cc93b-a6be-46fd-998b-16d1b4834284
In Next.js 15, redirect() inside a server action throws an error, which is caught by the try/catch block. To handle redirects cleanly, use throw new RedirectError() instead of redirect(), and catch it specifically:
async function createPost(formData: FormData) {
'use server'
try {
await db.insertPosts.values({ title: formData.get('title') });
throw new RedirectError('/posts');
} catch (err) {
if (err instanceof RedirectError) {
throw err; // Let Next.js handle the redirect
}
return { error: 'Failed to create post' };
}
}This pattern allows you to handle redirects while still catching other errors.