14

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.

juliomalves
  • 42,130
  • 20
  • 150
  • 146

2 Answers2

3

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`)
juliomalves
  • 42,130
  • 20
  • 150
  • 146
0

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"
johannchopin
  • 13,720
  • 10
  • 55
  • 101
Ivan V.
  • 7,593
  • 2
  • 36
  • 53
  • 2
    This doesn't work. The following will still be encoded by Router.push: ```router.push({ pathname: router.pathname, query: { ...router.query, pets: 'cats,dogs'}, })``` – Menelaos Kotsollaris Jan 31 '22 at 18:04
  • 3
    I am having the same issue with next router. Were you able to resolve this? – Philipp Feb 14 '22 at 16:52
  • 1
    As you said router automatically encodes query params for you. If you do this, you're double encoding them. You'd want `cats,dogs` and now you get `cats%252Cdogs` instead. – FINDarkside Aug 15 '22 at 16:36