#useRouter

1 messages · Page 1 of 1 (latest)

merry ridgeBOT
#

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

#

In Next.js, the useRouter hook is specifically designed for use in Client Components to programmatically change routes. If you want to move a component to the server side, you won't be able to use useRouter directly because it is not supported in Server Components.

Instead, you should handle routing differently on the server side. Here are a few alternatives:

  1. Server-Side Redirects: You can use server-side redirects in your API routes or in the getServerSideProps function if you are still using the pages directory. This approach allows you to redirect users based on server-side logic.

  2. Next.js Middleware: You can use Next.js Middleware to handle redirects and other routing logic at the edge, before the request reaches your application.

  3. Link Component: If you are moving logic that involves navigation to a Server Component, consider whether you can use the <Link> component in a Client Component that is nested within the Server Component.

Here is an example of how you might handle a redirect in a Server Component using Next.js Middleware:

// middleware.ts
import { NextResponse } from 'next/server'

export function middleware(request) {
  const url = request.nextUrl.clone()
  if (url.pathname === '/old-path') {
    url.pathname = '/new-path'
    return NextResponse.redirect(url)
  }
  return NextResponse.next()
}

For more information on how to handle routing and redirects in Next.js, you can refer to the official documentation:

If you need to programmatically navigate within a Client Component, you should continue using the useRouter hook as shown in the examples provided in the knowledge sources:

'use client'
#

import { useRouter } from 'next/navigation'

export default function Page() {
const router = useRouter()

return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}

(See **useRouter API reference** (<https://nextjs.org/docs/app/api-reference/functions/use-router>) for more details.)

If you have any specific requirements or scenarios, please provide more details so I can assist you further.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------