Reading list Switch to dark mode

    Shallow routing in next js

    Updated 4 May 2023

    In this blog, we are going to discuss the Shallow routing in NextJs.

    In Next.js, shallow routing is a technique that allows you to update the URL of a page without reloading the page itself or fetching new data from the server. This can improve the user experience by making page transitions faster and smoother.

    To use shallow routing, you can use the useRouter hook from the next/router module, which provides access to the router instance. Then, you can call the push method on the router with the shallow option set to true.

    The router object will also have access to the updated pathname. Changing the URL could mean adding a new query, so we could have the following code:

    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('/?counter=10', undefined, { shallow: true })
      }, [])
      useEffect(() => {
        // The counter changed!
      }, [router.query.counter])
    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.

    Start your headless eCommerce
    Find out More

    Note that the undefined the argument is passed as the second argument to router.push, which represents the as parameter and is used to specify a different URL for the browser to display (in case you’re using dynamic routes).

    Keep in mind that this routing is only available for same-level URLs, meaning that you cannot use it to navigate to a completely different page hierarchy.

    Also, some data-fetching methods such as getServerSideProps and getInitialProps will still be executed even with shallow routing.

    Meanwhile, the Link component uses the shallow props to specify if the routing is shallow or not. In both cases router.push and Link default to false.

    That’s all about the Shallow routing.

    You can check out our other next js blogs: Click here

    Happy coding ­čÖé

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*

    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home