Next.js - Shallow routing with dynamic routes

15,521

Solution 1

I think this is the expected behavior because you are routing to a new page. If you are just changing the query parameters shallow routing should work for example:

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

but you are using route parameters

router.push(
  '/post/[...slug]',
  '/post/2020/01/01/hello-world',
  { shallow: true }
);

That indicates you are routing to 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 and this is mentioned in the docs here Shallow routing caveats.

By the way, you say "the page is refreshed" but router.push doesn't refresh the page even when used without shallow: true. It's a single page app after all. It just renders the new page and runs getStaticProps, getServerSideProps, or getInitialProps.

Solution 2

Shallow Routing Caveats

Shallow Routing gives you the ability to update pathname or query params without losing state i.e., only the state of route is changed.. But the condition is, you have to be on the same page(as shown in docs Caveats image).

For that you have to pass the second arg to router.push or Router.push as undefined. Otherwise, new page will be loaded after unloading the first page and you won't get the expected behavior.

I mean shallow routing will no longer be working in terms of pathname changing and that's because we chose to load a new page not only the url. Hope this helps 😉

Example

import { useEffect } from 'react'
import { useRouter } from 'next/router'

// Current URL is '/'
function Page() {
  const router = useRouter()

  useEffect(() => {
    // Always do navigations after the first render
    router.push('/post/[...slug]', undefined, { shallow: true })
  }, [])

  useEffect(() => {
    // The pathname changed!
  }, [router.pathname ])
}

export default Page

Solution 3

Actually, based on the docs description, I believe you used this push function wrongly. See the following codes that come from docs:

import Router from 'next/router'

Router.push(url, as, options)

And the docs said:

  • url - The URL to navigate to. This is usually the name of a page
  • as - Optional decorator for the URL that will be shown in the browser. Defaults to url
  • options - Optional object with the following configuration options: shallow: Update the path of the current page without rerunning getStaticProps, getServerSideProps or getInitialProps. Defaults to false

It means you should pass the exact URL as the first parameter and if you wanna show it as decorating name pass the second parameter and for the third just pass the option, so you should write like below:

router.push(
  '/post/2020/01/01/hello-world',
  undefined,
  undefined
);

For the shallow routing you should use the exact example:

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

In fact, with your code, you create a new route and it is inevitable to refreshing.

Share:
15,521
AndrewMcLagan
Author by

AndrewMcLagan

I’m a full stack Web Developer with over fifteen years experience in the industry. I concentrate on open source languages and technologies such as PHP 5.6+, Python, Javascript EMCA6, AngularJS, React, Laravel and Symfony. My strengths would be a very strong interest in the open source community and approaching web­app development from a software design perspective rather than simply being a code­monkey. Strong understanding of basic SOLID principals and the patterns that make these principles a reality. Coming from many years experience as a contract developer, keeping up­-to-­date with the open source community, tools and best practices has been paramount to my career. Also, I LOVE to code!

Updated on June 06, 2022

Comments

  • AndrewMcLagan
    AndrewMcLagan almost 2 years

    When attempting shallow routing with a dynamic route in Next.js the page is refreshed and shallow ignored. Seems a lot of people are confused about this.

    Say we start on the following page

    router.push(
      '/post/[...slug]',
      '/post/2020/01/01/hello-world',
      { shallow: true }
    );
    

    Then we route to another blog post:

    router.push(
      '/post/[...slug]',
      '/post/2020/01/01/foo-bar',
      { shallow: true }
    );
    

    This does not trigger shallow routing, the browser refreshes, why?

    In the codebase its very clear that this is a feature:

    // If asked to change the current URL we should reload the current page
    // (not location.reload() but reload getInitialProps and other Next.js stuffs)
    // We also need to set the method = replaceState always
    // as this should not go into the history (That's how browsers work)
    // We should compare the new asPath to the current asPath, not the url
    if (!this.urlIsNew(as)) {
      method = 'replaceState'
    }
    

    I can achieve the same manually using window.history.pushState() although this would of course be a bad idea:

    window.history.pushState({
      as: '/post/2020/01/01/foo-bar',
      url: '/post/[...slug]',
      options: { shallow: true }
    }, '', '/post/2020/01/01/foo-bar');
    

    As the internal API of Next.JS could change at any time... I may be missing something... but why is shallow ignored in the case? Seems odd.