`next/router` to `next/navigation` migration cheatsheet

2 min read
Wrote down the sheet I wish I had.
Post cover imageImage by black-forest-labs/flux-dev

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 return ReadonlyURLSearchParams | null. The null value is for compatibility during migration since search params cannot be known during pre-rendering of a page that doesn't use getServerSideProps

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.

Discuss on Bluesky