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.

Upvotes: 15

Views: 10296

Answers (3)

JJY9
JJY9

Reputation: 623

From the question above, I have deduced that there are some other query params as well except the pathname(which comes in slug). And you wish to add pets=cats,dogs to it.

If someone want's to get the pathname, we can use window.location.pathname and the rest of the old query params can be accessed using window.location.search.

And to sum it all up, one can easily use

const subpathAndQuery = window.location.pathname + window.location.search;
router.push(`${subpathAndQuery}&pets=cats,dogs`);

NOTE: if pets=cats,dogs is the first key-value pair of the query param. You will have to use ? instead of &.

Upvotes: 0

Ivan V.
Ivan V.

Reputation: 8091

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"

Upvotes: 1

juliomalves
juliomalves

Reputation: 50338

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`)

Upvotes: 3

Related Questions