NEXT JS - How to remove Query Params

Viewed 32174

How can I remove or update query params without refreshing the page in Next JS (React)?

  1. The user is on the URL /about?login=success&something=yes
  2. Click a button and removes ?login=success&something=yes from the URL without refreshing the page. The URL after clicking the button will be /about

How can I achieve it?

As mentioned in this thread, I know that is possible to remove query params or query strings with Router. But, useLocation and useHistory are not avaliable on next/router.

9 Answers

You can use next/router to remove the query params in the URL.

const router = useRouter();

router.replace('/about', undefined, { shallow: true });

Use replace to prevent adding a new URL entry into the history (otherwise just use push), and shallow: true allows you to change the URL without running data fetching methods. This will cause a re-render but will not refresh the page per se.


The above solution will remove all query parameters from the URL. If you want to only remove a specific parameter you can use the code below instead.

const removeQueryParam = (param) => {
    const { pathname, query } = router;
    const params = new URLSearchParams(query);
    params.delete(param);
    router.replace(
        { pathname, query: params.toString() },
        undefined, 
        { shallow: true }
    );
};

removeQueryParam('something');

my solution to similiar problem of mine is this:

push(`${asPath.split('?')[0]}?comp=${id}`);

or if you want to have reusable function:


function delQuery(asPath) {
  return asPath.split('?')[0]
}

...
const {push, asPath} = useRouter()

push(`${delQuery(asPath)}?comp=${id}`);

According to the History, you can using history.replaceState to implement this.

window.history.replaceState(null, '', '/about')

If you want remove single or multiple params from query,

const router = useRouter();

/**
 * If removeList is empty, the function removes all params from url.
 * @param {*} router 
 * @param {*} removeList 
 */
const removeQueryParamsFromRouter = (router, removeList = []) => {
    if (removeList.length > 0) {
        removeList.forEach((param) => delete router.query[param]);
    } else {
        // Remove all
        Object.keys(router.query).forEach((param) => delete router.query[param]);
    }
    router.replace(
        {
            pathname: router.pathname,
            query: router.query
        },
        undefined,
        /**
         * Do not refresh the page
         */
        { shallow: true }
    );
};

const anyFunction = () => {
    // "/about?firstParam=5&secondParam=10"
    removeQueryParamsFromRouter(router, ['myParam']);
    // "/about?secondParam=10"
};

You usually want to keep pathname and all other query params the same while deleting one specific query param (in example shouldRefetchUser) you can do so like this:

const router = useRouter()
const { pathname, query } = router
delete router.query.shouldRefetchUser
router.replace({ pathname, query }, undefined, { shallow: true })

(Upgraded answer of @juliomalves)

You can remove query param from router object by []:

const router = useRouter();
router.query.something = [];
import {NextRouter} from 'next/router'

export const removeQueryParams = (
  router: NextRouter,
  paramsToRemove: Array<string> = []
) => {
  if (paramsToRemove.length > 0) {
    paramsToRemove.forEach((param) => delete router.query[param])
  } else {
    // Remove all query parameters
    Object.keys(router.query).forEach((param) => delete router.query[param])
  }
  router.replace(
    {
      pathname: router.pathname,
      query: router.query,
    },
    undefined,
    /**
     * Do not refresh the page when the query params are removed
     */
    {shallow: true}
  )
}
const anyFunction = () => {
    // "/about?firstParam=5&secondParam=10"
    removeQueryParamsFromRouter(router, ['myParam']);
    // "/about?secondParam=10"
};

Original Answer

The original answer mentioned here throws an error as the object is undefined, also it is the typescript version of it.

You can simply use "router.push" or "router.replace" with "shallow: true", this will remove the query param without reloading the page.

const router = useRouter();
router.replace('/about', undefined, { shallow: true });

Or if you want to delete single query then this quick and easy method will help you

eg. /about?login=success&something=yes

const router = useRouter();
// perform this inside function call or button click etc
delete router.query.something;
router.push(router)

now the updated route will be

/about?login=success

Nextjs has useRouter hook which can be used to changed url programmatically. Link to the docs.

Related