| | |

SvelteKit 03 ๐Ÿ“ Progressive Enhancement โ€” Upgrading native forms with use:enhance

โฑ๏ธ Estimated read: 8 min | |

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 fetch calls requires complex state management for loading, success, and error states; use:enhance automates this synchronization.
  • The Progressive Enhancement tradeoff. Building custom AJAX forms often leads to “JavaScript-only” websites that break for non-JS users; use:enhance provides 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

HookTimingPurpose
submitBefore requestDisable UI, show spinners
updateAfter responseSync UI with server state
cancelDuring submitStop submission logic

Result Types

TypeMeaning
successAction completed
failurefail() called on server
redirectredirect() called on server
errorUnexpected server error

Utilities

UtilityPurpose
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

PitfallWhy It HappensFix
Double submissionNot disabling buttonUse loading state
Sync issuesForgetting to await update()Always await the update
Navigation lossRedirect logic not handledUse standard applyAction
UI staleNot invalidating stateUse 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

ItemValue
Directiveuse:enhance
Primary useAJAX upgrade for native forms
Customizationsubmit / update lifecycle
Manual resultapplyAction()
Graceful fallNative if JS fails

Key takeaways:

  • Upgrade, don’t replace. use:enhance keeps 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(). The update() 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:enhance directive; 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.

Was this helpful?


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!