`next/router`
to `next/navigation`
migration cheatsheet
You might find this useful when migrating a Next.js app from the Pages Router to the App Router.
`router`
object
Properties of the next/router
object and their equivalent using next/navigation
exports.
pathname
const pathname = usePathname()
query
If an application includes the
/pages
directory,useSearchParams
will returnReadonlyURLSearchParams | null
. Thenull
value is for compatibility during migration since search params cannot be known during pre-rendering of a page that doesn't usegetServerSideProps
const searchParams = useSearchParams()
const query = Object.fromEntries(searchParams ?? new URLSearchParams())
asPath
const pathname = usePathname()
const searchParams = useSearchParams()
const asPath = `${pathname}?${searchParams?.toString()}`
Methods
push
, replace
// next/router example
const { pathname, query, replace } = useRouter()
replace({ pathname, query: { ...query, foo: "bar" } })
// next/navigation equivalent
const { replace } = useRouter()
const readOnlyParams = useSearchParams()
const pathname = usePathname()
const params = new URLSearchParams(readOnlyParams ?? {})
params.set("foo", "bar")
replace(pathname + "?" + params.toString())
router.events
This is documented by Next.js.