Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS App Router - redirect() in useEffect hook

I'm currently working on a Next.js 13.4.9 project and I'm facing an issue with redirecting logged in users within a client component using the useEffect hook. I have tried a certain method, but it keeps throwing an error in the browser (NEXT_REDIRECT).

import { redirect } from 'next/navigation';

useEffect(() => {
    getRedirectResult(auth).then( async (userCredential) => {
        if (!userCredential) return;

        fetch('/api/auth/login', {
          method: 'POST',
          headers: {
            Authorization: 'Bearer ' + (await userCredential.user.getIdToken()),
          },
        }).then((res) => {
          if (res.ok) {
            try {
              redirect('/user')
            } catch (error) {
              console.log(error)
            }
          }
        })
      })
}, [])

I would really appreciate it if someone could guide me through the correct approach to redirect logged in users in Next.js using the useEffect hook. Is there an alternative method I should consider? I don't really want to use a router. Thank you in advance for your help!

Error:

Error: NEXT_REDIRECT at getRedirectError (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect.js:40:19) at redirect (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect.js:50:11) at eval (webpack-internal:///(app-client)/./src/app/(auth)/signin/page.tsx:34:82)

like image 660
Jan Phillip Schwietzer Avatar asked Sep 17 '25 14:09

Jan Phillip Schwietzer


1 Answers

if you want use redirect you can't use redirect in try, you must use redirect in catch or after try catch. this is because redirect() work is by throwing an error that Next.js can handle in order to stop execution of the code.

Here is a the link relevant, for this case : https://github.com/vercel/next.js/issues/49298#issuecomment-1542055642

like image 115
raas Avatar answered Sep 20 '25 07:09

raas