Form Actions
A form action is one POST handler that serves a plain HTML form, a form enhanced with JavaScript, an HTMX form, and a typed Eden call. Forms keep working when JavaScript is off.
#Overview
You define an action with defineAction and mount it like any Elysia plugin. The body schema validates the form, and each invalid field gets its own message. The same action answers each caller in the way that caller expects.
Form actions work on React, HTML and HTMX pages. React uses the useFormAction hook. HTML pages use enhanceForms. HTMX forms use hx-post and the action's htmx renderer.
#Define an Action
defineAction(path, options) takes the route path and an options object. body is an Elysia t.Object. Add an error string to a property to replace the validator's message for that field.
// src/actions.ts
import { defineAction } from '@absolutejs/absolute';
import { t } from 'elysia';
export const signup = defineAction('/actions/signup', {
body: t.Object({
email: t.String({ error: 'Enter a valid email', format: 'email' }),
name: t.String({ error: 'Use at least 2 characters', minLength: 2 })
}),
handler: ({ body, fail }) => {
if (body.email.endsWith('@taken.dev'))
return fail({ email: 'That email is already registered' });
return { greeting: `Welcome, ${body.name}` };
}
});The handler runs only when the body is valid. Return data for success. Return fail(errors, message?) for errors you find yourself, such as a taken email. The keys of errors are typed to the schema's fields.
Browser forms send strings. Before validation, an unchecked checkbox becomes false, on becomes true, a numeric string becomes a number, and an empty file input is dropped.
Mount the action with .use(). A page route reads the result of the last post without JavaScript with getActionState(action) and passes it to the page as a prop. It returns undefined when there is none.
// src/backend/server.ts
import { asset, getActionState, prepare } from '@absolutejs/absolute';
import { handleReactPageRequest } from '@absolutejs/absolute/react';
import { Elysia } from 'elysia';
import { signup } from '../actions';
import { Signup } from '../frontend/react/pages/Signup';
const { absolutejs, manifest } = await prepare();
export const server = new Elysia()
.use(absolutejs)
.use(signup)
.get('/signup', () =>
handleReactPageRequest({
Page: Signup,
index: asset(manifest, 'SignupIndex'),
props: { signupState: getActionState(signup) }
})
);#React
useFormAction comes from @absolutejs/absolute/react/hooks. Pass the action's type with import type, so no server code reaches the browser bundle. The path is type-checked against the action.
// src/frontend/react/pages/Signup.tsx
import type { ActionStateOf } from '@absolutejs/absolute';
import { useFormAction } from '@absolutejs/absolute/react/hooks';
import type { signup } from '../../../actions';
type SignupProps = {
signupState?: ActionStateOf<typeof signup>;
};
export const Signup = ({ signupState }: SignupProps) => {
const form = useFormAction<typeof signup>('/actions/signup', {
initialState: signupState
});
return (
<html lang="en">
<head>
<title>Sign up</title>
</head>
<body>
<form {...form.formProps}>
<input defaultValue={form.values.name} name="name" />
{form.errors.name && <p>{form.errors.name}</p>}
<input defaultValue={form.values.email} name="email" />
{form.errors.email && <p>{form.errors.email}</p>}
<button disabled={form.pending} type="submit">
Sign up
</button>
</form>
{form.state.status === 'success' && <p>{form.data?.greeting}</p>}
</body>
</html>
);
};formProps renders a real form with method="post", the action path and multipart/form-data. Before hydration, or with JavaScript off, the browser posts it normally. Once hydrated, a submit goes through fetch and the page does not reload.
The hook returns state, pending, errors, values, data, message, submit and reset. A newer submit aborts an older one. On success the form resets, unless the action redirects or you pass resetOnSuccess: false.
#Without JavaScript
A plain post gets a 303 back to the page the form was on. The result travels in a cookie named absolute_action that lasts 60 seconds. The next HTML page served reads it once, clears it, and is sent with Cache-Control: no-store.
On error, the result holds the field errors and what the user typed, so the form shows both. Files and fields whose names look secret, such as password or token, are never echoed. In the React example, form.values.email and form.errors.email come from initialState, so the server render and hydration match.
#Redirects
Set redirect to send the browser somewhere else after success. Without JavaScript, the 303 goes there. With JavaScript, the helpers navigate there.
export const contact = defineAction('/actions/contact', {
body: t.Object({
message: t.String({ error: 'Write at least 10 characters', minLength: 10 }),
topic: t.String()
}),
handler: ({ body }) => ({ ticket: `T-${body.topic}` }),
// A string, or a function of the handler's result
redirect: (data) => `/thanks?ticket=${data.ticket}`
});#HTML Pages
Static HTML pages can't run code on the server, so AbsoluteJS writes the result into the form for you. Mark the form with data-absolute-action and add elements for the messages.
<!-- src/frontend/html/pages/Contact.html -->
<!doctype html>
<html lang="en">
<head>
<title>Contact</title>
<script type="module" src="../scripts/enhance-contact.ts"></script>
</head>
<body>
<form method="post" action="/actions/contact" data-absolute-action>
<select name="topic">
<option value="sales">Sales</option>
<option value="support">Support</option>
</select>
<textarea name="message"></textarea>
<p data-action-error="message" hidden></p>
<p data-action-message></p>
<button type="submit">Send</button>
</form>
</body>
</html>After a post without JavaScript, the server fills each [data-action-error="field"] and removes its hidden, fills [data-action-message], shows [data-action-success] on success, sets aria-invalid on invalid fields, sets data-action-status on the form, and puts the typed values back.
To submit without a reload, call enhanceForms() from @absolutejs/absolute/client. It applies the same markup changes in the browser, sets aria-busy and disables submit buttons while pending, focuses the first invalid field, and fires an absolute:form-action event on the form. It skips forms that have hx-post.
// src/frontend/html/scripts/enhance-contact.ts
import { enhanceForms } from '@absolutejs/absolute/client';
enhanceForms();#HTMX Pages
Give the action an htmx renderer. It receives the result and returns the HTML fragment that HTMX swaps in. The answer is a 200, so HTMX swaps errors too.
export const subscribe = defineAction('/actions/subscribe', {
body: t.Object({
email: t.String({ error: 'Enter a valid email', format: 'email' })
}),
handler: ({ body }) => ({ email: body.email }),
htmx: (result) =>
result.status === 'success'
? `<p id="subscribe-result">Subscribed ${result.data?.email}</p>`
: `<p id="subscribe-result">${result.errors.email ?? result.message}</p>`
});Keep method, action and data-absolute-action on the form next to hx-post. With JavaScript, HTMX posts and swaps the fragment. Without it, the form posts normally and the server writes the result into the form, as on an HTML page.
<!-- src/frontend/htmx/pages/Subscribe.html -->
<form
method="post"
action="/actions/subscribe"
data-absolute-action
hx-post="/actions/subscribe"
hx-target="#subscribe-result"
hx-swap="outerHTML"
>
<input name="email" type="email" />
<p data-action-error="email" hidden></p>
<p data-action-success hidden>You are subscribed.</p>
<button type="submit">Subscribe</button>
</form>
<p id="subscribe-result"></p>If the renderer returns undefined, or the action has none, an HTMX request gets an HX-Redirect and the result cookie, which behaves like a post without JavaScript.
#Eden and JSON
An action is a normal Elysia route with a body schema, so Eden sees it. A missing or mistyped field is a type error. JSON clients get the result as JSON, with 422 when it is an error.
import { treaty } from '@elysia/eden';
import type { server } from '../backend/server';
const api = treaty<typeof server>(window.location.origin);
const { data, error } = await api.actions.signup.post({
email: 'ada@example.com',
name: 'Ada'
});
if (error) {
// error.status is 422
// error.value is { status: 'error', errors: { email?: string; name?: string } }
console.log(error.value);
} else {
// data is { status: 'success', data: { greeting: 'Welcome, Ada' } }
console.log(data);
}
// Type error: property 'email' is missing
await api.actions.signup.post({ name: 'Ada' });A request counts as JSON when it sends a JSON body, or when its Accept header asks for JSON and not HTML.
#Responses
One action, one handler. The caller decides the shape of the answer.
| Caller | Answer |
|---|---|
| Plain form post (no JavaScript) | 303 to the page the form was on, or to redirect. The result rides in a short-lived cookie. |
useFormAction or enhanceForms | JSON result with status 200, valid or not |
| Eden, fetch, or any JSON client | JSON result, 422 on error |
HX-Request: true | The htmx fragment with status 200, or HX-Redirect when there is no fragment |
| Cross-site post | 403 before the body is read |
Content-Length over maxBodySize | 413 |
Cross-site protection is on by default. A post passes when its Sec-Fetch-Site is same-origin or none, when its Origin matches the host or a trusted origin, or when it sends neither header.
#Options
export const changePassword = defineAction('/actions/change-password', {
// Runs after validation, before the handler. Return a response to stop.
beforeHandle: ({ request }) =>
request.headers.get('cookie')?.includes('session=')
? undefined
: new Response('Sign in first', { status: 401 }),
body: t.Object({
confirm: t.Boolean({ error: 'Tick the box to confirm' }),
password: t.String({ minLength: 12 })
}),
// Also accept posts from this origin.
csrf: { trustedOrigins: ['https://admin.example.com'] },
handler: ({ body, fail }) =>
body.confirm
? { changed: true }
: fail({ confirm: 'Tick the box to confirm' }),
// Refuse bodies over 64 KiB with 413 before reading them.
maxBodySize: 64 * 1024,
// Don't send typed values back after a failed post without JavaScript.
preserveValues: false,
redirect: '/account'
});| Option | What it does |
|---|---|
body | An Elysia t.Object. Its keys are the field names. |
handler | Gets body, fail, request, set and the Elysia context. Returns data, fail(...), or a Response. |
redirect | A path, or a function of the returned data. Default: back to the form page. |
htmx | Returns the HTML fragment for HTMX requests, or undefined. |
beforeHandle | Runs after validation. Return a response to stop. |
csrf | { trustedOrigins } to allow other origins, or false to turn the check off. |
maxBodySize | Bytes. Default 10 MiB. |
preserveValues | Echo typed values after a failed post without JavaScript. Default true. |
#Result Types
ActionStateOf<typeof action> is the state a form can be in. Use it to type the prop that carries getActionState. The success data comes from what the handler returns, and the error keys come from the body schema.
import type { ActionStateOf } from '@absolutejs/absolute';
import type { signup } from '../actions';
type SignupState = ActionStateOf<typeof signup>;
// | { status: 'idle' }
// | { status: 'success'; data?: { greeting: string }; redirect?: string }
// | {
// status: 'error';
// errors: { email?: string; name?: string };
// message?: string;
// values?: { email?: string | string[]; name?: string | string[] };
// }