Skip to content

fix: keep URL on postponed browser back/forward with vaadin-router - #27141

Merged
caalador merged 24 commits into
mainfrom
postpone-browser-back-url-reproduction
Dec 1, 2026
Merged

caalador merged 24 commits into
mainfrom
postpone-browser-back-url-reproduction

Conversation

@totally-not-ai

@totally-not-ai totally-not-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

With reactEnable=false (vaadin-router), when a BeforeLeaveObserver postpones a navigation started with the browser back or forward button, the address bar already showed the target URL while the old view stayed. Cancelling then overwrote the target history entry, so it could no longer be reached with back. Now, while the navigation is postponed, Flow moves the browser back to the history entry of the active view. On proceed it moves on to the target entry. On cancel it leaves the history as it is. React router mode is unchanged.

Fixes #9551

What changed

  • Entry positions (vaadin-router mode only). When Flow is created, it wraps history.pushState and history.replaceState and records the position of every entry created through them in the entry's history.state. This lets Flow tell how many steps a back/forward navigation moved, which the history API does not say.
  • New FlowConfig.trackHistory option, true by default. The generated React Router integration (Flow.tsx) passes trackHistory: false, because React Router returns the browser to the active entry itself; in React mode Flow never wraps the history API or stamps an entry. A vaadin-router application with its own index.ts can pass it too, to turn the handling off.
  • While postponed. If the navigation came from back/forward and the positions are known, Flow calls history.go() back to the entry of the active view. That entry is recorded when a navigation completes, so several quick back/forward presses before the server answers still return to the view that is shown. The popstate from Flow's own move is kept from the router, so it is not a navigation and sends no second ui-navigate.
  • On proceed. Flow calls history.go() on to the target entry, which keeps its own URL and state. History API calls made while Flow moves the browser, such as a server-side forward in the same round trip, are held until the browser has arrived, so they apply to the target entry. The vaadin-navigated event the server fires after such a call is held with it, so its listeners see the new URL.
  • On cancel. Nothing changes in the history: the URL, the entries ahead and behind, and the cancelled target all stay where they were. This holds for back, forward and multi-step jumps (e.g. history.go(-2) from the back button's menu).
  • Reload. Positions live in the entries themselves, so a reload while a navigation is postponed leaves nothing to repair, and later back/forward navigations still work.
  • If the browser does not arrive. If no popstate reports the arrival within a second, Flow stops holding the history calls and completes the navigation. If the popstate comes later, it is still kept from the router.
  • State sent to the server. Flow removes its keys before sending history.state with ui-navigate, so HistoryStateChangeEvent.getState() is unchanged.
  • Fallback. When the target entry or the active view's entry has no position, the behaviour is the same as before this change: the address bar shows the target URL while the navigation is postponed, and on cancel vaadin-router writes the active view's URL into the target entry. An entry has no position when its state is neither null nor a plain object (e.g. an application stores a string). An entry the browser creates without the history API, such as a fragment navigation, gets a position in a new segment. Positions only compare within one segment, so the fallback applies when a back/forward crosses into another segment.
  • The server no longer needs to send the active view's location when it postpones, so UI is back to what it was.

Risks

Everything listed here applies only to applications with reactEnable=false. React Router mode, the default, is not affected: the generated Flow.tsx passes trackHistory: false. An application with reactEnable=false turns all of it off by passing trackHistory: false when it creates Flow in its index.ts, e.g. new Flow({ imports: ..., trackHistory: false }).

  • The History API is patched as soon as Flow is created, also in an application that only uses client-side routes. history.pushState and history.replaceState are replaced on window.history, and the state of the current entry is rewritten to carry its position. Code that captured the original functions before Flow was created makes entries without a position, which falls back as described above.
  • history.state changes for application code. A plain-object state gets a vaadinHistoryPosition key. A null state becomes {vaadinHistoryPosition, vaadinNullState: true}, so code that checks history.state === null behaves differently. vaadin-router stores null for its entries, so this applies to most entries. The state the server receives is unchanged.
  • Flow keeps the popstate of its own moves from later listeners with stopImmediatePropagation. Flow's listener is added when its module loads, so it runs before the router's. If the user presses back/forward while Flow's own move is in flight, the event is passed on as a normal navigation.
  • vaadin-navigated can come later. While Flow holds history calls, the event is dispatched again once the held call has run, after the browser arrived.

Test summary

  • Browser tests (vaadin-router mode):
    • the URL stays while a back or forward navigation is postponed; proceeding completes it and forward history still works;
    • after cancelling a postponed back, back still reaches the cancelled target;
    • cancelling a postponed forward keeps the URL, forward reaches the target again, and back reaches the initial view;
    • cancelling a postponed history.go(-2) keeps the URL and both entries in between;
    • two quick backs before the server answers keep the active URL, also after cancelling;
    • a reload while a back is postponed keeps the history working;
    • a link click while a back is postponed, then cancelled, still lets back reach the original target.
  • Browser tests in a second vaadin-router application: the URL stays while a back or forward navigation is postponed, and proceeding completes it.
  • Browser test (React router mode): a postponed back keeps the URL, cancelling keeps it, React Router's history state carries no Flow keys, and back then proceeds as before.
  • Client unit tests:
    • back, forward and two-step back, each for cancel and proceed: where the browser ends, that the router sees only the user's popstate, and that one ui-navigate is sent;
    • two quick backs, for cancel and for proceed;
    • the server answering before Flow's move ends; a history change and its vaadin-navigated event during the move; a redirect after proceed;
    • a move the browser never reports, and its late arrival;
    • entries created after a fragment navigation; a reload while postponed; a target entry without a position; the browser having left the target entry already; the state sent to the server without Flow's keys;
    • with trackHistory: false the history API is not wrapped and entries keep a null state, also after back; by default entries get a position.
  • Without the fix, the vaadin-router browser tests fail. The navigation, history and postpone browser tests of both router modes and all client unit tests pass.

Working on behalf of Artur

Asserts that the URL stays while a back navigation is postponed and that
forward history still works after proceeding. Fails with vaadin-router
(reactEnable=false), passes with the React router.

Part of #9551
When a BeforeLeaveObserver postponed a navigation started with the
browser back or forward button, the address bar already showed the
target URL while the old view stayed. Cancelling then replaced the
target history entry with the current URL, losing that entry.

When the server reports the navigation as postponed, the client now
pushes the URL of the still active view on top of the target entry.
Proceeding steps back to the target entry without starting a new
navigation, so forward history is kept. Cancelling leaves history as
it was before the back/forward navigation.

Only affects reactEnable=false; the React router already restores the
URL itself.

Fixes #9551
Pushing the active URL on top of the target entry dropped all entries
ahead of it and put the entry in the wrong order on forward navigation.
Instead, the target entry shows the active URL while the navigation is
postponed and gets its own URL and state back when the server answers,
so proceeding leaves history exactly as the browser made it, for back
and forward alike. Only cancelling adds an entry for the active view,
so that the cancelled target can still be reached with back.

The back/forward detection is tied to the URL of the popstate, so a
popstate to a client route no longer marks a later navigation.
@Artur-
Artur- marked this pull request as ready for review November 20, 2026 13:03
@github-actions

Copy link
Copy Markdown
Contributor

Postpone now restores the browser-back entry instead of overwriting it

sequenceDiagram
    participant H as Browser history API
    participant F as Flow.ts
    participant S as UI.serverPaused / serverConnected

    H->>F: popstate fires, URL already moved to target
    F->>F: onPopstate records popstateUrl (new, capture phase)
    F->>S: sends ui-navigate for the target route
    S->>S: BeforeLeaveObserver calls event.postpone()
    S->>F: serverPaused(activeLocation) (new argument)
    F->>H: showActiveUrl() replaceState back to active view's URL (new)
    Note over F,H: entry the browser moved to now shows the active view again
    S->>F: serverConnected(cancel)
    F->>H: restorePostponedEntry() replaceState entry.url to target (new)
    alt cancelled
        F->>H: pushState for active view on top of target (new)
        Note over H: back still reaches the postponed target
    else proceeded
        Note over H: target entry keeps its own URL, forward history intact
    end
Loading

In vaadin-router mode, Flow.onPopstate now records the URL the browser already jumped to, and UI.serverPaused sends the still-active view's location to the client so showActiveUrl can temporarily replace that history entry. When the server answers via serverConnected, restorePostponedEntry gives the target entry its URL back and, only on cancel, pushes a new entry for the active view — per the PR description and #9551.

Diagram Bot draws the mechanism this pull request touches; it does not review the change. Verify it against the diff.

Generated by Diagram Bot for #27141 · agent · 52 AIC · ⊞ 9.2K · ◷

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 2 comments.

Finding
⚠️ The "URL already matches" guard compares a re-serialized server location against the literal browser URL, so views with query parameters take the back/forward branch even when they should not.
⚠️ If another navigation starts while a navigation is postponed, the rewritten history entry keeps the active view's URL forever.

Comment thread flow-client/src/main/frontend/Flow.ts Outdated
private showActiveUrl(activeLocation: string): PostponedHistoryEntry | undefined {
const url = new URL(activeLocation, document.baseURI);
const { pathname, search, hash } = window.location;
if (url.pathname === pathname && url.search === search) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ The "URL already matches" guard compares a re-serialized server location against the literal browser URL, so views with query parameters take the back/forward branch even when they should not.

getPathWithQueryParameters() rebuilds the query from a HashMap and re-encodes every value with encodeURIComponent, so the browser's ?q=a+b&p=1 comes back as ?p=1&q=a%20b. The guard then sees a difference that does not exist.

This guard is what keeps the new code out of React mode, where React Router has already restored the URL. With query parameters on the active view, a postponed back now:

  • rewrites the URL of the entry the user is already on, and
  • on cancel pushes an extra entry carrying state: null, which React Router did not create and whose idx it cannot read.

In vaadin-router mode the effect is milder: the active view's query string comes back normalized.

Flow.ts:332 · correctness

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vaadin-review-bot Good catch. The check no longer uses the server's location: it now compares the browser URL with the back/forward target, both read from the browser. If the router has already moved the URL away from the target (React Router), nothing is rewritten. The server's location is only used for the URL shown while postponed, so in vaadin-router mode its query string can come back reordered or re-encoded. That limitation is now listed in the description.

Comment thread flow-client/src/main/frontend/Flow.ts Outdated
if (this.response) {
const fromPopstate = this.popstateUrl !== undefined && this.popstateUrl === ctx.pathname + (ctx.search ?? '');
this.popstateUrl = undefined;
let postponedEntry: PostponedHistoryEntry | undefined;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ If another navigation starts while a navigation is postponed, the rewritten history entry keeps the active view's URL forever.

postponedEntry lives in the flowNavigate closure and is only read from the serverConnected that the same call installed. The next flowNavigate or flowLeave overwrites container.serverConnected, and nothing else restores the entry.

Pressing back a second time while the confirm buttons are up, or clicking another link, therefore leaves the entry the browser first moved to pointing at the active view's URL. Navigating back to it later lands on the wrong view, and the original target is unreachable.

Flow.ts:273 · correctness

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vaadin-review-bot Fixed. The rewritten entry is now marked in history.state instead of being tracked in the closure. A new navigation that starts from that entry (e.g. a link click) handles the postponed one like a cancel: the entry gets its own URL back and the active view gets an entry on top. If the browser leaves the entry first (back/forward or a server-side navigation), the entry gets its own URL and state back as soon as the browser returns to it, before the router reads the URL. New browser tests cover a link click and a forward while a back is postponed.

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 1 711 files  ± 0   1 802 suites  +1   2h 4m 43s ⏱️ - 2m 24s
14 023 tests +28  13 951 ✅ +28  72 💤 ±0  0 ❌ ±0 
14 701 runs  +28  14 629 ✅ +28  72 💤 ±0  0 ❌ ±0 

Results for commit 4123eb2. ± Comparison against base commit 07b92e0.

♻️ This comment has been updated with latest results.

Decide whether the router already restored the URL by comparing the
browser URL with the back/forward target, both taken from the browser.
Comparing with the location from the server reported a difference for
query strings the server serializes differently.

When a new navigation starts while a back/forward navigation is
postponed, treat the postponed one as cancelled: give its entry its own
URL back and add an entry for the active view, so its target can still
be reached with back.
The entry that shows the active view's URL while a back/forward
navigation is postponed is now marked in its history state. When the
browser leaves it before the server answers, e.g. with another back or
forward, or a server-side navigation, the entry gets its own URL and
state back once the browser returns to it, before the router reads the
URL. Before, it kept the active view's URL for good.

The entry is left alone when the target URL equals the active view's
URL, and cancelling keeps the hash of the current URL.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

The SonarCloud finding on UI.java:143 (pushConfiguration could be final) is in existing code that this PR doesn't touch; it is reported only because the file changed. To keep this PR to the postpone/history fix, I left it out — it fits better in a separate cleanup.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Bundle size

Compared with the base commit 07b92e0.

File Minified Change Brotli Change
sw.js 20,674 B no change 6,141 B no change
VAADIN/build/ApplicationConnection.js 125,051 B no change 32,276 B no change
VAADIN/build/FlowBootstrap.js 3,191 B no change 1,027 B no change
VAADIN/build/FlowClient.js 10,723 B no change 3,503 B no change
VAADIN/build/frontend.js 408,828 B $\color{red}\textbf{+3,139 B}$ (+0.8%) 111,483 B $\color{red}\textbf{+852 B}$ (+0.8%)
VAADIN/build/generated-flow-imports.js 2,945 B no change 1,100 B no change
VAADIN/build/indexhtml.js 47 B no change 51 B no change
VAADIN/build/rolldown-runtime.js 870 B no change 437 B no change
Total 572,329 B $\color{red}\textbf{+3,139 B}$ (+0.6%) 156,018 B $\color{red}\textbf{+852 B}$ (+0.5%)
Size by module, before minification
Module Change
src/main/frontend/generated/jar-resources/Flow.js +6,724 B
src/main/frontend/generated/flow/Flow.tsx +29 B

The production bundle of test-prod-bundle, an application with no code of its own: the Flow client, the files Flow generates and the npm packages it brings in. Brotli is what the build precompresses the files with.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 1 comment.

Finding
🧪 Nothing tests the guard that keeps the history rewriting out of React Router mode.

Comment thread flow-client/src/main/frontend/Flow.ts Outdated
private showActiveUrl(activeLocation: string, targetUrl: string): PostponedHistoryEntry | undefined {
const { pathname, search, hash } = window.location;
const url = new URL(activeLocation, document.baseURI);
if (pathname + search !== targetUrl || url.pathname + url.search === targetUrl) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 Nothing tests the guard that keeps the history rewriting out of React Router mode.

pathname + search !== targetUrl is the only thing that stops the new code from running in React mode — fromPopstate is true there too, because the blocker effect runs before the revert popstate from React Router's history.go(-delta) lands.

If that condition is weakened, a postponed back in React mode replaces React Router's {usr, key, idx} state with the mark, and a cancel pushes an entry with state: null, so React Router can no longer compute a delta for that entry. The React-mode IT added here only compares URLs and would still pass.

This is client-only decision logic, and CONVENTIONS.md points it at flow-client/src/test/frontend/: the existing harness can call container.serverPaused(...) directly and assert that history.state and the URL are untouched when the browser URL no longer matches the navigation target.

Flow.ts:355 · tests

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added client unit tests in FlowTests.ts that call serverPaused directly after a simulated popstate. One sets React Router-style state and moves the URL back to the active view before the pause, then checks that history.state, the URL and history.length are untouched through pause and cancel. It fails if the pathname + search !== targetUrl check is removed. Two more cover the other paths: the rewrite when the browser still shows the target (including back reaching the target with its own state after cancel), and the skip when the active location already is the target.

Check that a postponed back navigation leaves history state and URL
untouched when the router already restored the active URL, as React
Router does, and that the URL is rewritten when the browser still shows
the target.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 1 comment.

Finding
⚠️ The capture flag does not make Flow see popstate before the router, as the comment claims.

Comment thread flow-client/src/main/frontend/Flow.ts Outdated
this.appShellTitle = document.title;

// Capture phase, so that Flow sees the event before the router does
window.addEventListener('popstate', (event) => this.onPopstate(event), { capture: true });

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ The capture flag does not make Flow see popstate before the router, as the comment claims.

popstate is dispatched at window, so every window listener runs in the AT_TARGET phase and capture vs. bubble has no effect on ordering — registration order decides. Restoring a marked entry before the router reads window.location works only because the generated index.ts constructs Flow before new Router(...).

In an entry point that creates the router first (applications may replace index.ts), vaadin-router's popstate trigger reads the active view's URL out of the marked entry and navigates there, while the address bar ends up showing the restored target URL.

Flow.ts:157 · correctness

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Flow now adds its popstate listener once, when Flow.ts loads, and hands the event to the Flow instance created last. vaadin-router adds its listener in the Router constructor, so Flow's listener now comes first however the entry point orders the two. I checked in Chromium that a capture listener on window still runs after a plain listener added before it, so registration order is what counts here. A new client test adds a "router" listener before Flow is created. It checks that the router sees the entry's own URL when the browser returns to a postponed entry, and it fails with the old registration in the constructor.

@caalador caalador left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Cancelling a forward navigation reverses the history and drops later entries (Flow.ts, restorePostponedEntry, the pushState when cancel is true). The new IT confirms this.
  • On cancel, the code puts the target entry's own URL back and then pushes a new entry for the active view. That is only correct for a single step back.
  • Forward: history A(active), B, C becomes A, B, A'. C is gone, forward is disabled, and back leads to B, the target the user just cancelled.
  • Jumping several entries back (go(-n) from the back-button dropdown): history Z, A, B(active), jump to Z and cancel → Z, B'. A is gone.
  • A suggested fix: record each entry's position in history.state (as React Router does with idx). On cancel, call history.go(-delta) to return to the original entry, and ignore the popstate that causes.
  1. Postponed entries are tracked only in memory, so a reload breaks them (postponedEntries / lastPostponedEntryId)
  • If the user reloads while a back navigation is postponed, entry A keeps B's URL and {vaadinPostponedEntry: 1} as its state permanently. A can no longer be reached in that tab.
  • Ids restart at 1 after a reload, so a leftover entry can match a new entry with the same id. onPopstate would then restore the wrong URL.
  • A suggested fix: store the original {state, url} directly in history.state, plus a per-page-load nonce, instead of using the map.

Window listeners for popstate run in the order they were added, and the
capture flag has no effect on that. Add Flow's listener when its module
loads, so that it restores a postponed entry before vaadin-router reads
the URL even when an entry point creates the router before Flow.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@caalador Thanks, both points are right. I haven't changed this part yet, because the fix you suggest replaces the whole mechanism and comes with its own trade-offs:

Option A: keep rewriting the entry and fix the reload problem. Store the entry's own {state, url} in its history state instead of an in-memory map, plus a per-page-load id. A reload no longer strands the entry, and ids can't collide. Cancelling a forward navigation or a multi-step jump still loses the later entries, as the PR description lists today.

Option B: return to the active entry with history.go(-delta) (your suggestion). Flow stamps a position in each entry's history state. When the server postpones, Flow moves the browser back to the active entry and hides that popstate from the router. On proceed it moves forward again, and on cancel it changes nothing. History stays intact in every direction, and nothing is left behind on reload, so point 2 goes away too. The query string also stays exactly as the user had it. The cost: Flow doesn't create the entries vaadin-router pushes, so it has to stamp them afterwards. When vaadin-router dispatches its popstate after a pushState or replaceState, Flow can't tell which of the two happened, and a wrong guess makes go() land on the wrong entry. Entries without a stamp, such as ones created by application code, would fall back to today's behaviour.

I lean towards B because it fixes the forward case. It is a bigger rewrite, though, so tell me which one you prefer.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 1 comment.

Finding
⚠️ The active view's URL is rebuilt from the server's location, and on cancel that rebuilt URL becomes the view's permanent history entry.

Comment thread flow-client/src/main/frontend/Flow.ts Outdated
id: this.lastPostponedEntryId,
state: window.history.state,
url: pathname + search + hash,
activeUrl: url.pathname + url.search

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ The active view's URL is rebuilt from the server's location, and on cancel that rebuilt URL becomes the view's permanent history entry.

getPathWithQueryParameters() re-encodes every query value with encodeURIComponent, which escapes /, : and spaces, so ?return=/home comes back as ?return=%2Fhome. It also appends the fragment, which url.pathname + url.search then drops.

The description lists the re-encoding as a limitation of the URL shown while postponed, but it does not stop there: on cancel, restorePostponedEntry pushes the current (rewritten) location, so the active view keeps the escaped, fragment-less URL in its own history entry afterwards. Where that string differs from what vaadin-router holds as its location, the router's history update after prevent() is likely to add a second entry for the same view.

No IT or client test uses a view with query parameters, so none of this would show up.

Flow.ts:374 · correctness

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. It also goes beyond what is shown while postponed: on cancel, the active view keeps the rebuilt URL in its own history entry. I've corrected the limitation in the PR description to say so, but haven't changed the code yet, because the fix depends on the open choice between the two designs in my earlier PR comment:

  • With B (return to the active entry with history.go(-delta)), no URL is ever rebuilt. The browser goes back to the real entry, so the query string, fragment and entry stay exactly as the user had them, and the server no longer needs to send the location.
  • With A, I'd stop using the server's location and use the URL the browser showed before the back/forward instead. I'd also add a test with a view that has query parameters and a fragment.

Once that's decided, I'll fix this the matching way.

@caalador

Copy link
Copy Markdown
Contributor

Let's go with B. It fixes the forward and multi-step cases, gets rid of the in-memory map, and it also settles the newest review-bot finding: the view's rebuilt URL becoming its permanent entry on cancel. With B, Flow never writes a URL of its own into history.

On the push vs replace problem: rather than guessing from the popstate vaadin-router dispatches, could Flow wrap history.pushState / history.replaceState and stamp the position as each call happens? Every entry created through the History API would then carry a correct position, including ones created by application code. Only entries Flow didn't see (from before Flow loaded, or after a reload) would be left without one. If wrapping turns out to be a bad idea, explain why and what you'd use instead.

A few things I'd like covered:

  • Fallback: when the active entry or the target entry has no position, what happens? Spell it out in the description and test it.
  • The extra popstate from go(-delta) must not reach vaadin-router as a navigation, or fire a second ui-navigate.
  • Proceed: moving forward again with go(+delta) must land on the original target entry, with its own state and URL.
  • Tests:
    • an IT for cancelling a forward navigation (below; it fails on the current head at the second forward()),
    • an IT for a multi-step jump (go(-2)) that is cancelled,
    • a client test for a reload while a navigation is postponed.

IT for cancelling a forward navigation (test-vaadin-router PostponeUpdateIT)

  @Test
  public void postpone_cancelForward_keepsUrlAndForwardHistory() {
      open(); 
      String initialUrl = getDriver().getCurrentUrl();
      
      findElement(By.id("link")).click();
      $(NativeButtonElement.class).id("proceedButton").click();
      waitUntil(driver -> driver.getCurrentUrl().endsWith("/1"));
      String postponingUrl = getDriver().getCurrentUrl();
      
      getDriver().navigate().back();
      waitUntil(driver -> isElementPresent(By.id("proceedButton")));
      $(NativeButtonElement.class).id("proceedButton").click();
      waitUntil(driver -> driver.getCurrentUrl().equals(initialUrl), 5);
      
      // Forward is postponed and then cancelled
      getDriver().navigate().forward();
      waitUntil(driver -> isElementPresent(By.id("cancelButton")));
      Assert.assertEquals(
              "While the forward navigation is postponed, the URL should stay",
              initialUrl, getDriver().getCurrentUrl());
      $(NativeButtonElement.class).id("cancelButton").click();
      waitUntil(driver -> !isElementPresent(By.id("cancelButton")));
      Assert.assertEquals("Cancelling should keep the URL of the view",
              initialUrl, getDriver().getCurrentUrl());
              
      // The cancelled target is still ahead in the history: forward
      // reaches it again
      getDriver().navigate().forward();
      waitUntil(driver -> isElementPresent(By.id("proceedButton")), 5);
      $(NativeButtonElement.class).id("proceedButton").click();
      waitUntil(driver -> driver.getCurrentUrl().equals(postponingUrl), 5);
      
      // And no entry was added behind the view: back reaches the initial
      // view, not a copy of the cancelled target
      getDriver().navigate().back();
      waitUntil(driver -> isElementPresent(By.id("proceedButton")), 5);
      $(NativeButtonElement.class).id("proceedButton").click();
      waitUntil(driver -> driver.getCurrentUrl().equals(initialUrl), 5);
  }

@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@caalador Fixed. Flow now records the position of the active view's entry when a navigation completes, and always returns to that entry. For two quick backs it computes the steps from the active entry to where the browser is now, so several presses in a row return to the view that is shown, and a second answer from the server doesn't move the browser again. Your IT is in PostponeUpdateIT as postpone_twoQuickBacks_keepsActiveUrl. Client tests cover two quick backs both on cancel and on proceed; proceed lands on the last target, with both entries in between still there.

On the smaller points:

  • Timeout. If no popstate reports the arrival within a second, Flow stops holding the history calls and completes the navigation. If the popstate arrives later anyway, it is still kept from the router, so it doesn't start a second navigation. A client test stubs history.go() to check both.
  • vaadin-navigated. While Flow holds history calls, it also holds the vaadin-navigated event that follows them and dispatches it again after the held call has run, so listeners read the new URL. Flow's listener for it is added when its module loads, ahead of the application's. The client test for a forward during the move checks the URL seen by a listener.
  • Side effects. The description now has a Risks section: the History API is patched, and history.state is no longer null on stamped entries, so history.state === null checks behave differently. Both apply to vaadin-router mode only now (see my other reply).

@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@caalador Done: React mode now behaves as on main. Flow wraps history.pushState/replaceState and stamps positions only once vaadin-router calls its route action. It recognizes vaadin-router by the route context, which has next(); React mode passes only the location. Flow's popstate and vaadin-navigated listeners are still added when the module loads, because they have to run before the router's, but in React mode they do nothing. A separate client suite, which runs in a page of its own, checks that in React mode history.pushState is not wrapped and entries keep a null state, also after a back navigation. The React-mode postpone, history and forward ITs pass.

@caalador

Copy link
Copy Markdown
Contributor

Looks ok, but one small thing:
How React mode is recognised (Flow.ts:379). Checking for next() on the route context works, but it relies on how vaadin-router builds its context. Flow.tsx is generated by Flow itself, so an explicit option there (e.g. new _Flow({ imports, trackHistory: false })) would be harder to break by accident. If you keep the next() check, a comment saying React mode must never pass a context with next would help whoever changes Flow.tsx next.

The React Router integration now passes trackHistory: false when it
creates Flow, instead of Flow recognizing vaadin-router by the next()
of its route context. Tracking starts when Flow is created, so entries
created before the first server-side route get positions too.

A browser test in a React Router application checks that a postponed
back keeps the URL and leaves React Router's history state as it is.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@caalador Switched to an explicit option. FlowConfig now has trackHistory, true by default, and the generated Flow.tsx creates Flow with trackHistory: false. The next() check is gone. Tracking now starts when Flow is created rather than on the first route action, so entries from client-side routes visited before the first server view get positions too. The option is documented and public, so a vaadin-router app whose own JavaScript relies on history.state can turn the handling off in its index.ts. The description lists both under Risks.

A correction to my earlier reply: test-root-context doesn't depend on flow-react and runs on vaadin-router, so the ITs I ran there didn't cover React mode. I added a browser test to test-default/NavigationIT, which does run on React Router. It postpones a back navigation, cancels it, checks that the URL stayed and that React Router's history state has no Flow keys, then goes back and proceeds. It fails when Flow.tsx turns tracking on.

@sonarqubecloud

Copy link
Copy Markdown

@caalador

caalador commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

I don't think this needs fix!:. A plain fix: should be enough.

  • Default apps aren't affected. React Router is the default (react.enable defaults to true), and there the generated Flow.tsx passes trackHistory: false. React-mode apps see no History API wrapping and no Flow keys in history.state, and the React NavigationIT test checks that.
  • There's no API or server contract change. UI is back to what it was, the state the server gets in HistoryStateChangeEvent.getState() is unchanged, and FlowConfig.trackHistory is only an addition.
  • The history fix itself is a behaviour change, not a breaking one. Cancel used to overwrite the target entry, which was the bug.
  • The side effects are narrow. The changed history.state shape and the wrapped pushState/replaceState only reach apps that set reactEnable=false, and only client-side JavaScript that reads history.state or relies on the original functions. Those apps can turn it off with trackHistory: false.

Could you change the title to fix: keep URL on postponed browser back/forward with vaadin-router? Please also make the Risks section say explicitly that everything listed applies only with reactEnable=false, and that trackHistory: false in the app's index.ts turns it off.

@totally-not-ai totally-not-ai Bot changed the title fix!: keep URL on postponed browser back/forward with vaadin-router fix: keep URL on postponed browser back/forward with vaadin-router Dec 1, 2026
@totally-not-ai

totally-not-ai Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@caalador Done. The title is now fix: keep URL on postponed browser back/forward with vaadin-router. The Risks section now opens by saying that everything in it applies only with reactEnable=false, that React Router mode is unaffected because the generated Flow.tsx passes trackHistory: false, and that an app turns it all off by passing trackHistory: false to new Flow(...) in its index.ts.

@caalador
caalador added this pull request to the merge queue Dec 1, 2026
Merged via the queue into main with commit 1982585 Dec 1, 2026
75 checks passed
@caalador
caalador deleted the postpone-browser-back-url-reproduction branch December 1, 2026 08:18
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Documentation Bot: No documentation needed for this change.

This is a BEHAVIOR_CHANGE (bug fix) and an API_CHANGE restricted to the deprecated reactEnable=false (vaadin-router) code path: it fixes browser back/forward URL handling during a postponed navigation and adds a FlowConfig.trackHistory escape hatch for custom index.ts files in that mode, which has no existing documentation page and is not the direction readers are being pointed in (vaadin-router is deprecated and removed in Vaadin 26). React Router mode, the default and documented path, is unaffected.

Nothing was opened in vaadin/docs. If you disagree, the change has to be documented by hand there.

Generated by Documentation Bot for #27141 · agent · 37.7 AIC · ⊞ 11.7K · ◷

vaadin-bot added a commit that referenced this pull request Dec 1, 2026
…27141) (CP: 25.4) (#27569)

This PR cherry-picks changes from the original PR #27141 to branch 25.4.

---

> ## Summary
> With `reactEnable=false` (vaadin-router), when a `BeforeLeaveObserver`
postpones a navigation started with the browser back or forward button,
the address bar already showed the target URL while the old view stayed.
Cancelling then overwrote the target history entry, so it could no
longer be reached with back. Now, while the navigation is postponed,
Flow moves the browser back to the history entry of the active view. On
proceed it moves on to the target entry. On cancel it leaves the history
as it is. React router mode is unchanged.
> 
> Fixes #9551
> 
> ## What changed
> - **Entry positions (vaadin-router mode only).** When Flow is created,
it wraps `history.pushState` and `history.replaceState` and records the
position of every entry created through them in the entry's
`history.state`. This lets Flow tell how many steps a back/forward
navigation moved, which the history API does not say.
> - **New `FlowConfig.trackHistory` option**, `true` by default. The
generated React Router integration (`Flow.tsx`) passes `trackHistory:
false`, because React Router returns the browser to the active entry
itself; in React mode Flow never wraps the history API or stamps an
entry. A vaadin-router application with its own `index.ts` can pass it
too, to turn the handling off.
> - **While postponed.** If the navigation came from back/forward and
the positions are known, Flow calls `history.go()` back to the entry of
the active view. That entry is recorded when a navigation completes, so
several quick back/forward presses before the server answers still
return to the view that is shown. The `popstate` from Flow's own move is
kept from the router, so it is not a navigation and sends no second
`ui-navigate`.
> - **On proceed.** Flow calls `history.go()` on to the target entry,
which keeps its own URL and state. History API calls made while Flow
moves the browser, such as a server-side forward in the same round trip,
are held until the browser has arrived, so they apply to the target
entry. The `vaadin-navigated` event the server fires after such a call
is held with it, so its listeners see the new URL.
> - **On cancel.** Nothing changes in the history: the URL, the entries
ahead and behind, and the cancelled target all stay where they were.
This holds for back, forward and multi-step jumps (e.g. `history.go(-2)`
from the back button's menu).
> - **Reload.** Positions live in the entries themselves, so a reload
while a navigation is postponed leaves nothing to repair, and later
back/forward navigations still work.
> - **If the browser does not arrive.** If no `popstate` reports the
arrival within a second, Flow stops holding the history calls and
completes the navigation. If the `popstate` comes later, it is still
kept from the router.
> - **State sent to the server.** Flow removes its keys before sending
`history.state` with `ui-navigate`, so
`HistoryStateChangeEvent.getState()` is unchanged.
> - **Fallback.** When the target entry or the active view's entry has
no position, the behaviour is the same as before this change: the
address bar shows the target URL while the navigation is postponed, and
on cancel vaadin-router writes the active view's URL into the target
entry. An entry has no position when its state is neither `null` nor a
plain object (e.g. an application stores a string). An entry the browser
creates without the history API, such as a fragment navigation, gets a
position in a new segment. Positions only compare within one segment, so
the fallback applies when a back/forward crosses into another segment.
> - The server no longer needs to send the active view's location when
it postpones, so `UI` is back to what it was.
> 
> ## Risks
> Everything listed here applies only to applications with
`reactEnable=false`. React Router mode, the default, is not affected:
the generated `Flow.tsx` passes `trackHistory: false`. An application
with `reactEnable=false` turns all of it off by passing `trackHistory:
false` when it creates Flow in its `index.ts`, e.g. `new Flow({ imports:
..., trackHistory: false })`.
> - **The History API is patched as soon as Flow is created**, also in
an application that only uses client-side routes. `history.pushState`
and `history.replaceState` are replaced on `window.history`, and the
state of the current entry is rewritten to carry its position. Code that
captured the original functions before Flow was created makes entries
without a position, which falls back as described above.
> - **`history.state` changes for application code.** A plain-object
state gets a `vaadinHistoryPosition` key. A `null` state becomes
`{vaadinHistoryPosition, vaadinNullState: true}`, so code that checks
`history.state === null` behaves differently. vaadin-router stores
`null` for its entries, so this applies to most entries. The state the
server receives is unchanged.
> - **Flow keeps the `popstate` of its own moves from later listeners**
with `stopImmediatePropagation`. Flow's listener is added when its
module loads, so it runs before the router's. If the user presses
back/forward while Flow's own move is in flight, the event is passed on
as a normal navigation.
> - **`vaadin-navigated` can come later.** While Flow holds history
calls, the event is dispatched again once the held call has run, after
the browser arrived.
> 
> ## Test summary
> - Browser tests (vaadin-router mode):
> - the URL stays while a back or forward navigation is postponed;
proceeding completes it and forward history still works;
> - after cancelling a postponed back, back still reaches the cancelled
target;
> - cancelling a postponed forward keeps the URL, forward reaches the
target again, and back reaches the initial view;
> - cancelling a postponed `history.go(-2)` keeps the URL and both
entries in between;
> - two quick backs before the server answers keep the active URL, also
after cancelling;
>   - a reload while a back is postponed keeps the history working;
> - a link click while a back is postponed, then cancelled, still lets
back reach the original target.
> - Browser tests in a second vaadin-router application: the URL stays
while a back or forward navigation is postponed, and proceeding
completes it.
> - Browser test (React router mode): a postponed back keeps the URL,
cancelling keeps it, React Router's history state carries no Flow keys,
and back then proceeds as before.
> - Client unit tests:
> - back, forward and two-step back, each for cancel and proceed: where
the browser ends, that the router sees only the user's `popstate`, and
that one `ui-navigate` is sent;
>   - two quick backs, for cancel and for proceed;
> - the server answering before Flow's move ends; a history change and
its `vaadin-navigated` event during the move; a redirect after proceed;
>   - a move the browser never reports, and its late arrival;
> - entries created after a fragment navigation; a reload while
postponed; a target entry without a position; the browser having left
the target entry already; the state sent to the server without Flow's
keys;
> - with `trackHistory: false` the history API is not wrapped and
entries keep a `null` state, also after back; by default entries get a
position.
> - Without the fix, the vaadin-router browser tests fail. The
navigation, history and postpone browser tests of both router modes and
all client unit tests pass.
> 
> Working on behalf of Artur
> 
>

Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
Co-authored-by: caalador <mikael.grankvist@vaadin.com>
caalador added a commit that referenced this pull request Dec 2, 2026
…27141) (CP: 25.3) (#27571)

This PR cherry-picks changes from the original PR #27141 to branch 25.3.

The original commit conflicts on 25.3, so this PR picks the 25.4 pick
#27569 instead, which already adapted the change to an older branch.

> [!WARNING]
> The cherry-pick had merge conflicts that were resolved automatically
by Claude Code. Please review the changes carefully.

**Resolution notes from Claude:**

- Flow.ts: 25.3 lacks #27058 (settleRoundTrip/navigationAnswered wrapper
around serverConnected), so the pick's serverConnected bodies were
assigned directly to this.container.serverConnected as on 25.3, with the
settleRoundTrip resets dropped; the history-position logic is unchanged.
- tsconfig.json (test): kept 25.3's version. The 25.4 version lists
suites from #26714/#26866 (missing on 25.3); adding
FlowRouterModeTests.ts there clashes with 25.3's eslint
allowDefaultProject glob 'src/test/frontend/*', so the new suite stays
in the default project like the other root-level suites.
- FlowRouterModeTests.ts: imports ConnectionState/ConnectionStateStore
from @​vaadin/common-frontend, as ConnectionState was moved into
flow-client only by #26714 (missing on 25.3).
- Verified: spotless, mvn install -DskipTests for flow-client,
flow-server and the three flow-tests modules (incl. tsc, test typecheck,
eslint). Client unit tests and the ITs (NavigationIT, both
PostponeUpdateIT) were not run.

---

> ## Summary
> With `reactEnable=false` (vaadin-router), when a `BeforeLeaveObserver`
postpones a navigation started with the browser back or forward button,
the address bar already showed the target URL while the old view stayed.
Cancelling then overwrote the target history entry, so it could no
longer be reached with back. Now, while the navigation is postponed,
Flow moves the browser back to the history entry of the active view. On
proceed it moves on to the target entry. On cancel it leaves the history
as it is. React router mode is unchanged.
> 
> Fixes #9551
> 
> ## What changed
> - **Entry positions (vaadin-router mode only).** When Flow is created,
it wraps `history.pushState` and `history.replaceState` and records the
position of every entry created through them in the entry's
`history.state`. This lets Flow tell how many steps a back/forward
navigation moved, which the history API does not say.
> - **New `FlowConfig.trackHistory` option**, `true` by default. The
generated React Router integration (`Flow.tsx`) passes `trackHistory:
false`, because React Router returns the browser to the active entry
itself; in React mode Flow never wraps the history API or stamps an
entry. A vaadin-router application with its own `index.ts` can pass it
too, to turn the handling off.
> - **While postponed.** If the navigation came from back/forward and
the positions are known, Flow calls `history.go()` back to the entry of
the active view. That entry is recorded when a navigation completes, so
several quick back/forward presses before the server answers still
return to the view that is shown. The `popstate` from Flow's own move is
kept from the router, so it is not a navigation and sends no second
`ui-navigate`.
> - **On proceed.** Flow calls `history.go()` on to the target entry,
which keeps its own URL and state. History API calls made while Flow
moves the browser, such as a server-side forward in the same round trip,
are held until the browser has arrived, so they apply to the target
entry. The `vaadin-navigated` event the server fires after such a call
is held with it, so its listeners see the new URL.
> - **On cancel.** Nothing changes in the history: the URL, the entries
ahead and behind, and the cancelled target all stay where they were.
This holds for back, forward and multi-step jumps (e.g. `history.go(-2)`
from the back button's menu).
> - **Reload.** Positions live in the entries themselves, so a reload
while a navigation is postponed leaves nothing to repair, and later
back/forward navigations still work.
> - **If the browser does not arrive.** If no `popstate` reports the
arrival within a second, Flow stops holding the history calls and
completes the navigation. If the `popstate` comes later, it is still
kept from the router.
> - **State sent to the server.** Flow removes its keys before sending
`history.state` with `ui-navigate`, so
`HistoryStateChangeEvent.getState()` is unchanged.
> - **Fallback.** When the target entry or the active view's entry has
no position, the behaviour is the same as before this change: the
address bar shows the target URL while the navigation is postponed, and
on cancel vaadin-router writes the active view's URL into the target
entry. An entry has no position when its state is neither `null` nor a
plain object (e.g. an application stores a string). An entry the browser
creates without the history API, such as a fragment navigation, gets a
position in a new segment. Positions only compare within one segment, so
the fallback applies when a back/forward crosses into another segment.
> - The server no longer needs to send the active view's location when
it postpones, so `UI` is back to what it was.
> 
> ## Risks
> Everything listed here applies only to applications with
`reactEnable=false`. React Router mode, the default, is not affected:
the generated `Flow.tsx` passes `trackHistory: false`. An application
with `reactEnable=false` turns all of it off by passing `trackHistory:
false` when it creates Flow in its `index.ts`, e.g. `new Flow({ imports:
..., trackHistory: false })`.
> - **The History API is patched as soon as Flow is created**, also in
an application that only uses client-side routes. `history.pushState`
and `history.replaceState` are replaced on `window.history`, and the
state of the current entry is rewritten to carry its position. Code that
captured the original functions before Flow was created makes entries
without a position, which falls back as described above.
> - **`history.state` changes for application code.** A plain-object
state gets a `vaadinHistoryPosition` key. A `null` state becomes
`{vaadinHistoryPosition, vaadinNullState: true}`, so code that checks
`history.state === null` behaves differently. vaadin-router stores
`null` for its entries, so this applies to most entries. The state the
server receives is unchanged.
> - **Flow keeps the `popstate` of its own moves from later listeners**
with `stopImmediatePropagation`. Flow's listener is added when its
module loads, so it runs before the router's. If the user presses
back/forward while Flow's own move is in flight, the event is passed on
as a normal navigation.
> - **`vaadin-navigated` can come later.** While Flow holds history
calls, the event is dispatched again once the held call has run, after
the browser arrived.
> 
> ## Test summary
> - Browser tests (vaadin-router mode):
> - the URL stays while a back or forward navigation is postponed;
proceeding completes it and forward history still works;
> - after cancelling a postponed back, back still reaches the cancelled
target;
> - cancelling a postponed forward keeps the URL, forward reaches the
target again, and back reaches the initial view;
> - cancelling a postponed `history.go(-2)` keeps the URL and both
entries in between;
> - two quick backs before the server answers keep the active URL, also
after cancelling;
>   - a reload while a back is postponed keeps the history working;
> - a link click while a back is postponed, then cancelled, still lets
back reach the original target.
> - Browser tests in a second vaadin-router application: the URL stays
while a back or forward navigation is postponed, and proceeding
completes it.
> - Browser test (React router mode): a postponed back keeps the URL,
cancelling keeps it, React Router's history state carries no Flow keys,
and back then proceeds as before.
> - Client unit tests:
> - back, forward and two-step back, each for cancel and proceed: where
the browser ends, that the router sees only the user's `popstate`, and
that one `ui-navigate` is sent;
>   - two quick backs, for cancel and for proceed;
> - the server answering before Flow's move ends; a history change and
its `vaadin-navigated` event during the move; a redirect after proceed;
>   - a move the browser never reports, and its late arrival;
> - entries created after a fragment navigation; a reload while
postponed; a target entry without a position; the browser having left
the target entry already; the state sent to the server without Flow's
keys;
> - with `trackHistory: false` the history API is not wrapped and
entries keep a `null` state, also after back; by default entries get a
position.
> - Without the fix, the vaadin-router browser tests fail. The
navigation, history and postpone browser tests of both router modes and
all client unit tests pass.
> 
> Working on behalf of Artur
> 
>

---------

Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: caalador <mikael.grankvist@vaadin.com>
Co-authored-by: Mikael Grankvist <mgrankvi@vaadin.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BeforeLeaveEvent::postpone() method doesn't prevent to update the browser URL

3 participants