Skip to content

Commit bf20661

Browse files
fix(pages): report the requested URL in page data after a rewrite (#799)
Closes #798 ## Problem A rewrite (`c.rewrite()`, `routing.rewrites`, `routing.fallbacks`, `_redirects` `200`) serves another route without changing the browser URL. But the page data's `url` was built from the rewritten request, so the client router took the destination as the current URL. After a rewrite, `useRouter().url`, `.path` and `.query` described the destination, `router.refresh()` loaded the destination, and active-link matching treated the visitor as being on it. ## Change `requestPathWithSearch()` in `packages/void/src/pages/protocol.ts` now builds the URL from `c.originalUrl()` when the request was rewritten: - The path goes through `decodePagePath()`, so it is decoded the same way `c.req.path` is (`/caf%C3%A9` → `/café`). Requests that were not rewritten get the same URL as before. - The action re-render branch uses the same helper and still leaves out the action key. - Build-time renders (`createStaticNotFound`) run without the routing context middleware, so the helper falls back to the served request when `c.originalUrl` is absent. The client already keeps the requested URL in history after a mutation rewrite (3c53034). One assertion in `pages-client.test.ts` checked that the server sent the destination URL; it now expects the visible URL. ## Tests - New `routing-runtime.test.ts` cases cover middleware and rule rewrites for GET page loads, an encoded path, and named-action re-renders. All five fail without the fix (`/maintenance?tab=1` instead of `/app/account?tab=1`). - `vp run check`, `vp lint` and `vp fmt --check` pass. - `vp test run`: 792 test files passed, 1 skipped. No docs change: the rewrites reference already says the browser URL does not change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent bf08a6e commit bf20661

3 files changed

Lines changed: 64 additions & 6 deletions

File tree

‎packages/void/src/pages/protocol.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { withLoaderNotFoundBoundary } from './not-found-context.ts';
1717
import { escapeScriptJson } from './script-json.ts';
1818
import { serializePageData } from './serialize.ts';
1919
import type { DevCssAsset, PageRenderMode } from './types.ts';
20+
import { decodePagePath } from './url.ts';
2021
import { ValidationError } from './validation-error.ts';
2122

2223
export { ValidationError };
@@ -299,8 +300,25 @@ function pageJsonResponse(c: CloudContext, pageObj: PageObject): Response {
299300
});
300301
}
301302

302-
function requestPathWithSearch(c: CloudContext): string {
303-
return c.req.path + new URL(c.req.url).search;
303+
/**
304+
* The URL in the address bar, which a rewrite keeps while it serves another
305+
* route. The path is decoded like c.req.path.
306+
*/
307+
function requestPathWithSearch(c: CloudContext, withoutActionKey = false): string {
308+
// Build-time renders run without the routing middleware that adds originalUrl.
309+
const original = c.originalUrl?.();
310+
const requestSearch = new URL(c.req.url).search;
311+
if (!original) {
312+
return c.req.path + (withoutActionKey ? searchWithoutActionKey(requestSearch) : requestSearch);
313+
}
314+
// The action key is in the query this request carries. It is also in the
315+
// original query only when the rewrite kept that query; a destination with
316+
// its own query leaves the original's parameters as they were.
317+
const search =
318+
withoutActionKey && original.search === requestSearch
319+
? searchWithoutActionKey(original.search)
320+
: original.search;
321+
return decodePagePath(original.pathname) + search;
304322
}
305323

306324
function requestParams(c: CloudContext): Record<string, string> {
@@ -908,9 +926,7 @@ async function runPageMutation(
908926
props,
909927
params: requestParams(c),
910928
shared,
911-
url: hasActionKey(c.req.raw)
912-
? c.req.path + searchWithoutActionKey(new URL(c.req.url).search)
913-
: requestPathWithSearch(c),
929+
url: requestPathWithSearch(c, hasActionKey(c.req.raw)),
914930
errors,
915931
...(head && { head }),
916932
};

‎packages/void/test/unit/pages-client.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1439,7 +1439,7 @@ describe('createVoidRouter', () => {
14391439
const response = await app.fetch(new Request(new URL(url, window.location.origin), init));
14401440
expect(response.status).toBe(200);
14411441
expect(decodePageData(await response.clone().json())).toMatchObject({
1442-
url: '/books?category=internal',
1442+
url: '/books?category=public',
14431443
});
14441444
return response;
14451445
}),

‎packages/void/test/unit/routing-runtime.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1166,6 +1166,48 @@ describe('typed Pages and SSR execution', () => {
11661166
expect((decodePageData(await response.json()) as { url: string }).url).toBe('/named?page=2');
11671167
});
11681168
});
1169+
it.each([
1170+
['middleware', 'GET', '/app/account?tab=1', '/maintenance', '/app/account?tab=1'],
1171+
['rule', 'GET', '/app/account?tab=1', '/maintenance', '/app/account?tab=1'],
1172+
['middleware', 'GET', '/app/caf%C3%A9', '/maintenance', '/app/café'],
1173+
['middleware', 'GET', '/app/account?tab=1', '/maintenance?mode=read', '/app/account?tab=1'],
1174+
['middleware', 'POST', '/app/account?save&tab=1', '/maintenance', '/app/account?tab=1'],
1175+
['rule', 'POST', '/app/account?save&tab=1', '/maintenance', '/app/account?tab=1'],
1176+
// The destination's query selects the action; the original query has no key.
1177+
['middleware', 'POST', '/app/account?tab=1', '/maintenance?save&tab=1', '/app/account?tab=1'],
1178+
['rule', 'POST', '/app/account?tab=1', '/maintenance?save&tab=1', '/app/account?tab=1'],
1179+
])(
1180+
'reports the requested URL after a %s rewrite of %s %s to %s',
1181+
async (kind, method, path, destination, url) => {
1182+
const app = new Hono();
1183+
const runtime = createRoutingRuntime(app, { nodeTarget: true });
1184+
app.use(runtime.contextMiddleware);
1185+
app.use(createNamedActionMarker(matchedRoutes));
1186+
if (kind === 'middleware') {
1187+
app.use('/app/*', (c) => (c as RoutingContext).rewrite(destination));
1188+
} else {
1189+
app.use(
1190+
runtime.routingMiddleware([{ source: '/app/*', destination, status: 200, force: true }]),
1191+
);
1192+
}
1193+
app.get('/maintenance', createPageGetHandler(pageOptions));
1194+
app.post(
1195+
'/maintenance',
1196+
createPageMutationHandler({
1197+
...pageOptions,
1198+
load: async () => ({ actions: { save: () => undefined } }),
1199+
namedActions: true,
1200+
}),
1201+
);
1202+
const response = await app.fetch(
1203+
new Request('https://app.test' + path, {
1204+
method,
1205+
headers: { 'x-voidpages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION },
1206+
}),
1207+
);
1208+
expect((decodePageData(await response.json()) as { url: string }).url).toBe(url);
1209+
},
1210+
);
11691211
it('executes the real page loader and protocol', async () => {
11701212
const app = new Hono();
11711213
app.get(

0 commit comments

Comments
 (0)