{"pageProps":{"routes":[{"title":"Documentation","heading":true,"routes":[{"title":"Getting Started","path":"/docs/getting-started.md"},{"title":"Basic Features","open":true,"routes":[{"title":"Pages","path":"/docs/basic-features/pages.md"},{"title":"Data fetching","path":"/docs/basic-features/data-fetching.md"},{"title":"Built-in CSS Support","path":"/docs/basic-features/built-in-css-support.md"},{"title":"Static File Serving","path":"/docs/basic-features/static-file-serving.md"},{"title":"TypeScript","path":"/docs/basic-features/typescript.md"},{"title":"Environment Variables","path":"/docs/basic-features/environment-variables.md"}]},{"title":"Routing","routes":[{"title":"Introduction","path":"/docs/routing/introduction.md"},{"title":"Dynamic Routes","path":"/docs/routing/dynamic-routes.md"},{"title":"Imperatively","path":"/docs/routing/imperatively.md"},{"title":"Shallow Routing","path":"/docs/routing/shallow-routing.md"}]},{"title":"API Routes","routes":[{"title":"Introduction","path":"/docs/api-routes/introduction.md"},{"title":"Dynamic API Routes","path":"/docs/api-routes/dynamic-api-routes.md"},{"title":"API Middlewares","path":"/docs/api-routes/api-middlewares.md"},{"title":"Response Helpers","path":"/docs/api-routes/response-helpers.md"}]},{"title":"Deployment","path":"/docs/deployment.md"},{"title":"Advanced Features","routes":[{"title":"Preview Mode","path":"/docs/advanced-features/preview-mode.md"},{"title":"Dynamic Import","path":"/docs/advanced-features/dynamic-import.md"},{"title":"Automatic Static Optimization","path":"/docs/advanced-features/automatic-static-optimization.md"},{"title":"Static HTML Export","path":"/docs/advanced-features/static-html-export.md"},{"title":"Absolute Imports and Module Path Aliases","path":"/docs/advanced-features/module-path-aliases.md"},{"title":"AMP Support","routes":[{"title":"Introduction","path":"/docs/advanced-features/amp-support/introduction.md"},{"title":"Adding AMP Components","path":"/docs/advanced-features/amp-support/adding-amp-components.md"},{"title":"AMP Validation","path":"/docs/advanced-features/amp-support/amp-validation.md"},{"title":"AMP in Static HTML export","path":"/docs/advanced-features/amp-support/amp-in-static-html-export.md"},{"title":"TypeScript","path":"/docs/advanced-features/amp-support/typescript.md"}]},{"title":"Customizing Babel Config","path":"/docs/advanced-features/customizing-babel-config.md"},{"title":"Customizing PostCSS Config","path":"/docs/advanced-features/customizing-postcss-config.md"},{"title":"Custom Server","path":"/docs/advanced-features/custom-server.md"},{"title":"Custom `App`","path":"/docs/advanced-features/custom-app.md"},{"title":"Custom `Document`","path":"/docs/advanced-features/custom-document.md"},{"title":"Custom Error Page","path":"/docs/advanced-features/custom-error-page.md"},{"title":"`src` Directory","path":"/docs/advanced-features/src-directory.md"},{"title":"Multi Zones","path":"/docs/advanced-features/multi-zones.md"},{"title":"Measuring performance","path":"/docs/advanced-features/measuring-performance.md"}]},{"title":"Upgrade Guide","path":"/docs/upgrading.md"},{"title":"FAQ","path":"/docs/faq.md"}]},{"title":"API Reference","heading":true,"routes":[{"title":"CLI","path":"/docs/api-reference/cli.md"},{"title":"next/router","path":"/docs/api-reference/next/router.md"},{"title":"next/link","path":"/docs/api-reference/next/link.md"},{"title":"next/head","path":"/docs/api-reference/next/head.md"},{"title":"next/amp","path":"/docs/api-reference/next/amp.md"},{"title":"Data Fetching","routes":[{"title":"getInitialProps","path":"/docs/api-reference/data-fetching/getInitialProps.md"}]},{"title":"next.config.js","routes":[{"title":"Introduction","path":"/docs/api-reference/next.config.js/introduction.md"},{"title":"Environment Variables","path":"/docs/api-reference/next.config.js/environment-variables.md"},{"title":"Custom Page Extensions","path":"/docs/api-reference/next.config.js/custom-page-extensions.md"},{"title":"CDN Support with Asset Prefix","path":"/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md"},{"title":"Build Target","path":"/docs/api-reference/next.config.js/build-target.md"},{"title":"Custom Webpack Config","path":"/docs/api-reference/next.config.js/custom-webpack-config.md"},{"title":"Compression","path":"/docs/api-reference/next.config.js/compression.md"},{"title":"Static Optimization Indicator","path":"/docs/api-reference/next.config.js/static-optimization-indicator.md"},{"title":"Runtime Configuration","path":"/docs/api-reference/next.config.js/runtime-configuration.md"},{"title":"Disabling x-powered-by","path":"/docs/api-reference/next.config.js/disabling-x-powered-by.md"},{"title":"Disabling ETag Generation","path":"/docs/api-reference/next.config.js/disabling-etag-generation.md"},{"title":"Setting a custom build directory","path":"/docs/api-reference/next.config.js/setting-a-custom-build-directory.md"},{"title":"Configuring the Build ID","path":"/docs/api-reference/next.config.js/configuring-the-build-id.md"},{"title":"Configuring onDemandEntries","path":"/docs/api-reference/next.config.js/configuring-onDemandEntries.md"},{"title":"Ignoring TypeScript Errors","path":"/docs/api-reference/next.config.js/ignoring-typescript-errors.md"},{"title":"exportPathMap","path":"/docs/api-reference/next.config.js/exportPathMap.md"}]}]}],"data":{"description":"Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook."},"route":{"title":"next/router","path":"/docs/api-reference/next/router.md"},"html":"

next/router

\n
\n

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

\n
\n

useRouter\n \n \n \n \n

\n

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:

\n
import { useRouter } from 'next/router'\n\nfunction ActiveLink({ children, href }) {\n  const router = useRouter()\n  const style = {\n    marginRight: 10,\n    color: router.pathname === href ? 'red' : 'black',\n  }\n\n  const handleClick = e => {\n    e.preventDefault()\n    router.push(href)\n  }\n\n  return (\n    <a href={href} onClick={handleClick} style={style}>\n      {children}\n    </a>\n  )\n}\n\nexport default ActiveLink\n
\n
\n

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.

\n
\n

router object\n \n \n \n \n

\n

The following is the definition of the router object returned by both useRouter and withRouter:

\n\n

Additionally, the Router API is also included inside the object.

\n
\n

The query object will be empty during prerendering if the page is statically optimized.

\n
\n

withRouter\n \n \n \n \n

\n

If useRouter is not the best fit for you, withRouter can also add the same router object to any component, here's how to use it:

\n
import { withRouter } from 'next/router'\n\nfunction Page({ router }) {\n  return <p>{router.pathname}</p>\n}\n\nexport default withRouter(Page)\n
\n

Router API\n \n \n \n \n

\n

The API of Router, exported by next/router, is defined below.

\n

Router.push\n \n \n \n \n

\n
\n Examples\n \n
\n

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

\n
import Router from 'next/router'\n\nRouter.push(url, as, options)\n
\n\n
\n

You don't need to use Router for external URLs, window.location is better suited for those cases.

\n
\n

Usage\n \n \n \n \n

\n

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

\n
import Router from 'next/router'\n\nfunction Page() {\n  return <span onClick={() => Router.push('/about')}>Click me</span>\n}\n
\n

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

\n
import Router from 'next/router'\n\nfunction Page() {\n  return (\n    <span onClick={() => Router.push('/post/[pid]', '/post/abc')}>\n      Click me\n    </span>\n  )\n}\n
\n

With URL object\n \n \n \n \n

\n

You can use an URL object in the same way you can use it for next/link. Works for both the url and as parameters:

\n
import Router from 'next/router'\n\nconst handler = () => {\n  Router.push({\n    pathname: '/about',\n    query: { name: 'Vercel' },\n  })\n}\n\nfunction ReadMore() {\n  return (\n    <div>\n      Click <span onClick={handler}>here</span> to read more\n    </div>\n  )\n}\n\nexport default ReadMore\n
\n

Router.replace\n \n \n \n \n

\n

Similar to the replace prop in next/link, Router.replace will prevent adding a new URL entry into the history stack, take a look at the following example:

\n
import Router from 'next/router'\n\nRouter.replace('/home')\n
\n

The API for Router.replace is exactly the same as that used for Router.push.

\n

Router.prefetch\n \n \n \n \n

\n

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.

\n
\n

This is a production only feature. Next.js doesn't prefetch pages on development.

\n
\n
import Router from 'next/router'\n\nRouter.prefetch(url, as)\n
\n\n

Usage\n \n \n \n \n

\n

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:

\n
import { useCallback, useEffect } from 'react'\nimport Router from 'next/router'\n\nexport default function Login() {\n  const handleSubmit = useCallback(e => {\n    e.preventDefault()\n\n    fetch('/api/login', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify({\n        /* Form data */\n      }),\n    }).then(res => {\n      // Do a fast client-side transition to the already prefetched dashboard page\n      if (res.ok) Router.push('/dashboard')\n    })\n  }, [])\n\n  useEffect(() => {\n    // Prefetch the dashboard page as the user will go there after the login\n    Router.prefetch('/dashboard')\n  }, [])\n\n  return (\n    <form onSubmit={handleSubmit}>\n      {/* Form fields */}\n      <button type=\"submit\">Login</button>\n    </form>\n  )\n}\n
\n

Router.beforePopState\n \n \n \n \n

\n

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.

\n

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

\n
import Router from 'next/router'\n\nRouter.beforePopState(({ url, as, options }) => {\n  // I only want to allow these two routes!\n  if (as !== '/' && as !== '/other') {\n    // Have SSR render bad routes as a 404.\n    window.location.href = as\n    return false\n  }\n\n  return true\n})\n
\n

Router.beforePopState(cb: () => boolean)

\n\n

If the function you pass into beforePopState returns false, Router will not handle popstate and you'll be responsible for handling it, in that case. See Disabling file-system routing.

\n

Router.back\n \n \n \n \n

\n

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

\n
import Router from 'next/router'\n\nRouter.back()\n
\n

Router.reload\n \n \n \n \n

\n

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

\n
import Router from 'next/router'\n\nRouter.reload()\n
\n

Router.events\n \n \n \n \n

\n
\n Examples\n \n
\n

You can listen to different events happening inside the Router. Here's a list of supported events:

\n\n
\n

Here url is the URL shown in the browser. If you call Router.push(url, as) (or similar), then the value of url will be as.

\n
\n

For example, to listen to the router event routeChangeStart, do the following:

\n
import Router from 'next/router'\n\nconst handleRouteChange = url => {\n  console.log('App is changing to: ', url)\n}\n\nRouter.events.on('routeChangeStart', handleRouteChange)\n
\n

If you no longer want to listen to the event, unsubscribe with the off method:

\n
import Router from 'next/router'\n\nRouter.events.off('routeChangeStart', handleRouteChange)\n
\n

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:

\n
import Router from 'next/router'\n\nRouter.events.on('routeChangeError', (err, url) => {\n  if (err.cancelled) {\n    console.log(`Route to ${url} was cancelled!`)\n  }\n})\n
\n

Router events should be registered when a component mounts (useEffect or componentDidMount / componentWillUnmount) or imperatively when an event happens, as in the following example:

\n
import Router from 'next/router'\n\nuseEffect(() => {\n  const handleRouteChange = url => {\n    console.log('App is changing to: ', url)\n  }\n\n  Router.events.on('routeChangeStart', handleRouteChange)\n  return () => {\n    Router.events.off('routeChangeStart', handleRouteChange)\n  }\n}, [])\n
"},"__N_SSG":true}