The Next.js router translates query parameters into encoded format when using the router.push

I'm attempting to create a redirect using router.push in order to include a query string. However, when I try to pass a special character like a comma as part of the parameter value, it encodes my URL. Can you actually include ',' in a URL using router.push?

I've experimented with various approaches but haven't been successful in making it function.

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

The resulting URL ends up being myurl?pets=cats%2Cdogs, but I would prefer it to be myurl?pets=cats,dogs.

Answer №1

When utilizing the URL object structure for both the path and query string, the query parameters will be encoded internally.

To circumvent this issue, you have the option to provide the path and query string as a simple string instead.

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

Answer №2

It is important to properly handle URI parameters by encoding and decoding them. The router will automatically encode query parameters for you:

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

Remember to also decode the parameters when reading them:

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

Answer №3

After analyzing the question above, I have concluded that aside from the pathname (which is in slug format), there are other query parameters present. You want to include pets=cats,dogs as well.

To retrieve the pathname, one can use window.location.pathname, while the existing query parameters can be fetched using window.location.search.

In summary, you can combine them like this:

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 in the query parameter, you need to use ? instead of &.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am struggling to locate the source of this mysterious middleware error

I seem to be encountering an issue with a middleware function, resulting in a "middleware is not a function" error message. I'm at a loss as to why this is happening... [Error] TypeError: middleware is not a function Routes JS import express from &ap ...

The error message "Royalslider - The property 'ev' is not defined on 'slider.ev.on'" appeared on the screen

Discussing the topic: Adding input to active slide I'm still struggling with this issue, but I believe I'm very close. I'm stuck at the moment. The code seems correct..but I keep encountering errors. Particularly with "slider.ev.on" - Uncau ...

Update the checkbox values for all checkboxes within the grid

Need help with setting the checkbox value of all checkboxes in a column based on a header checkbox. The function below is called when the column header checkbox is clicked and takes the column header name and the checkbox object as arguments. function han ...

Error: The property 'scrollIntoView' cannot be read because it is null

class MessageApp extends Component { constructor(props) { super(props) this.state = { text: "", messages: [] } } componentDidMount() { const config = { apiKey: "<api-key>", authDomain: "<projec ...

Error: The prop type validation failed because a `value` prop was provided to a form field in React-Bootstrap-Typehead component

I am currently using the bootstrap-typehead package from https://github.com/ericgio/react-bootstrap-typeahead and struggling to understand why it's causing issues. Could someone help me identify what's wrong with this code that's triggering ...

JavaScript is failing to display precise values during calculations

Could someone please explain to me why there is consistently a discrepancy in the calculated value when I run the following computations? let amount = 1000; let credit = 3.02; let netValue = (credit/100)*amount; console.log(netValue); //displays 29.02 i ...

Order a nested array according to the inner value, using a different array as a reference

Having two arrays at hand, array1 requires sorting based on its inner key, role, as per array2. Despite attempting various solutions, I have hit a roadblock due to my lack of understanding on the necessary steps to proceed. The current output for Array1 i ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...

What is the best way to pass `response` data between routes in Express when setting up PayPal subscriptions?

I'm currently in the process of integrating PayPal subscriptions into my Node.js application using Express. I've come across a challenge when trying to pass the subscription ID obtained from PayPal's /create-subscription route to the /execut ...

Using gulp to compile a Vue component without the need for `require` statements

I'm currently exploring the process of constructing a component with Gulp. Right now, I am working on a Vue component that has the following structure: my-component.vue <template> <div class="foo"> </div> </template> < ...

Is there a way to detect the completion of the fadeout animation before calling a function?

I am trying to create a toast message using jQuery. When the "show" class is appended to the div, I want the toast message to fade in and then fade out after a few seconds. Once the fade-out animation is complete, I need to remove the "show" class. This ...

What could be the reason my Backbone view is failing to render?

Can anyone help me troubleshoot why this template isn't rendering properly in my backbone views? Any insights would be greatly appreciated! Below, I've included the code from my jade file for the views and the main.js file for the backbone js scr ...

Is it possible for a single field to validate and accept multiple types of data?

As a newcomer to Yup, I am attempting to validate a field that can be either a string following a specific regular expression or an array of such strings. Below is a functional example of validating a string that matches the regex: { field: yup.string(). ...

Avoid loading Google Maps JavaScript library multiple times to improve website performance

I'm facing an issue with loading Google Maps API script twice in a Bootstrap modal through AJAX. Initially, I have a button that, when clicked, triggers an AJAX call to load an HTML file into the modal. The HTML file contains the Google Maps API scrip ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...

Changing the color of options in a list when clicked: a step-by-step guide

Here is the HTML code I have: <li onclick="switchColors()"> <a class="x" href="Faculty.php">Faculty</a> </li> <li onclick="switchColors()"> <a class="x" href="Contact.php">Contact</a> </li> And here ...

How to manage rejections in async/await within the Array#map method

In my Node 8.1.2 project, I encountered a scenario where one file is calling another file's function within a map structure. While in a real example, I would normally use Promise.all on the map, that specific implementation is not the focus of this qu ...

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...

How to avoid line breaking in Select component with icon and text using React Material-UI

I am working on a Select element that includes both ListItemIcon and ListItemText. Whenever the select option is chosen, there seems to be an unwanted line break appearing. Despite finding various workarounds for this issue, I am keen on discovering the ...

Next Js (version 13.4.4-canary.2) is reporting that NEXT_PUBLIC_BASE_URL is currently undefined

I currently have two .env files set up: NEXT_PUBLIC_BASE_URL=http://localhost:3000 One is a simple .env file and the other is a .env.local file. NEXT_PUBLIC_BASE_URL=http://localhost:3000 Within my project, I am utilizing the new nextjs app folder struct ...