Next.js Discord

Discord Forum

Cant redirect from Server Action

Answered
Savannah posted this in #help-forum
Open in Discord
Avatar
SavannahOP
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...
Answered by Ray
because redirect will throw an error and next will redirect the page when next catch the error
Image
View full answer

7 Replies

Avatar
Ray
because redirect will throw an error and next will redirect the page when next catch the error
Image
Answer
Avatar
SavannahOP
Lol thanks a lot for the quick response. But what's best practice on handling errors within the Server Action then?
Avatar
Ray
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
Avatar
SavannahOP
Moving the redirect outside of the try/catch works indeed
Avatar
Ray
yeah that works too
if you are going to use redirect inside a try/catch block, you should check the error and rethrow