'How to remove one specific query parameter from URL in Next.js?

http://localhost:3000/?search=test&type=abc&category=xyz

After I search for test (among with type and category), the URL changes to the URL above.

return router.push(
      {
         pathname: `/`,
         query: {
             // something to do here...
         },
      },
      "",
      { scroll: false }
);

Next, I have an onClick with this router.push.

I would like to remove ONLY the search query and keep the type and category queries. How is it possible? The documentation doesn't mention anything about this.



Solution 1:[1]

You can call router.push with the current query string, but omitting the search parameter.

const params = new URLSearchParams(router.query);
params.delete('search');
const queryString = params.toString();
const path = `/${queryString ? `?${queryString}` : ''}`;

router.push(path, '', { scroll: false });

Given that you're currently at /?search=test&type=abc&category=xyz, the above will route you to /?type=abc&category=xyz. This will also handle scenarios where the type and category query parameters aren't present.

Solution 2:[2]

let queries = Object.assign({}, router.query);

delete queries.search;
return router.push(
      {
         pathname: `/`,
         query: queries
      },
      "",
      { scroll: false }
);

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
Solution 2 David