Cant redirect from Server Action
Answered
Savannah posted this in #help-forum

SavannahOP
I have a Page (which is a server component) that has the following component.
The
All works fine. The console.log is showing, but the
What can be wrong? It's really hard to understand...
<div className="mb-8">
<CreateListButton
onCreate={async () => {
'use server'
try {
const createdList = await serverActions.createList();
console.log('$createdList', createdList);
redirect('/foo');
} catch (err) {
console.log('error creating list to debug: ', err);
}
}}
/>
</div>
The
CreateListButton
component has the 'use client' directive. The property being passed is a Server Action.All works fine. The console.log is showing, but the
redirect
is not working at all.What can be wrong? It's really hard to understand...
Answered by Ray
because
redirect
will throw an error and next will redirect the page when next catch the error
7 Replies

SavannahOP
Lol thanks a lot for the quick response. But what's best practice on handling errors within the Server Action then?

@Savannah I have a Page (which is a server component) that has the following component.
<div className="mb-8">
<CreateListButton
onCreate={async () => {
'use server'
try {
const createdList = await serverActions.createList();
console.log('$createdList', createdList);
redirect('/foo');
} catch (err) {
console.log('error creating list to debug: ', err);
}
}}
/>
</div>
The `CreateListButton` component has the 'use client' directive. The property being passed is a Server Action.
All works fine. The console.log is showing, but the `redirect` is not working at all.
What can be wrong? It's really hard to understand...

try this code
import { isRedirectError } from "next/dist/client/components/redirect";
try {
const createdList = await serverActions.createList();
console.log('$createdList', createdList);
redirect('/foo');
} catch (err) {
if (isRedirectError(err)) {
throw error;
}
console.log('error creating list to debug: ', err);
}
you just have to rethrow the error when its an NEXT_REDIRECT error

SavannahOP
Moving the
redirect
outside of the try/catch works indeed
@Savannah Moving the `redirect` outside of the try/catch works indeed

yeah that works too
if you are going to use
redirect
inside a try/catch block, you should check the error and rethrow