API Routes and Typed Requests

Generate an authenticated JSON endpoint, validate inputs, call it with typed fetch, and understand page-action versus API behavior.

Use an API route for JSON consumed by the browser or another client, webhooks, and uploads. Use a page action for a form tied to a page.

1. Generate an Endpoint

pnpm kit:generate route account-summary --methods get

This creates apps/web/routes/api/account-summary.ts, served at /api/account-summary, with a session check. The generator accepts get, post, put, patch, and delete; add only the methods you intend to support.

2. Return the Current User's Data

Reuse findAccountSummary from Fetching Data:

import { HTTPException } from 'hono/http-exception';
import { defineHandler } from 'void';
import { findAccountSummary } from '#/lib/account-summary.service.ts';
import { requireSession } from '#/lib/session.server.ts';
export const GET = defineHandler(async (c) => {
const { user } = requireSession({ c });
const profile = await findAccountSummary({ userId: user.id });
if (!profile) throw new HTTPException(404);
c.header('Cache-Control', 'private, no-store');
return c.json({ profile });
});

A signed-out request gets 401. A signed-in user receives only their own selected profile fields. The handler returns JSON rather than page props, so a Date in the response is a serialized string.

3. Call It from the Browser

import { fetch, FetchError } from 'void/client';
try {
const { profile } = await fetch('/api/account-summary');
// Use profile in the interaction or cache that requested it.
} catch (error) {
if (error instanceof FetchError && error.status === 401) {
// Show your translated sign-in-required state.
} else {
throw error;
}
}

Typed fetch returns the parsed data directly, not a native Response. Route paths, supported methods, validator inputs, and response types come from the generated app types. Do not call response.json() on its result.

For a dynamic route generated as account-summary/[id], pass params: { id } alongside the bracket path. A URL id identifies a resource; the server still checks ownership. Do not expose arbitrary account profiles by replacing the session-derived user id with a route parameter.

Request Validation

Use the same defineHandler.withValidator({ body, query, params }) API as page actions. Put reusable schemas in *.schema.ts. Typed client requests help during development, but external callers can send any payload, so the server validator remains required.

For a POST handler, authenticate inside POST even if GET in the same file already does. Call a named service for the mutation, return the minimal response, and keep GET read-only. A successful API mutation does not automatically rerun a page's loader or invalidate TanStack Query; refresh the relevant client state explicitly.

Origins, Webhooks and Caching

The kit's middleware/04.api-origin.ts checks unsafe /api requests. A normal browser request must satisfy the same-origin policy. Being signed in is not a substitute for that check. See CSRF Protection.

Webhooks require their provider's signature verification and a deliberate security configuration; do not add a broad origin exception to make a failing integration work. The existing Stripe flow should remain on the kit's billing setup and webhook handler.

Private responses must not be shared or cached publicly. A public generated route is for genuinely public data, not a shortcut around a session or ownership check.

Where Route Tests Live

Put route tests in apps/web/tests/routes/. Void discovers files under routes/ as handlers, so a test file beside an endpoint can accidentally become part of routing.


Related: Database and Services · Testing and Debugging