Svelte 63 🧡 Declarative Form Enhancement Directive — use:enhance and Custom Handlers
The use:enhance directive is the bridge between the old-school reliability of native HTML forms and the modern demands of a reactive, asynchronous application. By default, SvelteKit forms function as standard browser POST requests, causing a full-page reload on submission. Adding use:enhance informs SvelteKit that it should intercept this interaction, convert it into an asynchronous fetch request, and handle the server response without leaving the current view. This declarative approach keeps your application accessible to users without JavaScript while providing a high-fidelity experience to those who have it enabled.
Beyond mere submission interception, use:enhance accepts a callback function that allows you to orchestrate the client-side lifecycle. This gives you fine-grained control over the submission process, enabling you to implement custom loading indicators, perform complex client-side validation, or conditionally handle specific server results. This chapter explores how to utilize these hooks to create robust, user-friendly forms that respect the framework’s progressive enhancement contract while giving you complete control over the reactive UI.
Key point: use:enhance transforms native form submissions into asynchronous operations by intercepting the submit event; it allows you to inject custom behavior via a callback that provides lifecycle hooks for the submission, the server result, and the subsequent reactive update.
Why exists
The Reload-Free UX Problem. Native form submissions result in a “flash” or full-page reload, which disrupts the user’s flow. use:enhance exists to provide an SPA-like experience for native forms, ensuring the UI stays reactive and consistent without refreshing the page.
The Lifecycle Integration Problem. Developers need to know exactly when a form starts submitting and when the server completes its work to show loaders or disable buttons. use:enhance exists to expose these lifecycle states, allowing the developer to react to the state machine of the submission process.
The Progressive Enhancement Problem. Writing custom fetch code for every form is error-prone and often breaks if JS fails. use:enhance exists to ensure that your form-handling logic is “upgradable”—if JavaScript fails, the browser falls back to a native POST, and the form remains fully functional.
The Result Processing Problem. Handling the variety of server responses (success, validation errors, redirects) manually is tedious. use:enhance exists to automate the synchronization of the form store and the re-triggering of the load function, ensuring the UI reflects server state changes immediately.
The Interception Flexibility Problem. Sometimes you need to cancel a submission due to client-side validation logic. use:enhance exists to provide a cancel() function, giving you the ability to prevent an unnecessary network round-trip based on local criteria.
a. Intercepting and Enhancing Submissions
When you apply use:enhance to a form without arguments, SvelteKit assumes default behavior: it intercepts the submission, sends the FormData to the server, updates the form prop, and re-runs the page’s load function if the server returns a successful result.
<!-- Basic usage -->
<form method="POST" use:enhance>
<input name="email" />
<button>Send</button>
</form>
This default behavior is often sufficient, but for more complex UIs, you pass a submit function. This function receives the formElement, the formData, and a cancel method. It is executed before the request is sent, allowing you to perform initial checks or set up visual states before the request leaves the browser.
b. Lifecycle Hooks and Callbacks
The enhance callback returns an object with update and result functions. This gives you two distinct phases to interact with: the result phase (once the server has responded) and the update phase (once SvelteKit has updated the internal stores and re-run the load functions).
<form method="POST" use:enhance={({ formData, cancel }) => {
if (!formData.get('email')) {
cancel(); // Prevents submission
return;
}
return async ({ result, update }) => {
// result is the server's return object
if (result.type === 'success') {
console.log('Done!');
}
await update(); // Default behavior: re-run load, update form prop
};
}}>
This pattern is the industry standard for SvelteKit form handling. By explicitly invoking await update(), you retain the framework’s automated data synchronization while gaining the ability to inject custom logic (like triggering a toast notification or clearing a local state) based on the server’s response.
c. The Progressive Enhancement Guarantee
The progressive enhancement guarantee is the reason use:enhance is preferred over manually calling fetch in an event handler. If the user’s network is slow, or if a browser extension blocks your bundle, the form remains a simple POST request. The server-side action handler will execute exactly as it would if your enhanced code were running.
// src/routes/signup/+page.server.ts
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
// Logic runs whether enhance is present or not
}
};
Because your actions are server-side endpoints, you never have to worry about the “what if” scenarios of client-side failures. The structure ensures that you write your data-mutating logic once, and SvelteKit upgrades the transport layer automatically based on the browser’s capabilities.
Complete Example Session
// ============================================
// PART 1: BASIC ENHANCE
// ============================================
<form method="POST" use:enhance>
// ============================================
// PART 2: CUSTOM ENHANCE SUBMIT
// ============================================
<form use:enhance={({ formData, cancel }) => {
if (!formData.get('agree')) cancel();
}}>
// ============================================
// PART 3: HANDLING THE RESULT
// ============================================
return async ({ result, update }) => {
if (result.type === 'redirect') {
goto(result.location);
}
await update();
};
// ============================================
// PART 4: LOADING STATE
// ============================================
let loading = $state(false);
<form use:enhance={() => {
loading = true;
return async () => { loading = false; };
}}>
// ============================================
// PART 5: FORMDATA ACCESS
// ============================================
// const email = formData.get('email');
// ============================================
// PART 6: CANCEL SUBMISSION
// ============================================
// cancel(); // stop the request
// ============================================
// PART 7: UPDATE HOOK
// ============================================
// await update({ reset: false }); // keep form values
// ============================================
// PART 8: TYPING ENHANCE
// ============================================
// import type { SubmitFunction } from './$types';
// ============================================
// PART 9: ACCESSING FORMELEMENT
// ============================================
// formElement.reset();
// ============================================
// PART 10: PROGRESSIVE FALLBACK
// ============================================
// HTML form attributes (action, method) still work
The example flow demonstrates how use:enhance moves from a simple directive to a powerful, callback-driven lifecycle manager.
Quick Reference
Submit Function API
| Hook | Timing | Purpose |
|---|---|---|
formData | Before fetch | Access/Edit submission |
cancel | Before fetch | Stop submission |
formElement | Before fetch | Access HTML form |
Result Callback API
| Hook | Timing | Purpose |
|---|---|---|
result | After fetch | Inspect server response |
update | After fetch | Sync form prop and load |
Best Practices
✅ Do This:
// Use enhance for all forms to ensure SPA feel
<form use:enhance> // ✅
// Always await update() if used
return async ({ update }) => await update(); // ✅
// Handle redirects manually if needed
if (result.type === 'redirect') goto(result.location); // ✅
// Reset loading state in the result callback
return async () => { loading = false; }; // ✅
❌ Don’t Do This:
// Don't use window.fetch for form submissions
// (Breaks progressive enhancement) // ❌
// Don't forget to await the result of update()
update(); // (Race condition potential) // ❌
// Don't rely on enhance for security
// Actions handle validation on server // ❌
// Don't call cancel() without logic
// (Forms become unresponsive) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| No feedback | Forgot update() | Always call await update() |
| Redirect loop | Redirecting too early | Check result.type |
| Sync issues | Custom logic before update | Ensure update runs eventually |
| State flickering | update called twice | Call once per callback |
Real-World Examples
1. Basic enhancement
<form use:enhance />
2. Loading spinner state
<form use:enhance={() => {
loading = true;
return async () => { loading = false; };
}} />
3. Client-side validation
use:enhance={({ formData, cancel }) => {
if (formData.get('pwd').length < 8) cancel();
}}
4. Custom update behavior
return async ({ update }) => {
await update({ reset: false }); // keep input
};
5. Handling server redirects
return async ({ result }) => {
if (result.type === 'redirect') goto(result.location);
};
6. Resetting form element
return async ({ update }) => {
await update();
formElement.reset();
};
7. Error notification
return async ({ result }) => {
if (result.type === 'failure') toast('Failed');
};
8. Typed submit function
const submit: SubmitFunction = ({ cancel }) => { ... };
9. Disabling buttons
<button disabled={loading}>Submit</button>
10. Default behavior
<form method="POST" use:enhance />
Visual
The Enhance Lifecycle
┌──────────────────────────────────────┐
│ 1. Submit Callback (before fetch) │
│ │ │
│ 2. Fetch (asynchronous POST) │
│ │ │
│ 3. Result Callback (after fetch) │
│ │ │
│ 4. Update (Sync state & load) │
└──────────────────────────────────────┘
Progressive Enhancement Guarantee
┌──────────────────────────────────────┐
│ JAVASCRIPT ENABLED │
│ Form -> Fetch -> JSON │
│ │
│ JAVASCRIPT DISABLED/FAILED │
│ Form -> Browser POST -> Reload │
└──────────────────────────────────────┘
The Callback Sequence
┌──────────────────────────────────────┐
│ enhance = (submitFn) => { │
│ // Pre-request │
│ return async ({ result }) => { │
│ // Post-request │
│ await update(); │
│ }; │
│ } │
└──────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Directive | use:enhance |
| Default | Intercept & Update |
| Lifecycle | Submit -> Result -> Update |
| Fallback | Native HTML POST |
| Result API | result, update, cancel |
Key takeaways:
- Always enhance.
use:enhanceis the foundation of high-quality forms in SvelteKit, transforming native browser behaviors into reactive SPA interactions. - Understand the lifecycle. The submit callback runs before the network request, while the result callback gives you control after the server response is received.
- Maintain progressive enhancement. Because your backend is built on native
actions, your form logic will remain rock-solid regardless of the user’s browser environment. - Control the update. Always call
await update()inside your result callback to ensure SvelteKit properly refreshes theformstore and re-runs the page’sloadfunction. - Use for orchestration. Use the
enhancecallback to bridge the gap between your server-side logic and your client-side UI (loaders, toasts, manual redirects).
Remember: The use:enhance directive is the “secret sauce” that allows SvelteKit to be both a traditional server-side framework and a modern SPA library. By sticking to native HTML for the transport layer and using this directive for the client-side upgrade, you get the best of both worlds: extreme reliability and a frictionless 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!