Skip to content

Forms and Actions

A search form should produce a shareable URL; a feedback form needs to submit a body to a server. Router preserves that distinction. GET forms use ordinary route navigation, while POST forms stay native unless the original destination route explicitly opts into a custom form handler.

Start with a mounted Router in a Navigation-API-capable browser. These are HTML form submissions, not React function-valued action examples. Backend authentication, authorization, validation, and CSRF protection remain your server’s responsibility for every mutation.

A GET form places successful controls into the destination’s query string. Inside your application, render:

export default function LessonSearch() {
return (
<form method="get" action="/lessons">
<label>
Topic <input name="topic" />
</label>
<button type="submit">Find lessons</button>
</form>
)
}

Register /lessons to your results page and read topic with useSearchParams. Submitting react navigates to /lessons?topic=react. The native navigate event has no submitted FormData body for this GET, so Router follows the normal guards → prefetch → component-render flow. A route’s formHandler is not used for GET search.

Do not use GET to change server state. Query strings are public URL state, not a safe location for passwords or secrets.

If your backend already handles an HTML POST at /feedback, keep an ordinary form and do not register a formHandler for its destination:

export default function FeedbackForm() {
return (
<form method="post" action="/feedback">
<label>
Feedback <textarea name="message" required />
</label>
<button type="submit">Send feedback</button>
</form>
)
}

This example assumes your server endpoint exists and supplies any required CSRF fields. Without a destination form handler, Router neither intercepts the POST nor runs its guards/prefetch. The browser submits the body to the server and follows its response. The same rule applies when no route matches, or the submitted FormData is empty.

Registering only a React page at /feedback does not make that page a server POST endpoint. Ensure the production host routes mutations to the backend rather than rewriting them to the application document. This native path is the recommended choice when the server already owns submission and response rendering.

Choose a custom handler only when your client intentionally owns submission dispatch and the post-submit experience. The following complete src/feedbackRoutes.tsx module assumes an existing same-origin /api/feedback endpoint that accepts FormData and reports success with a 2xx status. That endpoint must enforce its own permissions and CSRF policy.

import { createRouter, type FormHandler } from '@studiolambda/router/react'
function FeedbackPage() {
return (
<form method="post" action="/feedback">
<label>
Feedback <textarea name="message" required />
</label>
<button type="submit">Send feedback</button>
</form>
)
}
const sendFeedback: FormHandler = async (formData, event) => {
const message = formData.get('message')
if (typeof message !== 'string' || message.trim() === '') {
throw new Error('feedback message is required')
}
const response = await fetch('/api/feedback', {
method: 'POST',
body: formData,
signal: event.signal,
})
if (!response.ok) throw new Error('feedback submission failed')
}
export const matcher = createRouter((route) => {
route('/feedback').formHandler(sendFeedback).render(FeedbackPage)
})

Mount this matcher in Router with onNavigateSuccess/onNavigateError reporting and your usual error boundary. The server contract is an integration prerequisite, not an endpoint supplied by the router. Add server-required CSRF tokens to the form or request before using this pattern with a real backend; client validation is only an early usability check.

On an eligible POST, Router awaits guards, then prefetch, then sendFeedback. A rejected check prevents dispatch. The handler receives the original native NavigateEvent, so its request can cooperate with event.signal cancellation. A non-2xx response is explicitly turned into a failure because fetch does not do that automatically.

If the action succeeds without a redirect, Router does not replace the current rendered route, update its stored navigation type/signal, reset the form, or invalidate data. It keeps the current page. Your application owns a success notification, form reset, and data-cache invalidation. Native completion reporting can confirm that the handler finished; it does not prove any broader business workflow succeeded.

Keep the submitted body with its original owner

Section titled “Keep the submitted body with its original owner”

Form ownership is decided from the original destination before route checks run. A form handler is route-local and is not inherited from a group. Add it to each rendered route that should own a submission.

If a precommit redirect changes the destination URL, Router checks/prefetches the target and renders it. It runs neither the source action nor a target action with the original body. Even a query-only change counts as a different destination. This prevents silently sending submitted content to a new action owner.

Without a redirect, a custom action runs instead of normal route rendering, even if its action URL names a page different from the currently visible one. Do not assume that posting to a route also displays its component.

Design failures and cancellation deliberately

Section titled “Design failures and cancellation deliberately”

An action throw/rejection fails native navigation and reaches onNavigateError; it does not render Router’s notFound or automatically throw into a route render boundary. Handle submission failure in your application UI. Noncancelable checks occur after URL commit, so failure cannot restore that URL.

Passing event.signal can abort a cooperating client request. It does not prove the server rolled back a request already received. Protect nonrepeatable operations with server-side idempotency and transaction rules, and do not retry mutations merely because a navigation was canceled. Use browser-level tests to verify actual form interception and native fallback behavior.