Common Next.js errorsNEXT_REDIRECT caught in try/catch
You see Error: NEXT_REDIRECT in your logs, or a redirect after a form submit simply doesn't happen. redirect() works by throwing a special error that Next.js catches to send the redirect. If your own try/catch catches it first, the redirect is lost (and often logged as a failure).
How to fix it
Call redirect() after the try/catch, once the work has succeeded:
'use server'
import { redirect } from 'next/navigation'
export async function createPost(form: FormData) {
let id: string
try {
id = await db.posts.create(form)
} catch (e) {
return { error: 'Could not save your post' }
}
redirect(`/posts/${id}`)
}
If you need a catch-all around code that may redirect or call notFound(), rethrow Next.js's own errors first:
Let Next.js errors through import { unstable_rethrow } from 'next/navigation'
try {
await doWorkThatMayRedirect()
} catch (err) {
unstable_rethrow(err)
console.error(err)
}