useRouter
If you want to access the router
object inside any function component in your app, you can use the useRouter
hook, take a look at the following example:
useRouter
is a React Hook, meaning it cannot be used with classes. You can either use withRouter or wrap your class in a function component.
router
object
The following is the definition of the router
object returned by both useRouter
and withRouter
:
pathname
:String
- The path for current route file that comes after/pages
. Therefore,basePath
,locale
and trailing slash (trailingSlash: true
) are not included.query
:Object
- The query string parsed to an object, including dynamic route parameters. It will be an empty object during prerendering if the page doesn't use Server-side Rendering. Defaults to{}
asPath
:String
- The path as shown in the browser including the search params and respecting thetrailingSlash
configuration.basePath
andlocale
are not included.isFallback
:boolean
- Whether the current page is in fallback mode.basePath
:String
- The active basePath (if enabled).locale
:String
- The active locale (if enabled).locales
:String[]
- All supported locales (if enabled).defaultLocale
:String
- The current default locale (if enabled).domainLocales
:Array<{domain, defaultLocale, locales}>
- Any configured domain locales.isReady
:boolean
- Whether the router fields are updated client-side and ready for use. Should only be used inside ofuseEffect
methods and not for conditionally rendering on the server. See related docs for use case with automatically statically optimized pagesisPreview
:boolean
- Whether the application is currently in preview mode.
Using the
asPath
field may lead to a mismatch between client and server if the page is rendered using server-side rendering or automatic static optimization. Avoid usingasPath
until theisReady
field istrue
.
The following methods are included inside router
:
router.push
Handles client-side transitions, this method is useful for cases where next/link
is not enough.
url
:UrlObject | String
- The URL to navigate to (see Node.JS URL module documentation forUrlObject
properties).as
:UrlObject | String
- Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes.options
- Optional object with the following configuration options:scroll
- Optional boolean, controls scrolling to the top of the page after navigation. Defaults totrue
shallow
: Update the path of the current page without rerunninggetStaticProps
,getServerSideProps
orgetInitialProps
. Defaults tofalse
locale
- Optional string, indicates locale of the new page
You don't need to use
router.push
for external URLs. window.location is better suited for those cases.
Navigating to pages/about.js
, which is a predefined route:
Navigating pages/post/[pid].js
, which is a dynamic route:
Redirecting the user to pages/login.js
, useful for pages behind authentication:
Resetting state after navigation
When navigating to the same page in Next.js, the page's state will not be reset by default as React does not unmount unless the parent component has changed.
In the above example, navigating between /one
and /two
will not reset the count . The useState
is maintained between renders because the top-level React component, Page
, is the same.
If you do not want this behavior, you have a couple of options:
-
Manually ensure each state is updated using
useEffect
. In the above example, that could look like: -
Use a React
key
to tell React to remount the component. To do this for all pages, you can use a custom app:
With URL object
You can use a URL object in the same way you can use it for next/link
. Works for both the url
and as
parameters:
router.replace
Similar to the replace
prop in next/link
, router.replace
will prevent adding a new URL entry into the history
stack.
- The API for
router.replace
is exactly the same as the API forrouter.push
.
Take a look at the following example:
router.prefetch
Prefetch pages for faster client-side transitions. This method is only useful for navigations without next/link
, as next/link
takes care of prefetching pages automatically.
This is a production only feature. Next.js doesn't prefetch pages in development.
url
- The URL to prefetch, including explicit routes (e.g./dashboard
) and dynamic routes (e.g./product/[id]
)as
- Optional decorator forurl
. Before Next.js 9.5.3 this was used to prefetch dynamic routes.options
- Optional object with the following allowed fields:locale
- allows providing a different locale from the active one. Iffalse
,url
has to include the locale as the active locale won't be used.
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:
router.beforePopState
In some cases (for example, if using a Custom Server), you may wish to listen to popstate and do something before the router acts on it.
cb
- The function to run on incomingpopstate
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 apage
as
:String
- the url that will be shown in the browseroptions
:Object
- Additional options sent by 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.
You could use beforePopState
to manipulate the request, or force a SSR refresh, as in the following example:
router.back
Navigate back in history. Equivalent to clicking the browser’s back button. It executes window.history.back()
.
router.reload
Reload the current URL. Equivalent to clicking the browser’s refresh button. It executes window.location.reload()
.
router.events
You can listen to different events happening inside the Next.js Router. Here's a list of supported events:
routeChangeStart(url, { shallow })
- Fires when a route starts to changerouteChangeComplete(url, { shallow })
- Fires when a route changed completelyrouteChangeError(err, url, { shallow })
- Fires when there's an error when changing routes, or a route load is cancellederr.cancelled
- Indicates if the navigation was cancelled
beforeHistoryChange(url, { shallow })
- Fires before changing the browser's historyhashChangeStart(url, { shallow })
- Fires when the hash will change but not the pagehashChangeComplete(url, { shallow })
- Fires when the hash has changed but not the page
Good to know: Here
url
is the URL shown in the browser, including thebasePath
.
For example, to listen to the router event routeChangeStart
, open or create pages/_app.js
and subscribe to the event, like so:
We use a Custom App (
pages/_app.js
) for this example to subscribe to the event because it's not unmounted on page navigations, but you can subscribe to router events on any component in your application.
Router events should be registered when a component mounts (useEffect or componentDidMount / componentWillUnmount) or imperatively when an event happens.
If a route load is cancelled (for example, by clicking two links rapidly in succession), routeChangeError
will fire. And the passed err
will contain a cancelled
property set to true
, as in the following example:
The next/compat/router
export
This is the same useRouter
hook, but can be used in both app
and pages
directories.
It differs from next/router
in that it does not throw an error when the pages router is not mounted, and instead has a return type of NextRouter | null
.
This allows developers to convert components to support running in both app
and pages
as they transition to the app
router.
A component that previously looked like this:
Will error when converted over to next/compat/router
, as null
can not be destructured. Instead, developers will be able to take advantage of new hooks:
This component will now work in both pages
and app
directories. When the component is no longer used in pages
, you can remove the references to the compat router:
Using useRouter
outside of Next.js context in pages
Another specific use case is when rendering components outside of a Next.js application context, such as inside getServerSideProps
on the pages
directory. In this case, the compat router can be used to avoid errors:
Potential ESLint errors
Certain methods accessible on the router
object return a Promise. If you have the ESLint rule, no-floating-promises enabled, consider disabling it either globally, or for the affected line.
If your application needs this rule, you should either void
the promise – or use an async
function, await
the Promise, then void the function call. This is not applicable when the method is called from inside an onClick
handler.
The affected methods are:
router.push
router.replace
router.prefetch
Potential solutions
withRouter
If useRouter
is not the best fit for you, withRouter
can also add the same router
object to any component.
Usage
TypeScript
To use class components with withRouter
, the component needs to accept a router prop: