SvelteKit 03 ๐ Progressive Enhancement โ Upgrading native forms with use:enhance
Native HTML forms are the bedrock of the web, providing a functional data submission model that works without a single line of JavaScript. However, the default browser behavior of navigating to a new page or refreshing the current one upon submission is often detrimental to the user experience in modern web applications. SvelteKitโs use:enhance directive is the bridge between this robust native functionality and the dynamic, responsive world of single-page applications.
By applying use:enhance to your form, you instruct SvelteKit to intercept the submission event, perform the request asynchronously, and update the page’s data and stateโall without a full browser reload. Crucially, because it is built on the principle of progressive enhancement, the form remains entirely functional if JavaScript fails to load or is disabled. This chapter examines how this directive works under the hood, how to customize the submission lifecycle, and how to use advanced hooks like applyAction to take full control of the response.
Key point: use:enhance is a Svelte action that intercepts a native form submission, sends the data via AJAX, and updates the SvelteKit-managed page state (like the form prop) in-place; it defaults to native form behavior if JavaScript is unavailable, ensuring maximum reliability.
Why exists
- The Full Navigation problem. Traditional form submissions force a full browser refresh, which wipes out local UI state, resets scroll positions, and causes a jarring “flicker.”
- The Lack of Feedback problem. Native forms provide no native way to show a “Loading…” spinner or disable buttons to prevent double-submissions, leading to a poorer UX.
- The Smooth Transition problem. Developers want the speed of an SPA, but they want to keep the semantic, robust structure of standard HTML forms for accessibility and SEO.
- The Client-Server Synchronization problem. Managing manual
fetchcalls requires complex state management forloading,success, anderrorstates;use:enhanceautomates this synchronization. - The Progressive Enhancement tradeoff. Building custom AJAX forms often leads to “JavaScript-only” websites that break for non-JS users;
use:enhanceprovides a seamless upgrade path that guarantees a working site under any condition.
a. Intercepting the submit event with use:enhance
The use:enhance directive is applied directly to the <form> element. When present, SvelteKit listens for the submit event on that form. Instead of allowing the browser to initiate a standard POST request, it prevents the default behavior and instead performs the action using a background fetch.
<form method="POST" use:enhance>
<input name="email" />
<button type="submit">Subscribe</button>
</form>
When you use the bare use:enhance directive, SvelteKit handles the entire lifecycle automatically: it sends the form data, updates the form prop, and handles redirects or errors. If the server returns a redirect, SvelteKit follows it automatically. If it returns a fail() response, it updates the form prop seamlessly.
b. Customizing the lifecycle with submit and update
You can pass a callback function to use:enhance to gain fine-grained control over the submission. This function receives a data object (the FormData), the form element, and an action function. Most importantly, it allows you to return an update function that runs after the server response is received.
<form method="POST" use:enhance={({ form, data, action, cancel }) => {
// Logic here runs before submission
return async ({ result, update }) => {
// Logic here runs after server response
await update(); // Default behavior: re-runs load functions
};
}}>
This allows you to implement loading states, toast notifications, or specific UI clean-up. For example, if you want to reset the form inputs after a successful submission, you would perform the reset logic inside the async callback after calling update().
c. Advanced control with applyAction
While the update() function handles the standard SvelteKit behavior (re-running load functions and updating the form prop), sometimes you need to handle the server result manually. The applyAction() function is provided for this exact purpose. It takes the result object and applies the standard SvelteKit logicโredirecting, invalidating data, or updating the form propโbased on the specific server outcome.
import { applyAction } from '$app/forms';
// ... inside the use:enhance callback
return async ({ result }) => {
if (result.type === 'success') {
// Custom logic before applying standard success
await applyAction(result);
}
};
This is particularly useful when you need to run specific animations or track events before allowing the framework to perform its final state reconciliation. applyAction ensures that even if you delay the standard update, the frameworkโs internal state remains perfectly consistent with the server.
Complete Example Session
// ============================================
// PART 1: THE SERVER ACTION
// ============================================
// +page.server.ts
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
// process data...
return { success: true };
}
};
// ============================================
// PART 2: THE ENHANCED FORM
// ============================================
// +page.svelte
<script>
import { enhance } from '$app/forms';
let loading = $state(false);
</script>
<form method="POST" use:enhance={() => {
loading = true;
return async ({ update }) => {
loading = false;
await update();
};
}}>
<input name="text" />
<button disabled={loading}>
{loading ? 'Submitting...' : 'Submit'}
</button>
</form>
This example covers the full lifecycle: toggling a loading state before the request, awaiting the server update, and resetting the UI state automatically once the process concludes.
Quick Reference
use:enhance Hooks
| Hook | Timing | Purpose |
|---|---|---|
submit | Before request | Disable UI, show spinners |
update | After response | Sync UI with server state |
cancel | During submit | Stop submission logic |
Result Types
| Type | Meaning |
|---|---|
success | Action completed |
failure | fail() called on server |
redirect | redirect() called on server |
error | Unexpected server error |
Utilities
| Utility | Purpose |
|---|---|
applyAction(result) | Applies standard SvelteKit response |
update() | Runs load functions + updates form |
Best Practices
โ Do This:
// Always destructure result and update
return async ({ result, update }) => { ... } // โ
// Disable buttons during submission
<button disabled={loading}>Submit</button> // โ
// Call update() for standard behavior
await update(); // โ
// Return a custom object for granular control
return async ({ result }) => { await applyAction(result); } // โ
โ Don’t Do This:
// Don't call update() inside a try/catch without result
// (you lose error information) // โ
// Don't ignore the `cancel` function
// (allows double submissions) // โ
// Don't mix manual `fetch` with `use:enhance`
// (defeats the purpose) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Double submission | Not disabling button | Use loading state |
| Sync issues | Forgetting to await update() | Always await the update |
| Navigation loss | Redirect logic not handled | Use standard applyAction |
| UI stale | Not invalidating state | Use default update() behavior |
Real-World Examples
1. Basic enhancement
<form method="POST" use:enhance>
2. Button loading state
use:enhance={() => { loading = true; return async ({ update }) => { loading = false; await update(); } }}
3. Conditional cancellation
use:enhance={({ cancel }) => { if (invalid) cancel(); }}
4. Post-submission notification
return async ({ update }) => { await update(); toast.show(); }
5. Custom result handling
return async ({ result }) => { if (result.type === 'redirect') ... }
6. Resetting form after success
return async ({ update }) => { await update(); formElement.reset(); }
7. Server-side redirect handling
return async ({ result }) => { await applyAction(result); }
8. Error boundary
return async ({ result }) => { if (result.type === 'error') ... }
9. Dynamic input focusing
return async ({ update }) => { await update(); input.focus(); }
10. Manual invalidation
invalidateAll();
Visual
The use:enhance Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FORM SUBMIT โโโบ [ Intercept ] โ
โ โ โ
โ [ submit callback ] โโโ โ
โ โ โ
โ AJAX REQUEST โโโโโโโโโโ โ
โ โ โ
โ SERVER RESPONSE โโโบ [ Result Received ] โ
โ โ โ
โ [ update callback ] โโโ โ
โ โ โ
โ [ UI RECONCILE (update) ] โโโโ FINISHED โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Native vs Enhanced
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ NATIVE: Form -> Reload -> Full Page Load โ
โ โ
โ ENHANCED: Form -> Fetch -> Update State โ
โ โ
โ Both share the same server-side logic. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The update() Process
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SERVER DATA โโโบ [ Run load functions ] โ
โ โ โ
โ [ Update form prop ] โโ โ
โ โ โ
โ [ DOM Patching ] โโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Directive | use:enhance |
| Primary use | AJAX upgrade for native forms |
| Customization | submit / update lifecycle |
| Manual result | applyAction() |
| Graceful fall | Native if JS fails |
Key takeaways:
- Upgrade, don’t replace.
use:enhancekeeps your HTML structure native and robust, only “upgrading” the interaction layer to AJAX when the client is capable. - Manage the lifecycle. Always use the callback to manage loading indicators, prevent double-submissions, and perform UI cleanup.
- The power of
update(). Theupdate()function is the engine that keeps your data and UI in sync; always await it after the server has processed the form. - Fine-grained control. If you need to perform logic specific to certain result types, manually handle the result and
applyAction()rather than relying on the default behavior. - Safety first. Because the fallback is native, your forms must still work without the
use:enhancedirective; always validate your actions on the server.
Remember: use:enhance is the final step in mastering SvelteKit forms. It allows you to build interfaces that feel as responsive as a desktop application, without sacrificing the reliability and accessibility of the standard web. By controlling the lifecycle with submit and update, you ensure the user is always informed of the request status, leading to a professional, frictionless 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!