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.
The companion life-cycle method getStaticPaths of getStaticProps lets us use the data we have at build-time to specify which dynamic routes (like /pages/blog/[slug] ) we want to generate statically.
Next.js supports pages with dynamic routes.
The Next.js router allows you to do client-side route transitions between pages, similar to a single-page application. A React component called Link is provided to do this client-side route transition.
Next. js supports ES2020 dynamic `import()` for JavaScript. With it, you can import JavaScript modules dynamically and work with them. They also work with server-side rendering (SSR).
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
.
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
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 pageas
- Optional decorator for the URL that will be shown in the browser. Defaults tourl
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With