Open smhutch opened 1 year ago
After doing some more investigation, I managed to work around this issue by using this approach instead of router.replace()
:
const params = new URLSearchParams({ example: 'value' });
const path = window.location.pathname;
const pathWithQueryParams = `${path}?${params.toString()}`;
// This variable contains Next.js internals, and must be passed to `replaceState` for it to work properly.
const currentState = window.history.state;
history.replaceState(currentState, "", pathWithQueryParams)
Prototype showing this working.
After some additional investigation, I landed on this solution:
const params = new URLSearchParams({ example: 'value' });
const path = window.location.pathname;
const pathWithQueryParams = `${path}?${params.toString()}`;
// It's vital to preserve the current history state, because it contains values that
// Next.js uses to support client-side navigation via the back/forward buttons.
const currentHistoryState = window.history.state;
// Here we're manually overriding the current history state, which Next.js uses internally.
// This is a bit of a high risk change, and should be revisited when upgrading Next.js.
const newHistoryState = {
...currentHistoryState,
as: path,
url: path,
};
// Update query params, without triggering a reload
history.replaceState(newHistoryState, '', path);
Verify canary release
Provide environment information
What browser are you using? (if relevant)
Firefox 106.0.5 (64-bit)
How are you deploying your application? (if relevant)
Vercel
Describe the Bug
router.replace
withshallow: false
, or by usinghistory.replaceState
)Link
orrouter.push
)Expected Behavior
Back button works as normal
Link to reproduction - Issues with a link to complete (but minimal) reproduction code will be addressed faster
https://codesandbox.io/p/sandbox/inspiring-gagarin-40iqxd
To Reproduce
Navigate to this demo, then follow these steps: