3

I export Next.js as static files and let backend code handle them. What I need is just to remove query params in the current URL. I used to use

window.history.replaceState(null, null, window.location.pathname)

When there are no query params, replaceState works, but when query params exist, soon the url is changed back. What is causing this? I am using a custom server, so 'next/router' doesn't help, it only reload the page.

Here is an example,

suppose my current path is /home, I can call window.history.replaceState(null, null, '/home1') to change path to /home1. But if path is like /home?a=123, after replaceState is called, the url revert to /home?a=123 right away.

azteker
  • 41
  • 5
  • Could you provide a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) please? Also, have you had a look at [NEXT JS - How to remove Query Params](https://stackoverflow.com/questions/65606974/next-js-how-to-remove-query-params)? – juliomalves Mar 12 '21 at 19:14
  • @juliomalves just open any nextjs page with query params, like `localhost:3000/home?a=1`. then call history.replaceState with any pathname. You can see the url is changed and revert to `localhost:3000/home?a=1` right away. The solution in the post doesn't work for me. – azteker Mar 12 '21 at 19:26
  • @juliomalves if run history.replaceState in console, there will be no problem, but I called in useEffect – azteker Mar 12 '21 at 19:39
  • 1
    I do what you are doing and it works flawlessly inside useEffect on exported next pages. However, you might want to use [router.replace](https://nextjs.org/docs/api-reference/next/router#routerreplace) to do things properly – Mr. Hedgehog Mar 12 '21 at 20:10
  • @Mr.Hedgehog I created a new nextjs app and run in dev mode, still got this error, do you have query params in your url? router.replace doesn't help me since it reloads the page. – azteker Mar 12 '21 at 23:50

0 Answers0