Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fail to use history.replaceState in next.js

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.

like image 753
azteker Avatar asked Oct 31 '25 15:10

azteker


1 Answers

In Next.js it's best to use router.replace(window.location.pathname, undefined, { shallow: true }), where shallow: true updates the URL without the page refreshing.

like image 179
martinedwards Avatar answered Nov 03 '25 21:11

martinedwards