#Set URL without triggering navigation.

1 messages · Page 1 of 1 (latest)

lusty frigate
#

How do I set query parameters in the url without triggering navigation in next js?

verbal oakBOT
#

Hi @lusty frigate. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, you can change the URL without triggering navigation by using the concept of shallow routing. 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, without losing state.

To enable shallow routing, set the shallow option to true. Here's an 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('/?counter=10', undefined, { shallow: true })
 }, [])
 
 useEffect(() => {
 // The counter changed!
 }, [router.query.counter])
}
 
export default Page

In this example, 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 find more details in the Next.js documentation (https://nextjs.org/docs/pages/building-your-application/routing/linking-and-navigating#shallow-routing).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: