Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/guide/pages-routing/actions-and-forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,12 @@ If a callback awaits `router.visit()` or `router.refresh()`, pass `{ resolveOn:

Vue, Svelte, and Solid submissions return a promise instead; use `await form.post()` to run work after a submission.

### Query parameters after submission

An action or form that posts to the current page keeps the page's query parameters. From `/items?page=2&search=foo`, `action('/items?vote')` posts to `/items?vote&page=2&search=foo`, so the action and loader see `page` and `search`. The URL, scroll position, and history entry stay as they are. A parameter written in the action URL takes precedence over the page's: `action('/items?vote&page=1')` posts with `page=1`.

A redirect from the action does not receive the page's query parameters. To clear them after an action, return `c.redirect('/items')`.

### Scroll after submission

Actions and forms keep the current scroll position when updating the page in place. Redirects and submissions that open another page scroll to the top, or to the destination's hash target.
Expand Down Expand Up @@ -248,7 +254,7 @@ export const actions = {
};
```

Named actions use a `?actionName` suffix, such as `/users/42?update`. `useForm` and `action()` handle this automatically. After a POST action renders the page or uses a default `c.redirect()`, the page URL keeps ordinary query parameters: `/users/42?update&tab=profile` becomes `/users/42?tab=profile`. See [redirect query parameters](../../reference/api/rewrites.md#c-rewrite-destination) for redirects that preserve the request method.
Named actions use a `?actionName` suffix, such as `/users/42?update`. `useForm` and `action()` handle this automatically. After a POST action renders the page or uses a default `c.redirect()`, the page URL keeps the action URL's ordinary query parameters: `/users/42?update&tab=profile` becomes `/users/42?tab=profile`. See [redirect query parameters](../../reference/api/rewrites.md#c-rewrite-destination) for redirects that preserve the request method.

Use `action` or `actions` in a file, not both.

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/api/rewrites.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ return c.redirect(requested.origin === new URL(c.req.url).origin ? requested : '

`c.redirect()` sends the location it is given. The request query is not added to an internal path, a protocol-relative URL, or an absolute URL, so `c.redirect('/notes')` from `/sign-in?redirectTo=/notes` goes to `/notes`. [`routing.redirects`](../../guide/edge/redirects.md) still merge the request query into the destination.

A [named action](../../guide/pages-routing/actions-and-forms.md#named-actions) is the exception. Redirecting it to a GET page drops the action key and keeps the page's other query parameters: `POST /users/42?delete&tab=profile` with `c.redirect('/users/42')` goes to `/users/42?tab=profile`. Redirects that preserve the request method keep the action key: `307` and `308`, or `301` and `302` after a `PUT`, `PATCH`, or `DELETE`.
A [named action](../../guide/pages-routing/actions-and-forms.md#named-actions) is the exception. Redirecting it to a GET page drops the action key and keeps the page's other query parameters: `POST /users/42?delete&tab=profile` with `c.redirect('/users/42')` goes to `/users/42?tab=profile`. Redirects that preserve the request method keep the action key: `307` and `308`, or `301` and `302` after a `PUT`, `PATCH`, or `DELETE`. Only the action URL's own parameters are kept: the [current page's query](../../guide/pages-routing/actions-and-forms.md#query-parameters-after-submission) that `action()` and forms add is left out.

```ts
import { defineHandler } from 'void';
Expand Down
6 changes: 5 additions & 1 deletion packages/solid/test/unit/form-submissions.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createComponent, createRoot } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vite-plus/test';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test';
import type { VoidRouter } from 'void/pages-client';
import { RouterContext } from '../../src/runtime/context.ts';
import { useForm as typedUseForm } from '../../src/runtime/use-form.ts';
Expand Down Expand Up @@ -53,6 +53,10 @@ function validationResponse(errors: Record<string, string>): Response {

const disposers: Array<() => void> = [];

beforeEach(() => {
vi.stubGlobal('window', { location: { pathname: '/', search: '' } });
});

afterEach(() => {
vi.unstubAllGlobals();
for (const dispose of disposers.splice(0)) {
Expand Down
10 changes: 9 additions & 1 deletion packages/solid/test/unit/use-form.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { createComponent, createRoot } from 'solid-js';
import { describe, expect, it } from 'vite-plus/test';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test';
import type { VoidRouter } from 'void/pages-client';
import { RouterContext } from '../../src/runtime/context.ts';
import { useForm as typedUseForm } from '../../src/runtime/use-form.ts';

beforeEach(() => {
vi.stubGlobal('window', { location: { pathname: '/', search: '' } });
});

afterEach(() => {
vi.unstubAllGlobals();
});

// The public overload only accepts generated action URLs; these tests use plain paths.
const useForm = typedUseForm as unknown as (
url: string,
Expand Down
2 changes: 2 additions & 0 deletions packages/void/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Pages navigation payloads keep `url` as a path and query string. The render call

Pages clients and prerender requests send `X-VoidPages: true` with `X-VoidPages-Version` set to the shared `PAGES_PROTOCOL_VERSION` from `@void/edge` for devalue payloads. Missing or unsupported versions receive an uncached, empty `200 text/plain` response without `X-VoidPages`, which makes released clients load the document. Run legacy mutations once before that response; return validation errors as plain `422` JSON so forms retain their input. Native and hosted ISR must bypass JSON cache reads for unsupported versions without evicting current entries. HTML and JSON responses vary by both headers.

`submitAction()` appends the current page query to an action URL on the same path and names the added segments in `X-VoidPages-Preserved-Query`. Named-action `c.redirect()` strips that suffix before merging the request query, so the preserved query only feeds the in-place render. Keep the segments verbatim: history and scroll preservation compare the returned page URL with `location.pathname + location.search` as strings.

Pages `_not-found`/`_error` recovery uses finite render plans that retain logical layout slots. Never serialize original exceptions through framework hydration helpers, rerun a failed loader/action, or cache an error document. Native client boundaries reset on every visit/refresh and preserve healthy ancestor layouts.

**Hono** is used as the runtime framework. The generated virtual module creates a Hono app with file-based routes and middleware. Route handlers receive a Hono `Context` object (`c`) and can use the full Hono API (`c.json()`, `c.text()`, `c.req.param()`, etc.) plus the Hono middleware ecosystem.
Expand Down
52 changes: 52 additions & 0 deletions packages/void/src/pages/action-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,55 @@ export function searchWithoutActionKey(search: string): string {
}
return rest < search.length ? '?' + search.slice(rest) : '';
}

/**
* Names the page query that an action request carries only because it posts
* to the page it runs on. Redirects leave that query out.
*/
export const PRESERVED_QUERY_HEADER = 'X-VoidPages-Preserved-Query';

export function queryKey(segment: string): string | undefined {
return new URLSearchParams(segment).keys().next().value;
}

/**
* For an action URL on the page's own path, `url` with the page's query
* parameters after its own. A key the action URL names wins over the page's.
* `preserved` is the query that was added, as sent.
*/
export function withPageQuery(
url: string,
page: { pathname: string; search: string },
): { url: string; preserved: string } {
const hashIndex = url.indexOf('#');
const base = hashIndex === -1 ? url : url.slice(0, hashIndex);
const q = base.indexOf('?');
if (!page.search || base.slice(0, q === -1 ? base.length : q) !== page.pathname) {
return { url, preserved: '' };
}
const own = new Set(new URLSearchParams(q === -1 ? '' : base.slice(q + 1)).keys());
const preserved = page.search
.slice(1)
.split('&')
.filter((segment) => segment !== '' && !own.has(queryKey(segment)!))
.join('&');
if (!preserved) {
return { url, preserved };
}
const query = q === -1 || q === base.length - 1 ? '?' : base.slice(q) + '&';
return {
url: base.slice(0, q === -1 ? base.length : q) + query + preserved + url.slice(base.length),
preserved,
};
}

/** `search` without the page query that `withPageQuery()` added to its end. */
export function searchWithoutPreservedQuery(search: string, preserved: string | null): string {
if (!preserved) {
return search;
}
if (search === '?' + preserved) {
return '';
}
return search.endsWith('&' + preserved) ? search.slice(0, -preserved.length - 1) : search;
}
8 changes: 8 additions & 0 deletions packages/void/src/pages/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import type { ActionUrl, ResolveActionBody, ResolveActionParams, RouteUrlInput } from 'void/routes';
import { toUrlString } from '../runtime/route-url.ts';
import { interpolateRouteParams } from '../runtime/route-url.ts';
import { withPageQuery } from './action-key.ts';
import {
VoidActionError,
isAbortError,
Expand Down Expand Up @@ -286,6 +287,13 @@ export async function submitAction(
options: VisitOptions,
errorOptions?: { throwOnError?: boolean },
): Promise<ActionResult> {
// An action on the page it runs on re-renders that page, so its loader sees the
// page query and the URL, scroll and history entry stay as they are.
const page = withPageQuery(url, window.location);
if (page.preserved) {
url = page.url;
options = { ...options, _preservedQuery: page.preserved };
}
try {
const pageData = await router.visit(url, options);
if (
Expand Down
7 changes: 6 additions & 1 deletion packages/void/src/pages/navigation-engine.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// <reference lib="dom" />

import { PAGES_PROTOCOL_VERSION } from '@void/edge';
import { searchWithoutActionKey } from './action-key.ts';
import { PRESERVED_QUERY_HEADER, searchWithoutActionKey } from './action-key.ts';
import { createActionErrorFromResponse, isAbortError } from './action-result.ts';
import { pageBoundarySlots, clientPageError, showTerminalPageError } from './boundary-client.ts';
import type { BoundaryManifest } from './boundary-plans.ts';
Expand Down Expand Up @@ -66,6 +66,8 @@ export type VisitOptions = {
_popstate?: boolean;
/** @internal Used by router.refresh() to refetch the current URL even when it has a hash */
_refresh?: boolean;
/** @internal Used by actions: the page query they added to the URL, which redirects leave out */
_preservedQuery?: string;
};

export type PrefetchOptions = {
Expand Down Expand Up @@ -712,6 +714,9 @@ export async function createPageNavigationEngine(
'X-VoidPages-Version': PAGES_PROTOCOL_VERSION,
Accept: 'application/json',
};
if (options._preservedQuery && method !== 'GET') {
headers[PRESERVED_QUERY_HEADER] = options._preservedQuery;
}
const fetchOptions: PageFetchOptions = { method, headers, signal };

if (options.data && method !== 'GET') {
Expand Down
13 changes: 8 additions & 5 deletions packages/void/src/runtime/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ import type { TypedResponse } from 'hono';
import type { RedirectStatusCode } from 'hono/utils/http-status';
import type { RouteDestination, RouteUrlInput } from 'void/routes';
import {
PRESERVED_QUERY_HEADER,
actionKeySegment,
hasActionKey,
markActionKey,
queryKey,
searchWithoutActionKey,
searchWithoutPreservedQuery,
} from '../pages/action-key.ts';
import { SHARED_CACHE_HEADERS, authDependentRequests } from './auth-response.ts';
import { VoidAssetRewriteError, type CloudContext } from './handler.ts';
Expand Down Expand Up @@ -325,7 +328,11 @@ function redirectLocation(
status: RedirectStatusCode | undefined,
): string {
const url = new URL(request.url);
const search = url.search;
// The page query that action() added only re-renders the page in place.
const search = searchWithoutPreservedQuery(
url.search,
request.headers.get(PRESERVED_QUERY_HEADER),
);
if (!hasActionKey(request)) {
return mergeQueryIntoLocation(location, search);
}
Expand Down Expand Up @@ -377,10 +384,6 @@ function redirectLocation(
);
}

function queryKey(segment: string): string | undefined {
return new URLSearchParams(segment).keys().next().value;
}

/** A rewrite that keeps the query keeps the action key in it too. */
function keepActionKey(from: Request, to: Request, destinationSearch: string): void {
if (!destinationSearch && hasActionKey(from)) {
Expand Down
67 changes: 66 additions & 1 deletion packages/void/test/unit/action-result.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HTTPException } from 'hono/http-exception';
import { describe, expect, it, vi } from 'vite-plus/test';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test';
import { createActionErrorFromResponse } from '../../src/pages/action-result.ts';
import {
VoidActionError,
Expand Down Expand Up @@ -46,6 +46,13 @@ function routerWithVisit(visit: VoidRouter['visit']): VoidRouter {
};
}

function stubLocation(pathname: string, search = '') {
vi.stubGlobal('window', { location: { pathname, search } });
}

beforeEach(() => stubLocation('/'));
afterEach(() => vi.unstubAllGlobals());

describe('action result handling', () => {
it('categorizes expected client errors as call-site errors', () => {
expect(categorizeActionError(400)).toBe('callSite');
Expand Down Expand Up @@ -316,6 +323,64 @@ describe('action clients', () => {
});
});

describe('the page query', () => {
it.each([
['/items?vote', '/items?vote&page=2&search=foo', 'page=2&search=foo'],
['/items', '/items?page=2&search=foo', 'page=2&search=foo'],
['/items?', '/items?page=2&search=foo', 'page=2&search=foo'],
['/items?vote&page=3', '/items?vote&page=3&search=foo', 'search=foo'],
['/items?vote&page=3&search=bar', '/items?vote&page=3&search=bar', undefined],
['/items?vote#row-1', '/items?vote&page=2&search=foo#row-1', 'page=2&search=foo'],
['/items/1?vote', '/items/1?vote', undefined],
['/other?vote', '/other?vote', undefined],
])('posts %s from /items?page=2&search=foo to %s', async (url, requested, preserved) => {
stubLocation('/items', '?page=2&search=foo');
const visit = vi.fn(async () => ({ props: {} }));

await submitAction(routerWithVisit(visit), url, { method: 'POST' });

expect(visit).toHaveBeenCalledWith(requested, {
method: 'POST',
...(preserved === undefined ? {} : { _preservedQuery: preserved }),
});
});

it('keeps encoded parameters as the page sent them', async () => {
stubLocation('/items', '?q=a+b%26c&&tag=x%20y');
const visit = vi.fn(async () => ({ props: {} }));

await submitAction(routerWithVisit(visit), '/items?vote&tag=z', { method: 'POST' });

expect(visit).toHaveBeenCalledWith('/items?vote&tag=z&q=a+b%26c', {
method: 'POST',
_preservedQuery: 'q=a+b%26c',
});
});

it('leaves the URL alone on a page without a query', async () => {
stubLocation('/items');
const visit = vi.fn(async () => ({ props: {} }));

await submitAction(routerWithVisit(visit), '/items?vote', { method: 'POST' });

expect(visit).toHaveBeenCalledWith('/items?vote', { method: 'POST' });
});

it('adds the page query to an action() call on the current page', async () => {
stubLocation('/__action-test/users/a%2Fb', '?tab=profile');
const client = createActionClient();
const visit = vi.fn(async () => ({ props: {} }));
client.setActionRouter(routerWithVisit(visit));

await client.action('/__action-test/users/:id?save', { params: { id: 'a/b' } });

expect(visit).toHaveBeenCalledWith(
'/__action-test/users/a%2Fb?save&tab=profile',
expect.objectContaining({ _preservedQuery: 'tab=profile' }),
);
});
});

it('exposes the application message and retry deadline for structured quota responses', () => {
const error = new VoidActionError({
status: 429,
Expand Down
28 changes: 28 additions & 0 deletions packages/void/test/unit/pages-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,34 @@ describe('createVoidRouter', () => {
},
);

it('keeps the page query, scroll and history entry for an in-place action', async () => {
stubClientGlobals();
window.location.pathname = '/editor';
window.location.search = '?page=2&search=foo';
window.scrollY = 1800;
const fetch = vi.fn(async () =>
pageJson({ component: 'home', props: {}, url: '/editor?page=2&search=foo', errors: null }),
);
vi.stubGlobal('fetch', fetch);
const { router } = await createTestRouter();

await submitAction(router, '/editor?save', { method: 'POST' });

expect(fetch).toHaveBeenCalledWith(
'/editor?save&page=2&search=foo',
expect.objectContaining({
headers: expect.objectContaining({ 'X-VoidPages-Preserved-Query': 'page=2&search=foo' }),
}),
);
expect(window.scrollTo).not.toHaveBeenCalled();
expect(history.pushState).not.toHaveBeenCalled();
expect(history.replaceState).toHaveBeenCalledWith(
expect.anything(),
'',
'/editor?page=2&search=foo',
);
});

it.each([
['/editor', false, undefined],
['/destination', false, undefined],
Expand Down
38 changes: 38 additions & 0 deletions packages/void/test/unit/routing-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,44 @@ describe('typed Pages and SSR execution', () => {
expect(response.headers.get('location')).toBe(location);
});

it.each([
['/named?delete&page=2', 'page=2', 'a redirect', '/named'],
['/named?update&tab=a&page=2&q=x', 'page=2&q=x', 'a 303 redirect', '/named?tab=a'],
['/named?move&page=2', 'page=2', 'a 307 redirect', '/named-v2?move'],
['/named?moveTab&page=2', 'page=2', 'a 307 redirect', '/named-v2?moveTab&tab=details'],
['/named?delete&page=2', 'page=2', 'middleware', '/login'],
['/named?go&page=2', 'page=2', 'a rewrite', '/done'],
['/named?delete&page=2', 'page=3', 'a redirect', '/named?page=2'],
])(
'POST %s that preserves %s through %s redirects to %s',
async (path, preserved, through, location) => {
const response = await createNamedActionApp().fetch(
new Request('https://app.test' + path, {
method: path.includes('update') ? 'PUT' : 'POST',
headers: {
'X-VoidPages-Preserved-Query': preserved,
...(through === 'middleware' ? { 'x-anon': '1' } : {}),
},
}),
);
expect(response.headers.get('location')).toBe(location);
},
);

it('keeps the preserved query in the page URL when the action renders the page again', async () => {
const response = await createNamedActionApp().fetch(
new Request('https://app.test/named?save&page=2', {
method: 'POST',
headers: {
'x-voidpages': 'true',
'X-VoidPages-Version': PAGES_PROTOCOL_VERSION,
'X-VoidPages-Preserved-Query': 'page=2',
},
}),
);
expect((decodePageData(await response.json()) as { url: string }).url).toBe('/named?page=2');
});

it('marks the request for a one-argument middleware that answers first', async () => {
const app = new Hono();
const runtime = createRoutingRuntime(app, { nodeTarget: true });
Expand Down
Loading