Skip to content

Commit

Permalink
Don't pushState when already on the url (#42735)
Browse files Browse the repository at this point in the history
Solves the case where you click a link to the page you're on already that pushes additional history entries, uses replaceState for that instead. This mirrors the default `<a>` behavior.



## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
  • Loading branch information
timneutkens authored Nov 10, 2022
1 parent f612acf commit 6490252
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/next/client/components/app-router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,10 @@ function Router({
// __NA is used to identify if the history entry can be handled by the app-router.
// __N is used to identify if the history entry can be handled by the old router.
const historyState = { __NA: true, tree }
if (pushRef.pendingPush) {
if (
pushRef.pendingPush &&
createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl
) {
// This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.
pushRef.pendingPush = false

Expand Down
23 changes: 23 additions & 0 deletions test/e2e/app-dir/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2135,6 +2135,29 @@ describe('app dir', () => {
.text()
).toBe(`About page`)
})
it('should not do additional pushState when already on the page', async () => {
const browser = await webdriver(next.url, '/linking/about')
const goToLinkingPage = async () => {
expect(
await browser
.elementByCss('a[href="/linking"]')
.click()
.waitForElementByCss('#home-page')
.text()
).toBe(`Home page`)
}

await goToLinkingPage()
await waitFor(1000)
await goToLinkingPage()
await waitFor(1000)
await goToLinkingPage()
await waitFor(1000)

expect(
await browser.back().waitForElementByCss('#about-page', 2000).text()
).toBe(`About page`)
})
})

describe('not-found', () => {
Expand Down

0 comments on commit 6490252

Please sign in to comment.