Shallow Routing

Examples

Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.

You’ll receive the updated pathname and the query via the router object (added by useRouter or withRouter), without losing state.

To enable shallow routing, set the shallow option to true. Consider the following example:

  1. import { useEffect } from 'react'
  2. import { useRouter } from 'next/router'
  3. // Current URL is '/'
  4. function Page() {
  5. const router = useRouter()
  6. useEffect(() => {
  7. // Always do navigations after the first render
  8. router.push('/?counter=10', undefined, { shallow: true })
  9. }, [])
  10. useEffect(() => {
  11. // The counter changed!
  12. }, [router.query.counter])
  13. }
  14. export default Page

The URL will get updated to /?counter=10. and the page won’t get replaced, only the state of the route is changed.

You can also watch for URL changes via componentDidUpdate as shown below:

  1. componentDidUpdate(prevProps) {
  2. const { pathname, query } = this.props.router
  3. // verify props have changed to avoid an infinite loop
  4. if (query.counter !== prevProps.router.query.counter) {
  5. // fetch data based on the new query
  6. }
  7. }

Caveats

Shallow routing only works for URL changes in the current page. For example, let’s assume we have another page called pages/about.js, and you run this:

  1. router.push('/?counter=10', '/about?counter=10', { shallow: true })

Since that’s a new page, it’ll unload the current page, load the new one and wait for data fetching even though we asked to do shallow routing.

When shallow routing is used with middleware it will not ensure the new page matches the current page like previously done without middleware. This is due to middleware being able to rewrite dynamically and can’t be verified client-side without a data fetch which is skipped with shallow, so a shallow route change must always be treated as shallow.