'Next.js router.push encodes query parameters

I'm trying to make a redirect using router.push to pass a query string, but when I try to pass a value in my param with special characters as a comma is encoding my URL. Is it possible to pass ',' into an URL using router.push?

I have tried a lot of things but I don't know how to make it work.

router.push({
  pathname: router.pathname,
  query: { ...router.query, pets: 'cats,dogs'},
})

The resulting URL will be myurl?pets=cats%2Cdogs, I want it to be myurl?pets=cats,dogs.



Solution 1:[1]

You need to decode and encode URI params. Router automatically encodes query params for you:

encodeURIComponent('cats,dogs')
// "cats%2Cdogs"

You need to decode them when reading:

decodeURIComponent("cats%2Cdogs")
"cats,dogs"

Solution 2:[2]

Using the URL object format for the path and query string will internally encode the query parameters.

To avoid this, you can pass the path and query string as a string instead.

router.push(`${router.asPath}?pets=cats,dogs`)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ivan V.
Solution 2 juliomalves