Next.js Discord

Discord Forum

CLIENT SIDE NAVIGATION depending upon api response

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Brown bearOP
version: Next JS 14.2

I'm using useRouter from next/navigation,
'use client'
const router = useRouter();
useEffect(()=>{
if(isFetched) {
router.push("/login")
}
},[isFetched])

its not navigating client side, it navigates user to login page by reloading the page

4 Replies

@Brown bear version: Next JS 14.2 I'm using useRouter from next/navigation, 'use client' const router = useRouter(); useEffect(()=>{ if(isFetched) { router.push("/login") } },[isFetched]) its not navigating client side, it navigates user to login page by reloading the page
it looks like you are checking clientside if the user is currently logged in. That's not a good practice. Fetch it serverside and check if the user is logged in serverside. If so, render the content, else redirect to the login page.

The easiest way to do that is by creating a [middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware)
Brown bearOP
Thanks for the reponse
but the problem statement is redirecting user depending on api response after some user actions

'use client'
const router = useRouter();
useEffect(()=>{
if(isxyz) {
router.push("/xyz")
return;
}
router.push("/abc");
},[isxyz])

its not navigating client side, it navigates user to xyz/ abc page by reloading the page
@Brown bear Thanks for the reponse but the problem statement is redirecting user depending on api response after some user actions 'use client' const router = useRouter(); useEffect(()=>{ if(isxyz) { router.push("/xyz") return; } router.push("/abc"); },[isxyz]) its not navigating client side, it navigates user to xyz/ abc page by reloading the page
yes, I understood, that you fetch stuff clientside and redirect clientside via the router. But it does not work directly. It works only after reloading the page.

Yes. I understood your initial problem and I am telling you, that you check the current auth status serverside and not clientside.

So either share more details so I can understand why you are doing this or use the method via a serverside check (like middleware for example)
@Brown bear solved?