Next.js Discord

Discord Forum

redirect is not working inside a setTimout

Answered
Naeemgg posted this in #help-forum
Open in Discord
tried using redirect() from next/navigation inside a setTimout to redirect the user to a dif page after a couple of seconds but its not working at all and I can see some error messages in the terminal as well.
Answered by Ray
you could create a client component like this
"use client"
function Redirect() {
  const router = useRouter()
  useEffect(() => {
    const timer = setTimeout(() => {
      router.push('/')
    }, 1000)

    return () => {
      clearTimeout(timer)
    }
  },[router])

  return null
}
View full answer

20 Replies

these errors
I guess that you want to redirect from client-side, you need to use browser's history API or next's useRouter hook:

app/example-client-component.tsx
'use client'
 
import { useRouter } from 'next/navigation'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.push('/dashboard')}>
      Dashboard
    </button>
  )
}


https://nextjs.org/docs/app/api-reference/functions/use-router

Hope that will clarify this for you 🙂
I want to redirect user to lets say /posts from /user after n number of seconds
@Naeemgg these errors
btw, these error doesn't look like related to redirect
the whole page is just some texts so its a SC
can't it be done within here
or do I need to create a CC for this purpose?
I shared the wrong link
oh you have content in the page?
posts
retrieved from db
so no user interaction is present
you could create a client component like this
"use client"
function Redirect() {
  const router = useRouter()
  useEffect(() => {
    const timer = setTimeout(() => {
      router.push('/')
    }, 1000)

    return () => {
      clearTimeout(timer)
    }
  },[router])

  return null
}
Answer
and render it on the page