---
description: Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook.
---
# next/router
> Before moving forward, we recommend you to read [Routing Introduction](/docs/routing/introduction.md) first.
## useRouter
If you want to access the [`router` object](#router-object) inside any function component in your app, you can use the `useRouter` hook, take a look at the following example:
```jsx
import { useRouter } from 'next/router'
function ActiveLink({ children, href }) {
const router = useRouter()
const style = {
marginRight: 10,
color: router.pathname === href ? 'red' : 'black',
}
const handleClick = (e) => {
e.preventDefault()
router.push(href)
}
return (
{children}
)
}
export default ActiveLink
```
> `useRouter` is a [React Hook](https://reactjs.org/docs/hooks-intro.html), meaning it cannot be used with classes. You can either use [withRouter](#withRouter) or wrap your class in a function component.
## `router` object
The following is the definition of the `router` object returned by both [`useRouter`](#useRouter) and [`withRouter`](#withRouter):
- `pathname`: `String` - Current route. That is the path of the page in `/pages`
- `query`: `Object` - The query string parsed to an object. It will be an empty object during prerendering if the page doesn't have [data fetching requirements](/docs/basic-features/data-fetching.md). Defaults to `{}`
- `asPath`: `String` - Actual path (including the query) shown in the browser
Additionally, the following methods are also included inside `router`:
### router.push
Examples
Redirecting...
} ``` #### With URL object You can use a URL object in the same way you can use it for [`next/link`](/docs/api-reference/next/link.md#with-url-object). Works for both the `url` and `as` parameters: ```jsx import { useRouter } from 'next/router' export default function ReadMore({ post }) { const router = useRouter() return ( { router.push({ pathname: '/post/[pid]', query: { pid: post.id }, }) }} > Click here to read more ) } ``` ### router.replace Similar to the `replace` prop in [`next/link`](/docs/api-reference/next/link.md), `router.replace` will prevent adding a new URL entry into the `history` stack. ```jsx router.replace(url, as, options) ``` - The API for `router.replace` is exactly the same as the API for [`router.push`](#router.push). #### Usage Take a look at the following example: ```jsx import { useRouter } from 'next/router' export default function Page() { const router = useRouter() return router.replace('/home')}>Click me } ``` ### router.prefetch Prefetch pages for faster client-side transitions. This method is only useful for navigations without [`next/link`](/docs/api-reference/next/link.md), as `next/link` takes care of prefetching pages automatically. > This is a production only feature. Next.js doesn't prefetch pages on development. ```jsx router.prefetch(url, as) ``` - `url` - The URL to prefetch, that is, a path with a matching page - `as` - Optional decorator for `url`. Before Next.js 9.5.3 this was used to prefetch dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked #### Usage Let's say you have a login page, and after a login, you redirect the user to the dashboard. For that case, we can prefetch the dashboard to make a faster transition, like in the following example: ```jsx import { useCallback, useEffect } from 'react' import { useRouter } from 'next/router' export default function Login() { const router = useRouter() const handleSubmit = useCallback((e) => { e.preventDefault() fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ /* Form data */ }), }).then((res) => { // Do a fast client-side transition to the already prefetched dashboard page if (res.ok) router.push('/dashboard') }) }, []) useEffect(() => { // Prefetch the dashboard page router.prefetch('/dashboard') }, []) return ( ) } ``` ### router.beforePopState In some cases (for example, if using a [Custom Server](/docs/advanced-features/custom-server.md)), you may wish to listen to [popstate](https://developer.mozilla.org/en-US/docs/Web/Events/popstate) and do something before the router acts on it. ```jsx router.beforePopState(cb) ``` - `cb` - The function to run on incoming `popstate` events. The function receives the state of the event as an object with the following props: - `url`: `String` - the route for the new state. This is usually the name of a `page` - `as`: `String` - the url that will be shown in the browser - `options`: `Object` - Additional options sent by [router.push](#router.push) If `cb` returns `false`, the Next.js router will not handle `popstate`, and you'll be responsible for handling it in that case. See [Disabling file-system routing](/docs/advanced-features/custom-server.md#disabling-file-system-routing). #### Usage You could use `beforePopState` to manipulate the request, or force a SSR refresh, as in the following example: ```jsx import { useEffect } from 'react' import { useRouter } from 'next/router' export default function Page() { const router = useRouter() useEffect(() => { router.beforePopState(({ url, as, options }) => { // I only want to allow these two routes! if (as !== '/' && as !== '/other') { // Have SSR render bad routes as a 404. window.location.href = as return false } return true }) }, []) returnWelcome to the page
} ``` ### router.back Navigate back in history. Equivalent to clicking the browser’s back button. It executes `window.history.back()`. #### Usage ```jsx import { useRouter } from 'next/router' export default function Page() { const router = useRouter() return router.back()}>Click here to go back } ``` ### router.reload Reload the current URL. Equivalent to clicking the browser’s refresh button. It executes `window.location.reload()`. #### Usage ```jsx import { useRouter } from 'next/router' export default function Page() { const router = useRouter() return router.reload()}>Click here to reload } ``` ### router.events{router.pathname}
} export default withRouter(Page) ```