Skip to content
Draft
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
31 changes: 29 additions & 2 deletions docs/guide/pages-routing/actions-and-forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ Each named action has its own validator schema, which supplies types for its URL

## `action()` Helper

Use `action()` for a button or other mutation that does not need form state. It updates the page after a successful request:
Use `action()` for a button or other mutation that does not need form state. By default, it refreshes the page after a successful request:

```ts
import { action } from '@void/react'; // or "@void/vue", "@void/svelte", "@void/solid"
Expand All @@ -308,6 +308,33 @@ A successful call returns `{ ok: true, pageData }`. Expected errors, such as val

For `4xx` errors, `error.message` uses the [`HTTPException`](../../integrations/hono.md#utilities) message or the body of a plain-text response. Other response formats use a status summary, such as `Action failed with 404 Not Found`.

### Returning a result without refreshing

Wrap the entire action with `definePageAction(handler, { reload: false })` to return a value to `action()` and skip the loader. Put authorization in the action or in middleware.

```ts
// pages/imports.server.ts
import { defineHandler, definePageAction } from 'void';

export const actions = {
preview: definePageAction(
defineHandler(() => ({ validRows: 3 })),
{ reload: false },
),
};
```

```ts
import { action } from '@void/react'; // or "@void/vue", "@void/svelte", "@void/solid"

const reply = await action('/imports?preview');
if (reply.ok) console.log(reply.result?.validRows);
```

The result can be a serializable value such as a `Date`, or `undefined` for an acknowledgement. A result-only response leaves `pageData` undefined and preserves the current page, URL, history and scroll. React may show its configured navigation fallback while the request is pending.

This option applies to `action()` in the full Pages router. Forms and actions on older servers continue to refresh the page. To refresh after receiving a result, call `router.refresh()` once navigation has settled. Refreshing cancels a pending visit and can still serve a cached page from public ISR.

## Validation Errors

`withValidator()` and `ValidationError` populate `form.errors` automatically.
Expand Down Expand Up @@ -511,5 +538,5 @@ Pick the storage key on the server and allow only the file types you expect. See
| Primitive | Page update | Form state | Framework-specific |
| ---------------- | ----------- | -------------------------- | ------------------ |
| `useForm` | Yes | Yes (errors, dirty, reset) | Yes |
| `action()` | Yes | No | Yes |
| `action()` | By default | No | Yes |
| Native `fetch()` | No | No | No |
8 changes: 8 additions & 0 deletions packages/edge/src/headers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import type { HeaderRule } from '@void/deploy-core';
import {
hasProtectedPageActionContentType,
protectPageActionResultCache,
} from './pages-protocol.ts';
import { matchLiteralPattern } from './pattern.ts';

export type { HeaderRule } from '@void/deploy-core';
Expand Down Expand Up @@ -162,6 +166,9 @@ export function applyHeaderRules(
rawOriginClearSiteData === null ? null : sanitizeClearSiteData(rawOriginClearSiteData);
for (const [name, value] of matched) {
const lowerName = name.toLowerCase();
if (lowerName === 'content-type' && hasProtectedPageActionContentType(response)) {
continue;
}
if (isolateSharedDomainCookies && BLOCKED_HEADERS.has(lowerName)) {
continue;
}
Expand All @@ -179,5 +186,6 @@ export function applyHeaderRules(
newResponse.headers.set(name, value);
}

protectPageActionResultCache(newResponse.headers, response.headers);
return newResponse;
}
6 changes: 6 additions & 0 deletions packages/edge/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
export type { ProjectZeroTrustRouting } from './access.ts';
export {
buildHeaders,
hasProtectedPageActionContentType,
isPageActionResult,
isStaleBuild,
isStaleBuildReload,
PAGE_ACTION_RESULT_HEADER,
PAGE_ACTION_RESULT_TYPE,
PAGE_ACTION_VALIDATION_HEADER,
pagesPayloadFitsBuild,
PAGES_BUILD_HEADER,
PAGES_PROTOCOL_VERSION,
protectPageActionResultCache,
} from './pages-protocol.ts';
export { redirectToHttps } from './https.ts';
export {
Expand Down
30 changes: 30 additions & 0 deletions packages/edge/src/pages-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,36 @@ export const PAGES_PROTOCOL_VERSION = '2';
*/
export const PAGES_BUILD_HEADER = 'X-VoidPages-Build';

export const PAGE_ACTION_RESULT_HEADER = 'X-VoidPages-Action-Result';
export const PAGE_ACTION_RESULT_TYPE = 'application/vnd.void.action-result+json';
export const PAGE_ACTION_VALIDATION_HEADER = 'X-VoidPages-Action-Validation';

export function isPageActionResult(headers: Headers): boolean {
const type = headers.get('Content-Type')?.split(';', 1)[0]?.trim().toLowerCase();
return type === PAGE_ACTION_RESULT_TYPE;
}

export function hasProtectedPageActionContentType(response: Response): boolean {
const { headers, status } = response;
return (
isPageActionResult(headers) ||
(status === 422 &&
headers.get(PAGE_ACTION_VALIDATION_HEADER) === 'true' &&
headers.get('Content-Type') === 'application/json')
);
}

/** Header rules can replace the media type while the body still carries the result. */
export function protectPageActionResultCache(headers: Headers, original: Headers = headers): void {
if (!original.has(PAGE_ACTION_RESULT_HEADER) && !isPageActionResult(original)) {
return;
}
headers.set('Cache-Control', 'no-store');
headers.delete('CDN-Cache-Control');
headers.delete('Cloudflare-CDN-Cache-Control');
headers.delete('Surrogate-Control');
}

/**
* Whether a build id seen on the wire belongs to another deployment. A peer
* that sends no id (an older Void, or a parse of a partial response) is not
Expand Down
5 changes: 4 additions & 1 deletion packages/react/src/runtime/pages-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,10 @@ function App({
if (activePendingNavigationId === prepared.id) {
activePendingNavigationId = null;
}
// The browser is leaving or downloading a file: keep the current page.
// The response has no destination page. Keep the current page.
if (terminalResource === next) {
terminalResource = null;
}
dispatch({ type: 'abandon', resource: prepared, location: currentUrl() });
resolveVisit(undefined);
} else if (resolveOnData) {
Expand Down
111 changes: 111 additions & 0 deletions packages/react/test/unit/page-action-result.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// @vitest-environment happy-dom

import { act, createElement, useState } from 'react';
import { afterEach, expect, it, vi } from 'vite-plus/test';
import { pageActionTargetId } from '../../../void/src/pages/action-key.ts';
import { action } from '../../src/runtime/action.ts';
import { startReactPages } from '../../src/runtime/pages-client.ts';

declare module 'void/routes' {
interface PageActionMap {
'/react-preview': { body: Record<string, unknown>; result: string };
}
}

afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
document.body.replaceChildren();
});

it('keeps React state and error recovery on the current page after a result-only action', async () => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
history.replaceState(null, '', '/draft?view=edit#note');
const url = location.href;
document.body.innerHTML = '<div id="app" data-void-ssr="false"></div>';
const data = document.createElement('script');
data.id = '__VOID_PAGE_DATA__';
data.textContent = JSON.stringify({ component: 'home', props: {}, url: '/draft?view=edit' });
document.body.append(data);
const fetch = vi.fn(
async (target: string) =>
new Response('[{"result":1},"saved"]', {
headers: {
'Content-Type': 'application/vnd.void.action-result+json',
'X-VoidPages-Action-Result': pageActionTargetId(new URL(target, location.origin)),
},
}),
);
vi.stubGlobal('fetch', fetch);
function Home() {
const [draft, setDraft] = useState('initial');
const [broken, setBroken] = useState(false);
if (broken) {
throw new Error('Page render failed');
}
return createElement(
'main',
null,
createElement('button', { onClick: () => setDraft('local draft') }, draft),
createElement('button', { id: 'break-page', onClick: () => setBroken(true) }, 'Break page'),
);
}
await act(async () => {
await startReactPages({
components: { home: async () => ({ default: Home }) },
boundaryManifest: {
plans: {
'root-not-found': {
id: 'root-not-found',
componentId: '_not-found',
filePath: '_not-found.tsx',
directory: '',
kind: 'not-found',
source: 'root-not-found',
layouts: [],
},
},
pages: {},
root: 'root-not-found',
},
layoutTree: {},
routeMeta: {},
matchRoute: () => 'home',
prefetchHoverDelay: 0,
prefetchDefaultCacheFor: { stale: 0, expires: 0 },
viewTransitions: false,
staticPageData: false,
staticPageDataFastPath: false,
});
});
const button = document.querySelector('button');
act(() => button?.click());
const push = vi.spyOn(history, 'pushState');
const replace = vi.spyOn(history, 'replaceState');
const scroll = vi.spyOn(window, 'scrollTo');
await act(async () => {
expect(await action('/react-preview')).toEqual({
ok: true,
pageData: undefined,
result: 'saved',
});
});
expect(document.querySelector('button')).toBe(button);
expect(button?.textContent).toBe('local draft');
expect(location.href).toBe(url);
expect(push).not.toHaveBeenCalled();
expect(replace).not.toHaveBeenCalled();
expect(scroll).not.toHaveBeenCalled();
expect(fetch).toHaveBeenCalledOnce();

// React's act() rethrows render failures instead of calling the root's error handler.
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', false);
document.querySelector<HTMLButtonElement>('#break-page')?.click();
await vi.waitFor(() => {
expect(document.querySelector('main a')?.textContent).toBe('Try again');
});
expect({
address: location.href,
retry: document.querySelector('main a')?.getAttribute('href'),
}).toEqual({ address: url, retry: url });
});
19 changes: 19 additions & 0 deletions packages/void/src/codegen/route-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ export function generateRouteTypes(
' V[K] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<V[K]> : never;',
'};',
'',
'type PageActionValueOf<H> = H extends { __pageActionResult: true; __output: infer R } ? R : undefined;',
'',
'type ExtractOutput<S> =',
' S extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<S> : never;',
'',
Expand Down Expand Up @@ -453,6 +455,21 @@ export function generateRouteTypes(
' : PageNamedActionBody<PageActionMap[ParseActionUrl<U>["base"]], ParseActionUrl<U>["action"]>',
' : Record<string, unknown>;',
'',
' type PageActionValue<A> = A extends { result: infer R } ? R : undefined;',
'',
// Single actions ignore the selector. Named actions use "default" when it is absent.
' type PageActionValueFor<P, K> = P extends { body: unknown }',
' ? PageActionValue<P>',
' : P extends { actions: infer A }',
' ? PageActionValue<A[Extract<[K] extends [""] ? "default" : K, keyof A>]>',
' : never;',
'',
' export type ResolveActionResult<U extends string> = U extends unknown',
" ? ParseActionUrl<U>['base'] extends keyof PageActionMap",
" ? PageActionValueFor<PageActionMap[ParseActionUrl<U>['base']], ParseActionUrl<U>['action']>",
' : undefined',
' : never;',
'',
' export type ResolveActionParams<U extends string> =',
' ParseActionUrl<U>["base"] extends keyof PageActionMap',
' ? PageActionMap[ParseActionUrl<U>["base"]] extends { params: infer P }',
Expand Down Expand Up @@ -584,12 +601,14 @@ export function generateRouteTypes(
body.push(
` actions: { [K in keyof ${actionsImport}]: {`,
` body: ExtractInput<${actionsImport}[K]["__validators"]> extends { body: infer B } ? B : Record<string, unknown>;`,
` result: PageActionValueOf<${actionsImport}[K]>;`,
' } };',
);
} else {
const importExpr = `(typeof import(${JSON.stringify(importPath)}))["action"]`;
body.push(
` body: ExtractInput<${importExpr}["__validators"]> extends { body: infer B } ? B : Record<string, unknown>;`,
` result: PageActionValueOf<${importExpr}>;`,
);
}

Expand Down
1 change: 1 addition & 0 deletions packages/void/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1252,6 +1252,7 @@ export function voidPlugin(options?: {
// Re-export runtime types and functions
export {
defineHandler,
definePageAction,
defineMiddleware,
basicAuth,
defineScheduled,
Expand Down
15 changes: 15 additions & 0 deletions packages/void/src/pages/action-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ export function searchWithoutActionKey(search: string): string {
*/
export const PRESERVED_QUERY_HEADER = 'X-VoidPages-Preserved-Query';

/** A fixed-size FNV-1a identity check for the concrete action target, not a security boundary. */
export function pageActionTargetId(url: URL): string {
const target = url.pathname + url.search;
let high = 0xcb_f2_9c_e4;
let low = 0x84_22_23_25;
for (let index = 0; index < target.length; index++) {
low = (low ^ target.charCodeAt(index)) >>> 0;
// Multiply by the FNV prime (2^40 + 435), carrying from the low word.
const lowProduct = low * 435;
high = (Math.imul(high, 435) + (low << 8) + Math.floor(lowProduct / 2 ** 32)) >>> 0;
low = lowProduct >>> 0;
}
return high.toString(16).padStart(8, '0') + low.toString(16).padStart(8, '0');
}

export function queryKey(segment: string): string | undefined {
return new URLSearchParams(segment).keys().next().value;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/void/src/pages/action-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import type { PageObject } from './protocol.ts';

export type ActionErrorHandlingScope = 'callSite' | 'boundary';

export type ActionResult<T = PageObject | undefined> =
| { ok: true; pageData: T }
export type ActionResult<T = PageObject | undefined, TResult = undefined> =
| { ok: true; pageData: T; result?: TResult }
| { ok: false; error: VoidActionError };

export class VoidActionError extends Error {
Expand Down
19 changes: 15 additions & 4 deletions packages/void/src/pages/client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
/// <reference lib="dom" />

import type { ActionUrl, ResolveActionBody, ResolveActionParams, RouteUrlInput } from 'void/routes';
import type {
ActionUrl,
ResolveActionBody,
ResolveActionParams,
ResolveActionResult,
RouteUrlInput,
} from 'void/routes';
import { toUrlString } from '../runtime/routing/route-url.ts';
import { interpolateRouteParams } from '../runtime/routing/route-url.ts';
import { withPageQuery } from './action-key.ts';
Expand Down Expand Up @@ -392,7 +398,7 @@ export type ActionClient = {
this: void,
url: U,
...args: HasParams<U> extends true ? [options: ActionOptions<U>] : [options?: ActionOptions<U>]
): Promise<ActionResult>;
): Promise<ActionResult<PageData | undefined, ResolveActionResult<U>>>;
};

/** Creates an action client with its own router for each framework adapter. */
Expand All @@ -410,7 +416,7 @@ export function createActionClient(
async function action<U extends ActionUrl & string>(
url: U,
...args: HasParams<U> extends true ? [options: ActionOptions<U>] : [options?: ActionOptions<U>]
): Promise<ActionResult> {
): Promise<ActionResult<PageData | undefined, ResolveActionResult<U>>> {
if (!_router) {
throw new Error('action(): called before router initialization.');
}
Expand All @@ -423,12 +429,17 @@ export function createActionClient(
url,
options?.params as Record<string, string> | undefined,
);
return submitAction(_router, resolvedUrl, {
let published: { result: ResolveActionResult<U> } | undefined;
const reply = await submitAction(_router, resolvedUrl, {
method,
data,
preserveScroll: options?.preserveScroll,
...defaults,
_onActionResult: (result) => {
published = { result: result as ResolveActionResult<U> };
},
});
return reply.ok && published ? { ...reply, ...published } : reply;
}

return { action, setActionRouter };
Expand Down
Loading