Repository navigation
Better code ergonomics for URL rewriting use cases #5
Description
(Moved from slightlyoff/history_api#23 by @SetTrend, with me synthesizing and summarizing.)
This example, which was formerly in the readme, is an instance of a somewhat-common pattern, of wanting to do slight tweaks to the URL before navigating. I'll quote it here in full (translated to the window.navigation API):
navigation.addEventListener("navigate", e => {
const url = new URL(e.destination.url);
if (url.hostname === "store.example.com") {
url.queryParams.set("affiliateId", "ead21623-781e-442f-a2c4-6cc1b2a9fda2");
e.preventDefault();
location.href = url;
}
});However, as noted there,
TODO: it feels like this should be less disruptive than a cancel-and-perform-new-navigation; it's just a tweak to the outgoing navigation.
To expand on this, code like the above will generate a second navigate event. Which, actually, this code doesn't guard against: so as written this will cause an infinite loop. Oh dear.
I also suspect that sometimes you want to do something like this, but with state, not URLs. For example, something like
navigation.addEventListener("navigate", e => {
if (!e.destination.getState()) {
// We probably got here via an <a> click or something.
const state = figureOutStateForURL(e.destination.url);
e.preventDefault();
navigation.navigate(e.destinationEntry.url, { state });
}
});This example, like the previous one, is unfortunate; canceling the navigation (with e.preventDefault()) then starting a new one feels wrong for this sort of minor tweak.
The question is just what syntax would be better. Here are some ideas we've seen so far:
Expand transitionWhile()
Right now transitionWhile() takes a promise for nothing; the browser is only interested in how long the promise takes to settle, and whether it fulfills or rejects. We could expand it to take a promise for { url, state }, so that you'd write the above examples as
navigation.addEventListener("navigate", e => {
const url = new URL(e.destinationEntry.url);
if (url.hostname === "store.example.com") {
url.queryParams.set("affiliateId", "ead21623-781e-442f-a2c4-6cc1b2a9fda2");
e.transitionWhile({ url });
}
});navigation.addEventListener("navigate", e => {
if (!e.destination.state) {
// We probably got here via an <a> click or something.
const state = figureOutStateForURL(e.destination.url);
e.transitionWhile({ url: e.destination.url, state });
}
});This would also allow asynchronous calculation of the new URL and state, which I could imagine being useful.
Make destination mutable
This ties into larger questions about mutability (#7), so it could come in a few variants. But a simple version is to just have NavigationDestination's url and state properties be mutable. Then the above examples would become
navigation.addEventListener("navigate", e => {
const url = new URL(e.destination.url);
if (url.hostname === "store.example.com") {
url.queryParams.set("affiliateId", "ead21623-781e-442f-a2c4-6cc1b2a9fda2");
e.destination.url = url;
}
});navigation.addEventListener("navigate", e => {
if (!e.destination.state) {
// We probably got here via an <a> click or something.
const state = figureOutStateForURL(e.destination.url);
e.destination.setState(state);
}
});Introduce a new beforenavigate event where these things are mutable
Here the idea is to separate navigations into two phases: preparing for the navigation, where you might want to tweak the URL and state; and processing the navigation, where you don't want to change those but instead you simply want to act on it.
This could look a lot like "Make destination mutable", or maybe we'd put the url and state properties directly on the event object.
This has a lot of consequences though that'd need to be thought through. Like, does beforenavigate get the same information as navigate? And, we'd need to reevaluate each of our navigate examples to figure out whether they'd be better off using beforenavigate. I'm not sure there would always be a right answer, which would make this API hard to use.
A tricky thing to consider is what happens when such mutations change the "type" of the navigation. The affiliate links example takes a cross-document cross-origin navigation, and just produces a slightly-different cross-document cross-origin navigation. But, what about a case like this?
appHistory.addEventListener("navigate", e => {
e.destination.url = "https://some-other-origin.example.com/";
});
history.pushState(null, "", "/same-origin-page");Here we're starting with a same-origin same-document navigation. But the navigate handler wants to update it to a cross-origin navigation, and cross-origin navigations must be cross-document. (You can't have your Document object claiming to be someone else's origin!)
We could probably just throw in such cases, I suppose. You could always do a proper redirect in your navigate handler, i.e. canceling the current navigation and starting a new one via location.href, if you wanted this.
The reverse version:
navigate.addEventListener("navigate", e => {
e.destination.url = "/same-origin-page";
});
location.href = "https://some-other-origin.example.com/";does not have this problem; it transforms a cross-document cross-origin navigation into a cross-document same-origin navigation, which is fine. (It's just like link-rewriting.) But, we could also throw on that sort of thing for simplicity...
Activity
tbondwilkinson commentedon Feb 11, 2021
I do think that the destinationEntry that's passed into the navigate event should NOT be the same Entry that you would read from currentEntry because in some ways it's prospective - it hasn't yet been serialized to history, and specifically if you do:
this should be false - and I would expect it to be false.
So I like the approach of passing a separate instanceof Object in destinationEntry, and I like the idea of making it mutable. But I think that the promise you pass to respondWith should also be able to resolve to that entry, or should be the entry itself.
So in total:
domenic commentedon Feb 12, 2021
(Note: I recently renamed
e.destinationEntrytoe.destinationto cut down on verbosity.)Yep, that's already the plan. It's definitely a different object. The question is, whether it should be a different class. Right now
AppHistoryEntry'surlandstateproperties are semi-immutable; they can only be changed viaappHistory.update(), for the current entry only. If we want to make them mutable (so thate.destination.url = ...works), then it'd be a new class.Hmm, this seems like it's mixing two paradigms to me. If you're already doing
e.destination.url = ..., then the browser knows you mutated the URL; there's no need to tell it via the additionale.respondWith(Promise.resolve(modifiedEntry))(or, equivalently,e.respondWith(Promise.resolve(e.destination)).Similarly, if you need to do some async work to figure out the new URL, the mutable
e.destinationparadigm for that would be:tbondwilkinson commentedon Feb 17, 2021
It's just for me a question of the timing.
If we say, for instance:
Would you expect the URL to update on each new assignment to
e.destination.url? I think that's reasonable, actually, I just want to make sure we're intentional. Because otherwise, if we only want to let the URL change at the end when the Promise resolves, then I think having to explicitly resolve the intended entry makes it clearer that THAT'S the triggering action.domenic commentedon Feb 18, 2021
Great point. I don't like the look of that; causing many URL updates per navigation is tricky. So that inclines me more toward "expand respondWith". @annevk also was somewhat in favor of that alternative when we discussed offline.
I do want to figure out #19 first since that impacts exactly when the URL updates. I'll come back to this after we have a model there...
domenic commentedon Mar 5, 2021
After #56 gave us more clarity on when
respondWith()works, re-using that no longer makes sense. In particular we want to allow URL rewriting for cross-origin<a>clicks, but we don't allowrespondWith()for that case. We would end up with two very different meanings for the same function.Before we come up with a new solution, we need to clarify, in a similar style to #56, exactly when this kind of URL/state modification is allowed. Here's a first pass: it's allowed for
location.hrefset orhistory.pushState().This is very similar to when
navigateis cancelable. However,navigatecancelation is allowed forhistory.back()/appHistory.back()and friends, which I think we should not allow URL rewriting for, because it's too confusing what that means.With this on hand, here's a new menu of solutions:
A new event with mutable
e.destinationThis event fires only when the above conditions hold.
Note that making state mutable requires adding
setState()toe.destination. (We wouldn't add it toAppHistoryEntrygenerally.)A new event with an update() method
This event fires only when the above conditions hold. Better names welcome for
update().A new method and boolean in
navigateWe'd add
update()andcanUpdate(better names welcome).canUpdateis true in the above conditions, andupdate()throws when the above conditions don't hold. I think in most cases people wouldn't need to checkcanUpdate, but it seems important to have.If you called
update()after callingrespondWith(), it would throw. If you called it asynchronously, it would throw. (Also, I guesscanUpdatewould flip to false in such cases.)Mutable
e.destinationin navigateYou can pretty much figure out how this works by analogy. I think we'd still need
canUpdate, as the setters would throw in some cases.I like "A new event with an update() method" the best.
tbondwilkinson commentedon Mar 5, 2021
Also my favorite, except I think the name
updateis quite bad.modify?redirect?domenic commentedon Mar 5, 2021
Redirect would be so good but doesn't make sense for the state-change-only case IMO. Modify is not bad.
annevk commentedon Mar 9, 2021
One thing that will likely help in clarifying this is to have a clear description of the primitives you end up exposing here. I guess the distinction you are drawing above is between "normal" navigation and "history" navigation. And then there's a difference between that being same origin and cross origin (though this only matters for "normal" as "history" is by definition same-origin as far as this API is concerned?).
It seems to me that
respondWith()could still work (assuming that a delayed answer is acceptable) if you would also allow this kind of rewriting same-origin. And through getters (such ascanRespond) you indicate what kind of objectrepondWith()can work with for a given event.At least, from a high-level there's a set of primitive operations that you allow to be intercepted and responded to, but not all responses are acceptable everywhere. Perhaps these sets are completely non-overlapping and therefore two different APIs is better, but it's not clear that is the case?
domenic commentedon Mar 15, 2021
Still haven't processed all the comments and thoughts here yet, but some discussion with @csreis pointed out that the explainer's current solution of
e.preventDefault(); location.href = ...is extra-undesirable for other reasons. It loses important data like form submission data, same-siteness (forSec-Same-Site), and various other things browsers bundle with navigations.annevk commentedon Mar 16, 2021
Right, I would expect a similar API to the fetch event in service workers. You get a NavigationRequest and you can create a new one to respond with. And then there's various policies about what is acceptable to read from these and what you get to set when creating a new one, to match security expectations.
posva commentedon Feb 26, 2025
In SPA routers, it would be useful to write
stateandinfoin each navigation. Right now these properties are only writable if they exist but that's only if doingnavigation.navigate('...', { state: {}, info: {} }). Adding transitive info is particularly useful for users who want to access or augment the navigation cycle at different points. e.g. collecting fetching calls based on the pages we are navigating to without calling them and verifying authenticated access to a page (this can happen in parallel in the same pass), then in a different interception, call the fetches. This allows routers to let users use the Navigation API to customize the navigation, it makes it easy for routers to let their users customize thingsyoavweiss commentedon Aug 21, 2026
Note
🤖 This comment was written and posted by an AI agent (Claude, running in the Pi coding agent), acting on behalf of @yoavweiss while triaging this repository ahead of archiving it. Migration scope was agreed with @noamr. If this is wrong, please say so and it can be reopened.
Migrated upstream → whatwg/html#12810
This repository is being archived, so this issue has been re-filed in HTML with the discussion summarised, the original author credited, and the
topic: navigationlabel applied for triage. Please continue there; this thread stays readable but is now closed.Where this work lives now: the Navigation API is specified in HTML §7.2.6. Please file new issues at whatwg/html with the
topic: navigationlabel.