Next.js 37: Redirecting After a Mutation
easy⏱ 5 mincoursenextjs
redirect() inside an action
Call redirect(path) after a mutation completes to send the user straight to the result — e.g. redirect('/posts/' + post.id) right after db.post.create(...). Under the hood, redirect() throws; Next.js's framework code catches that specific throw and performs the navigation, so nothing after the call ever executes.
'use server';
import { redirect } from 'next/navigation';
export async function createPost(formData: FormData) {
const title = formData.get('title');
const post = await db.post.create({ data: { title } });
redirect(`/posts/${post.id}`); // never returns — throws internally
}
Don't swallow the throw
Because redirect() works by throwing, wrapping the call in a try { ... } catch { ... } that catches everything will accidentally catch the redirect too and stop the navigation. Only catch the errors you expect (e.g. a database error), or call redirect() after your try/catch block has already finished.
Client-side vs server-side redirect
redirect() from next/navigation works in Server Actions, Server Components, and Route Handlers. In a Client Component, you'd instead use the useRouter() hook's router.push(path) — same end result (navigate the user), different API for a different environment.
Simulate a redirect
Build a form with a title field and a simulated createPostAction. On success, instead of showing a message inline, switch a view state from 'form' to 'detail' and render a different screen showing the new post — comment it as simulating redirect(), since there's no real router in this sandbox. Keep export default App.