SvelteKit 07 🧡 Form Actions & Progressive Enhancement — Handling POST mutations with actions, fail(), named actions, and use:enhance
Form Actions are the fundamental way SvelteKit handles data mutations. Instead of creating separate API routes and manually calling them via fetch from the client, you define actions directly within your +page.server.ts files. This pattern treats forms as the source of truth for your application’s write operations, significantly reducing boilerplate code while ensuring that your application remains functional even when JavaScript is disabled or delayed in the browser.
This chapter explores how to define and handle POST requests through server-side actions. We will examine the structure of the actions object, how to return structured error data using the fail() helper, how to differentiate between multiple submission types using named actions, and how the use:enhance action provides a seamless, SPA-like experience through progressive enhancement.
Key point: Form Actions allow you to handle data mutations entirely on the server while optionally providing a smooth, client-side experience through use:enhance, which intercepts form submissions to prevent full-page reloads and automatically synchronizes UI state.
Why exists
The API fragmentation problem. Without Form Actions, developers often create /api/ endpoints that mirror every single form submission. This forces the application to maintain two distinct layers—one for data loading and one for data mutations—leading to unnecessary code duplication.
The progressive enhancement requirement. Web applications should be resilient. By using native HTML <form> elements, SvelteKit ensures that if a user’s connection is unstable or JavaScript fails to load, the core functionality of your application—submitting data—still works through standard browser behavior.
The state synchronization challenge. After a mutation, the server typically needs to update the UI. Form Actions automatically trigger a re-load of the load function for the current page, ensuring that the displayed data remains consistent with the backend state without manual re-fetching.
The complexity of client-side validation. Manually managing form errors, loading states, and validation logic on the client is notoriously error-prone. Form Actions provide a unified way to pass validation errors from the server back to the component, maintaining a clean contract between the data-processing logic and the user interface.
The “double submission” threat. In standard client-side forms, managing pending states to prevent double-submissions is difficult. SvelteKit’s use:enhance automates this process, providing hooks to manage loading states and disabling inputs during the submission lifecycle.
a. The standard actions object
In SvelteKit, the actions object is exported from a +page.server.ts file. By default, the default action is invoked when a form is submitted to the current page. This action receives a RequestEvent, which includes the request object containing the FormData.
// src/routes/contact/+page.server.ts
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
const email = data.get('email');
await saveToDatabase(email);
return { success: true };
}
};
When the form is submitted, the server processes the data, performs the mutation, and then triggers a re-run of the load functions. The return object is accessible in your +page.svelte component via the form prop, which contains the result of the submission.
b. Named actions and error handling with fail()
Named actions allow a single page to handle multiple different forms or distinct operations. By naming the action property, you target it by adding a query parameter to your form’s action attribute. When handling errors, use the fail() helper; it allows you to return a status code and custom error information without throwing a server exception.
import { fail } from '@sveltejs/kit';
export const actions = {
register: async ({ request }) => {
const data = await request.formData();
if (!data.get('username')) {
return fail(400, { missing: true, username: '' });
}
// ...
}
};
In your HTML, you target the named action by setting the action attribute to ?/register. If fail() is triggered, the form prop in your .svelte file will reflect the data provided to the fail call, enabling you to show precise validation errors near specific inputs.
c. Progressive enhancement via use:enhance
The use:enhance action is a Svelte action that transforms a standard form submission into a client-side navigation. When you apply use:enhance to a <form>, SvelteKit intercepts the submit event, sends the data via fetch, and updates the page state without a full reload.
<form method="POST" action="?/login" use:enhance>
<input name="email" />
<button type="submit">Login</button>
</form>
use:enhance also accepts a callback function. This function provides a formElement, formData, action, and a cancel() function. This is the ideal place to manage local component state, like setting a submitting flag or showing a loading spinner while the server processes the request.
Complete Example Session
// ============================================
// PART 1: THE SERVER ACTION (NAMED)
// ============================================
// src/routes/profile/+page.server.ts
import { fail } from '@sveltejs/kit';
export const actions = {
update: async ({ request }) => {
const data = await request.formData();
const name = data.get('name');
if (!name) return fail(400, { name, error: 'Required' });
await db.update(name);
return { success: true };
}
};
// ============================================
// PART 2: THE FORM COMPONENT
// ============================================
// src/routes/profile/+page.svelte
<script>
import { enhance } from '$app/forms';
export let form;
</script>
<form method="POST" action="?/update" use:enhance>
<input name="name" />
{#if form?.error} <p>{form.error}</p> {/if}
<button>Update</button>
</form>
// ============================================
// PART 3: THE CUSTOM ENHANCE LOGIC
// ============================================
<form use:enhance={({ formData, cancel }) => {
if (formData.get('name') === 'admin') cancel(); // stop submission
return async ({ update }) => {
await update(); // refresh page data
};
}}>
...
</form>
// ============================================
// PART 4: HANDLING MULTIPLE ACTIONS
// ============================================
// +page.server.ts
export const actions = {
login: async () => { /* ... */ },
logout: async () => { /* ... */ }
};
This sequence covers defining a server-side update action, binding it to a form with use:enhance, customizing the enhancement with client-side logic, and handling multiple actions within a single page file.
Quick Reference
Action Attributes
| Attribute | Usage |
|---|---|
method="POST" | Standard for mutations |
action="?/name" | Target named action |
use:enhance | Opt-in to SPA-like behavior |
Server Return Values
| Return Type | Usage |
|---|---|
{ success: true } | Signal successful mutation |
fail(code, data) | Return errors with HTTP status |
redirect(303, path) | Redirect after successful action |
Best Practices
✅ Do This:
// Always return data from actions
return { success: true }; // ✅
// Use namespaced error messages
return fail(400, { email: 'Invalid' }); // ✅
// Handle the update lifecycle in enhance
return async ({ update }) => { await update(); }; // ✅
// Reset form state if needed
formElement.reset(); // ✅
❌ Don’t Do This:
// Don't mutate state outside of actions
if (browser) { /* ... */ } // ❌
// Don't return plain objects if you need status
return { error: 'Failed' }; // Use fail() instead // ❌
// Don't ignore the return value in the component
// The 'form' prop is critical for UI feedback // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Full reload | use:enhance missing | Add use:enhance directive |
| State desync | Not awaiting update() | Always await update() |
| Security | Trusting FormData | Validate inputs server-side |
| Action mismatch | Wrong action attribute | Check ?/action-name syntax |
Real-World Examples
1. Simple login action
login: async ({ request }) => { /* ... */ }
2. Validation with fail
return fail(400, { values: data, error: 'Short' });
3. Redirect after submit
throw redirect(303, '/dashboard');
4. Disabling form on submit
use:enhance={() => { loading = true; return async () => { loading = false; } }}
5. Named action in HTML
<form action="?/logout">
6. FormData entries
const { email } = Object.fromEntries(data);
7. Client-side validation cancel
if (!valid) cancel();
8. Success object
return { success: true, message: 'Saved' };
9. Multiple action routing
<button formaction="?/register">Sign up</button>
10. Server-side persistence
await db.user.update({ where: { id }, data });
Visual
Form Action Lifecycle
┌──────────────────────────────────────────────┐
│ FORM SUBMISSION │
│ Browser POST ──► Server (+page.server.ts) │
│ │ │
│ Action Executes ◄───────┘ │
│ │ │
│ Reloads Data (Load) ◄───┘ │
│ │ │
│ Returns Data (form prop) ──► UI Updates │
└──────────────────────────────────────────────┘
use:enhance Flow
┌──────────────────────────────────────────────┐
│ use:enhance (intercepts) │
│ ├─ FormData gathered │
│ ├─ fetch() sent (async) │
│ ├─ UI updates (state managed) │
│ └─ update() refreshes current page │
└──────────────────────────────────────────────┘
Error Handling Pipeline
┌──────────────────────────────────────────────┐
│ VALIDATION │
│ Input check (server) │
│ │ │
│ ▼ │
│ fail(400, { error: 'invalid' }) │
│ │ │
│ ▼ │
│ Component 'form' prop updated │
│ │ │
│ ▼ │
│ UI shows error message │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Action definition | export const actions |
| Default action | default: async |
| Named action | ?/name |
| Error handling | fail(code, data) |
| Progressive tool | use:enhance |
Key takeaways:
- Form Actions are server-side. Mutations happen in
+page.server.ts, keeping sensitive logic away from the browser. - Progressive enhancement is built-in. Forms work as standard HTML if JS is off, and
use:enhanceupgrades them to SPA-like interactions. - The
formprop is vital. This prop is where server-side validation results and operation outcomes arrive in your Svelte components. - Use
fail()for errors. It allows you to return validation states or error messages without disrupting the control flow with exceptions. use:enhanceprovides full control. It exposes the submission process, letting you manage loading states, abort requests, and update the UI programmatically.
Remember: Form Actions represent the most idiomatic way to manage data mutations in SvelteKit. By consolidating your form logic into actions and embracing progressive enhancement, you build applications that are inherently more robust, easier to maintain, and performant. Keep your server logic focused on mutations and return structured feedback to your components via the form prop to maintain a clean and reactive user experience.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!