Answer
In Next.js 15, `redirect()` inside a server action throws an error, which is caught by the `try/catch` block. To handle redirects properly, use `throw new RedirectError()` instead. Here's a clean 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.
15cd8e62-7235-4d77-b62c-0ddf9c974347
In Next.js 15, redirect() inside a server action throws an error, which is caught by the try/catch block. To handle redirects properly, use throw new RedirectError() instead. Here's a clean 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.