Menu

1 / 2

Your Next.js redirect() Silently Does Nothing Because It's Inside a try/catch

DEV Community: react·Anas Sheikh·about 12 hours ago
#VQdYnsez
#devtoreact#devto#dev#redirect#error
Reading 0:00
15s threshold

A user fills in your form and clicks "Create post". The post is saved in the database. And the page shows "Could not create post".

They try again. Now there are two posts.

Nothing is wrong with your database. Your error handling caught something it was never supposed to catch.

The Code That Causes It

// app/actions.ts ' use server ' ;

import { redirect } from ' next/navigation ' ;

export async function createPost ( formData : FormData ) { try { const post = await db . post . create ({ data : { title : String ( formData . get ( ' title ' )) }, });

redirect ( `/posts/ ${ post . id } ` ); } catch ( err ) { return { error : ' Could not create post ' }; } }

Enter fullscreen mode

Exit fullscreen mode

It reads perfectly. Save the post, go to its page, and if anything fails, return an error. A tidy, defensive pattern that you have probably written a hundred times in other frameworks.

Why It Breaks

In Next.js, redirect() does not return.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.