/

How to Use the Next.js Router

How to Use the Next.js Router

In this blog post, we’ll explore how to use the next/router package to control routes in Next.js. We’ll focus on programmatic routing changes, using the Next.js Router directly.

Linking pages in Next.js using the Link component is a convenient way to handle routing declaratively. However, there are cases where you need to trigger a routing change programmatically. To do this, we can access the Next.js Router provided by the next/router package and call its push() method.

Here’s an example of accessing the router:

1
2
3
4
5
6
import { useRouter } from 'next/router'

export default () => {
const router = useRouter()
// ...
}

Once we have the router object by invoking useRouter(), we can use its methods.

Note: The router methods should only be used in frontend-facing code. To ensure this, it’s recommended to wrap the calls in the useEffect() React hook or inside componentDidMount() for React stateful components.

The most commonly used methods are push() and prefetch().

The push() method allows us to programmatically trigger a URL change in the frontend:

1
router.push('/login')

The prefetch() method allows us to programmatically prefetch a URL. This is useful when we don’t have a Link tag that automatically handles prefetching for us:

1
router.prefetch('/login')

Here’s a complete example:

1
2
3
4
5
6
7
8
9
import { useRouter } from 'next/router'

export default () => {
const router = useRouter()

useEffect(() => {
router.prefetch('/login')
})
}

You can also use the router to listen for route change events.

tags: [“Next.js”, “Router”, “Frontend Development”, “Programmatic Routing”]