#nextjs redirect not working

1 messages · Page 1 of 1 (latest)

gusty pebbleBOT
#

Hi @calm vigil. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The issue you're experiencing might be due to the placement of the redirect() function within a try/catch block. According to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/routing/redirecting#redirect-function), the redirect() function internally throws an error, so it should be called outside of try/catch blocks.

Here's how you can modify your code:

const handleAddTemplate = async ({ template }: { template: any }) => {
    "use server";

    if (template.type === "routine") {
      const update = await prisma.routine.create({
        data: {
          title: template.title,
          userId: session.user.id,
          ...template.data,
        },
      });

      if (update.id) {
        redirect(`/dashboard/routines`);
      }
      return 500;
    }
  };

In this modified code, the redirect() function is called directly when update.id is truthy, without being wrapped in a try/catch block.

Also, please note that redirect() does not require you to use return redirect() as it uses the TypeScript never (https://www.typescriptlang.org/docs/handbook/2/functions.html#never) type.

If you're still experiencing issues, it might be due to a known issue with Next.js 14 and the app router. Some users have reported issues with redirect() not working as expected when switching between root layouts. As a workaround, some users are handling redirection on the client side via useRouter from next/navigation based on a status returned from the server action (source (https://github.com/vercel/next.js/issues/58263)).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@calm vigil kapa.ai is still learning and improving, please let us know how it did by reacting below

calm vigil
#

ilysm

#

@gusty pebble how can i use that with setTimeout?

gusty pebbleBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Using redirect() from next/navigation inside setTimeout in a useEffect hook can be tricky because setTimeout takes the call to redirect outside of the stack such that the redirection is no longer caught by the Next.js renderer.

However, a workaround suggested by a user in a Github issue (https://github.com/vercel/next.js/issues/59489) is to wrap the redirect inside startTransition. Here's how you can do it:

import { useTransition } from 'next/navigation';

// ...

const [, startTransition] = useTransition();

useEffect(() => {
  const timeout = setTimeout(() => startTransition(() => redirect("/dashboard/routines")), 5000);
  return () => clearTimeout(timeout);
}, []);

In this code, startTransition is used to ensure that the redirection error is caught by Next.js. The redirect is called after a delay of 5000 milliseconds (5 seconds) set by setTimeout. The clearTimeout in the cleanup function ensures that the timeout is cleared if the component unmounts before the timeout finishes.

Please note that this is a workaround and might not work in all cases. If you're still having issues, you might want to consider using router.push for client-side navigation.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: