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. Here's a pattern: ```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 allows the redirect to propagate correctly while still handling errors gracefully.
7789775d-577c-4f53-954d-7a90cde83b09
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. Here's a pattern:
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 allows the redirect to propagate correctly while still handling errors gracefully.