Ensure original history is read in effect (#58861)

## What?

Fixes
https://github.com/vercel/next.js/pull/58335#issuecomment-1825003091.
Waiting on a reply for the exact case but my assumption is that the
history is overwritten in the user module instead of before the other JS
loads.


<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
This commit is contained in:
Tim Neutkens 2023-12-03 09:18:34 +01:00 committed by GitHub
parent c530664c13
commit 8ff1368fdb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 50 deletions

View file

@ -138,14 +138,11 @@ function HistoryUpdater({
) {
// This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.
pushRef.pendingPush = false
if (originalPushState) {
originalPushState(historyState, '', canonicalUrl)
}
window.history.pushState(historyState, '', canonicalUrl)
} else {
if (originalReplaceState) {
originalReplaceState(historyState, '', canonicalUrl)
}
window.history.replaceState(historyState, '', canonicalUrl)
}
sync(appRouterState)
}, [appRouterState, sync])
return null
@ -219,15 +216,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
)
}
const originalPushState =
typeof window !== 'undefined'
? window.history.pushState.bind(window.history)
: null
const originalReplaceState =
typeof window !== 'undefined'
? window.history.replaceState.bind(window.history)
: null
function copyNextJsInternalHistoryState(data: any) {
if (data == null) data = {}
const currentState = window.history.state
@ -450,6 +438,10 @@ function Router({
}
useEffect(() => {
const originalPushState = window.history.pushState.bind(window.history)
const originalReplaceState = window.history.replaceState.bind(
window.history
)
if (process.env.__NEXT_WINDOW_HISTORY_SUPPORT) {
// Ensure the canonical URL in the Next.js Router is updated when the URL is changed so that `usePathname` and `useSearchParams` hold the pushed values.
const applyUrlFromHistoryPushReplace = (
@ -465,42 +457,49 @@ function Router({
})
}
if (originalPushState) {
/**
* Patch pushState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.pushState = function pushState(
data: any,
_unused: string,
url?: string | URL | null
): void {
data = copyNextJsInternalHistoryState(data)
applyUrlFromHistoryPushReplace(url)
/**
* Patch pushState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.pushState = function pushState(
data: any,
_unused: string,
url?: string | URL | null
): void {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if (data?.__NA || data?._N) {
return originalPushState(data, _unused, url)
}
}
if (originalReplaceState) {
/**
* Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.replaceState = function replaceState(
data: any,
_unused: string,
url?: string | URL | null
): void {
data = copyNextJsInternalHistoryState(data)
data = copyNextJsInternalHistoryState(data)
if (url) {
applyUrlFromHistoryPushReplace(url)
}
if (url) {
applyUrlFromHistoryPushReplace(url)
}
return originalPushState(data, _unused, url)
}
/**
* Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.replaceState = function replaceState(
data: any,
_unused: string,
url?: string | URL | null
): void {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if (data?.__NA || data?._N) {
return originalReplaceState(data, _unused, url)
}
data = copyNextJsInternalHistoryState(data)
if (url) {
applyUrlFromHistoryPushReplace(url)
}
return originalReplaceState(data, _unused, url)
}
}
@ -536,10 +535,8 @@ function Router({
// Register popstate event to call onPopstate.
window.addEventListener('popstate', onPopState)
return () => {
if (originalPushState) {
if (process.env.__NEXT_WINDOW_HISTORY_SUPPORT) {
window.history.pushState = originalPushState
}
if (originalReplaceState) {
window.history.replaceState = originalReplaceState
}
window.removeEventListener('popstate', onPopState)

View file

@ -32,7 +32,7 @@ export default function Page() {
previousQuery ? previousQuery + '-added' : 'foo'
}`
window.history.replaceState(null, '', url)
window.history.pushState(null, '', url)
}}
id="push-string-url-null"
>