next/router

Before moving forward, we recommend you to read Routing Introduction first.

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:

  1. import { useRouter } from 'next/router'
  2. function ActiveLink({ children, href }) {
  3. const router = useRouter()
  4. const style = {
  5. marginRight: 10,
  6. color: router.asPath === href ? 'red' : 'black',
  7. }
  8. const handleClick = (e) => {
  9. e.preventDefault()
  10. router.push(href)
  11. }
  12. return (
  13. <a href={href} onClick={handleClick} style={style}>
  14. {children}
  15. </a>
  16. )
  17. }
  18. export default ActiveLink

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 the trailingSlash configuration. basePath and locale 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 of useEffect methods and not for conditionally rendering on the server. See related docs for use case with automatically statically optimized pages
  • isPreview: 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 using asPath until the isReady field is true.

The following methods are included inside router:

router.push

Examples

Handles client-side transitions, this method is useful for cases where next/link is not enough.

  1. router.push(url, as, options)
  • url: UrlObject | String - The URL to navigate to (see Node.JS URL module documentation for UrlObject 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, check our previous docs to see how it worked. Note: when this path differs from the one provided in href the previous href/as behavior is used as shown in the previous docs
  • options - Optional object with the following configuration options:
    • scroll - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to true
    • shallow: Update the path of the current page without rerunning getStaticProps, getServerSideProps or getInitialProps. Defaults to false
    • 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.

Usage

Navigating to pages/about.js, which is a predefined route:

  1. import { useRouter } from 'next/router'
  2. export default function Page() {
  3. const router = useRouter()
  4. return (
  5. <button type="button" onClick={() => router.push('/about')}>
  6. Click me
  7. </button>
  8. )
  9. }

Navigating pages/post/[pid].js, which is a dynamic route:

  1. import { useRouter } from 'next/router'
  2. export default function Page() {
  3. const router = useRouter()
  4. return (
  5. <button type="button" onClick={() => router.push('/post/abc')}>
  6. Click me
  7. </button>
  8. )
  9. }

Redirecting the user to pages/login.js, useful for pages behind authentication:

  1. import { useEffect } from 'react'
  2. import { useRouter } from 'next/router'
  3. // Here you would fetch and return the user
  4. const useUser = () => ({ user: null, loading: false })
  5. export default function Page() {
  6. const { user, loading } = useUser()
  7. const router = useRouter()
  8. useEffect(() => {
  9. if (!(user || loading)) {
  10. router.push('/login')
  11. }
  12. }, [user, loading])
  13. return <p>Redirecting...</p>
  14. }

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.

  1. // pages/[slug].js
  2. import Link from 'next/link'
  3. import { useState } from 'react'
  4. import { useRouter } from 'next/router'
  5. export default function Page(props) {
  6. const router = useRouter()
  7. const [count, setCount] = useState(0)
  8. return (
  9. <div>
  10. <h1>Page: {router.query.slug}</h1>
  11. <p>Count: {count}</p>
  12. <button onClick={() => setCount(count + 1)}>Increase count</button>
  13. <Link href="/one">
  14. <a>one</a>
  15. </Link> <Link href="/two">
  16. <a>two</a>
  17. </Link>
  18. </div>
  19. )
  20. }

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:

  1. Manually ensure each state is updated using useEffect. In the above example, that could look like:
  1. useEffect(() => {
  2. setCount(0)
  3. }, [router.query.slug])
  1. Use a React key to tell React to remount the component. To do this for all pages, you can use a custom app:
  1. // pages/_app.js
  2. import { useRouter } from 'next/router'
  3. export default function MyApp({ Component, pageProps }) {
  4. const router = useRouter()
  5. return <Component key={router.asPath} {...pageProps} />
  6. }

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:

  1. import { useRouter } from 'next/router'
  2. export default function ReadMore({ post }) {
  3. const router = useRouter()
  4. return (
  5. <button
  6. type="button"
  7. onClick={() => {
  8. router.push({
  9. pathname: '/post/[pid]',
  10. query: { pid: post.id },
  11. })
  12. }}
  13. >
  14. Click here to read more
  15. </button>
  16. )
  17. }

router.replace

Similar to the replace prop in next/link, router.replace will prevent adding a new URL entry into the history stack.

  1. router.replace(url, as, options)
  • The API for router.replace is exactly the same as the API for router.push.

Usage

Take a look at the following example:

  1. import { useRouter } from 'next/router'
  2. export default function Page() {
  3. const router = useRouter()
  4. return (
  5. <button type="button" onClick={() => router.replace('/home')}>
  6. Click me
  7. </button>
  8. )
  9. }

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.

  1. router.prefetch(url, as, options)
  • url - The URL to prefetch, including explicit routes (e.g. /dashboard) and dynamic routes (e.g. /product/[id])
  • as - Optional decorator for url. Before Next.js 9.5.3 this was used to prefetch dynamic routes, check our previous docs to see how it worked
  • options - Optional object with the following allowed fields:
    • locale - allows providing a different locale from the active one. If false, url has to include the locale as the active locale won’t be used.

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:

  1. import { useCallback, useEffect } from 'react'
  2. import { useRouter } from 'next/router'
  3. export default function Login() {
  4. const router = useRouter()
  5. const handleSubmit = useCallback((e) => {
  6. e.preventDefault()
  7. fetch('/api/login', {
  8. method: 'POST',
  9. headers: { 'Content-Type': 'application/json' },
  10. body: JSON.stringify({
  11. /* Form data */
  12. }),
  13. }).then((res) => {
  14. // Do a fast client-side transition to the already prefetched dashboard page
  15. if (res.ok) router.push('/dashboard')
  16. })
  17. }, [])
  18. useEffect(() => {
  19. // Prefetch the dashboard page
  20. router.prefetch('/dashboard')
  21. }, [])
  22. return (
  23. <form onSubmit={handleSubmit}>
  24. {/* Form fields */}
  25. <button type="submit">Login</button>
  26. </form>
  27. )
  28. }

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.

  1. 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

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.

Usage

You could use beforePopState to manipulate the request, or force a SSR refresh, as in the following example:

  1. import { useEffect } from 'react'
  2. import { useRouter } from 'next/router'
  3. export default function Page() {
  4. const router = useRouter()
  5. useEffect(() => {
  6. router.beforePopState(({ url, as, options }) => {
  7. // I only want to allow these two routes!
  8. if (as !== '/' && as !== '/other') {
  9. // Have SSR render bad routes as a 404.
  10. window.location.href = as
  11. return false
  12. }
  13. return true
  14. })
  15. }, [])
  16. return <p>Welcome to the page</p>
  17. }

router.back

Navigate back in history. Equivalent to clicking the browser’s back button. It executes window.history.back().

Usage

  1. import { useRouter } from 'next/router'
  2. export default function Page() {
  3. const router = useRouter()
  4. return (
  5. <button type="button" onClick={() => router.back()}>
  6. Click here to go back
  7. </button>
  8. )
  9. }

router.reload

Reload the current URL. Equivalent to clicking the browser’s refresh button. It executes window.location.reload().

Usage

  1. import { useRouter } from 'next/router'
  2. export default function Page() {
  3. const router = useRouter()
  4. return (
  5. <button type="button" onClick={() => router.reload()}>
  6. Click here to reload
  7. </button>
  8. )
  9. }

router.events

Examples

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 change
  • routeChangeComplete(url, { shallow }) - Fires when a route changed completely
  • routeChangeError(err, url, { shallow }) - Fires when there’s an error when changing routes, or a route load is cancelled
    • err.cancelled - Indicates if the navigation was cancelled
  • beforeHistoryChange(url, { shallow }) - Fires before changing the browser’s history
  • hashChangeStart(url, { shallow }) - Fires when the hash will change but not the page
  • hashChangeComplete(url, { shallow }) - Fires when the hash has changed but not the page

Note: Here url is the URL shown in the browser, including the basePath.

Usage

For example, to listen to the router event routeChangeStart, open or create pages/_app.js and subscribe to the event, like so:

  1. import { useEffect } from 'react'
  2. import { useRouter } from 'next/router'
  3. export default function MyApp({ Component, pageProps }) {
  4. const router = useRouter()
  5. useEffect(() => {
  6. const handleRouteChange = (url, { shallow }) => {
  7. console.log(
  8. `App is changing to ${url} ${
  9. shallow ? 'with' : 'without'
  10. } shallow routing`
  11. )
  12. }
  13. router.events.on('routeChangeStart', handleRouteChange)
  14. // If the component is unmounted, unsubscribe
  15. // from the event with the `off` method:
  16. return () => {
  17. router.events.off('routeChangeStart', handleRouteChange)
  18. }
  19. }, [])
  20. return <Component {...pageProps} />
  21. }

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:

  1. import { useEffect } from 'react'
  2. import { useRouter } from 'next/router'
  3. export default function MyApp({ Component, pageProps }) {
  4. const router = useRouter()
  5. useEffect(() => {
  6. const handleRouteChangeError = (err, url) => {
  7. if (err.cancelled) {
  8. console.log(`Route to ${url} was cancelled!`)
  9. }
  10. }
  11. router.events.on('routeChangeError', handleRouteChangeError)
  12. // If the component is unmounted, unsubscribe
  13. // from the event with the `off` method:
  14. return () => {
  15. router.events.off('routeChangeError', handleRouteChangeError)
  16. }
  17. }, [])
  18. return <Component {...pageProps} />
  19. }

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

  1. import { useEffect } from 'react'
  2. import { useRouter } from 'next/router'
  3. // Here you would fetch and return the user
  4. const useUser = () => ({ user: null, loading: false })
  5. export default function Page() {
  6. const { user, loading } = useUser()
  7. const router = useRouter()
  8. useEffect(() => {
  9. // disable the linting on the next line - This is the cleanest solution
  10. // eslint-disable-next-line no-floating-promises
  11. router.push('/login')
  12. // void the Promise returned by router.push
  13. if (!(user || loading)) {
  14. void router.push('/login')
  15. }
  16. // or use an async function, await the Promise, then void the function call
  17. async function handleRouteChange() {
  18. if (!(user || loading)) {
  19. await router.push('/login')
  20. }
  21. }
  22. void handleRouteChange()
  23. }, [user, loading])
  24. return <p>Redirecting...</p>
  25. }

withRouter

If useRouter is not the best fit for you, withRouter can also add the same router object to any component.

Usage

  1. import { withRouter } from 'next/router'
  2. function Page({ router }) {
  3. return <p>{router.pathname}</p>
  4. }
  5. export default withRouter(Page)

TypeScript

To use class components with withRouter, the component needs to accept a router prop:

  1. import React from 'react'
  2. import { withRouter, NextRouter } from 'next/router'
  3. interface WithRouterProps {
  4. router: NextRouter
  5. }
  6. interface MyComponentProps extends WithRouterProps {}
  7. class MyComponent extends React.Component<MyComponentProps> {
  8. render() {
  9. return <p>{this.props.router.pathname}</p>
  10. }
  11. }
  12. export default withRouter(MyComponent)