Actions Example
Actions in Hyperspan are progressively enhanced <form> elements that can
be used to perform data mutations.
Hyperspan Actions feature data validation with Zod v4.x and can automatically update the UI with pending states, errors, and server-rendered responses in place. Hyperspan Actions require very little JavaScript to work, and can be used in any template or route. Read more about Actions in the Actions Docs.
Example Action:
Please enter your name below:
- Name must be at least 3 characters long
- Name must contain only letters (no numbers or special characters)
Example Action Code:
You can create an action by using the createAction function from the
@hyperspan/framework/actions package, similar to how you would create a route.
import { createAction } from "@hyperspan/framework/actions";
import { html } from "@hyperspan/html";
import { z } from "zod/v4";
export default createAction({
name: 'example-action',
schema: z.object({
name: z.string()
.min(3, 'Name must be at least 3 characters long')
.regex(/^[a-zA-Z]+$/, 'Name must contain only letters'),
}),
})
.form((c, { data, error }) => {
const errorMessage = error ? (error?.fieldErrors ? error?.fieldErrors?.name?.[0] : error.message) : '';
const errorHTML = error ? html`< div class= "alert alert-error mb-2" > ${ errorMessage } </div>` : '';
return html`
<p>Please enter your name below:</p>
<ul>
<li>Name must be at least 3 characters long</li>
<li>Name must contain only letters (no numbers or special characters)</li>
</ul>
<form method="post">
${errorHTML}
<input class="input input-bordered max-w-sm" type="text" name="name" value="${data?.name}" />
<button class="btn btn-primary" type="submit">Submit</button>
</form>
`;
})
.post(async (c, { data }) => {
return html(`
<div class="alert alert-success"><p>Hello, ${data?.name}!</p></div>
`;
});
Example Action Usage:
To use the action in a route, you can simply import it and render it in your template:
import { createRoute } from '@hyperspan/framework';
import ExampleAction from '~/app/actions/example-action';
export default createRoute().get((c) => {
return html`
<h1>Identify Yourself</h1>
${ExampleAction.render(c)}
`;
});