| | |

Svelte 61 🧡 Progressive Enhancement and Form Actions — export const actions in +page.server.ts

⏱️ Estimated read: 8 min | |

Form handling is a fundamental part of web development, traditionally involving custom API endpoints, manual CORS configuration, and complex state management. SvelteKit simplifies this through “Form Actions,” a feature that allows you to define submission logic directly within your +page.server.ts file. This architecture adheres to the browser’s native capabilities, allowing forms to function even if JavaScript fails to load or is disabled, a concept known as Progressive Enhancement.

By leveraging native HTML form submissions, SvelteKit allows your application to remain functional in restricted environments while providing a seamless, high-performance experience when JavaScript is active. This chapter covers the anatomy of server-side actions, how to process FormData securely, and the integration of the use:enhance directive to bridge the gap between native browser behavior and modern SPA-like interactivity.

Key point: Form Actions allow you to handle form submissions on the server, ensuring that your application is natively robust and progressively enhanced; using use:enhance upgrades the native browser behavior to a modern, asynchronous experience without sacrificing accessibility or reliability.


Why exists

The Boilerplate Problem. Writing dedicated API routes (/api/submit) for simple form submissions creates unnecessary files and code duplication. Actions exist to colocate your submission logic with the page that hosts the form, simplifying navigation and maintenance.

The Progressive Enhancement Problem. Relying solely on client-side JS to handle forms means the site breaks if a script fails to load. Actions exist to ensure that the server-side code handles the request natively via a POST request, ensuring the application always works.

The State Sync Problem. After a submission, developers often struggle to keep the page’s reactive data in sync with the database. Actions exist to automatically re-run the page’s load function after a successful submission, ensuring the UI always reflects the database state.

The Request Handling Problem. Handling FormData, cookies, and authentication logic in client-side code is complex and potentially insecure. Actions exist to run this logic within the secure server environment, providing direct access to request headers and session data.

The UX/JS Gap Problem. While native forms are reliable, they cause full-page reloads. use:enhance exists to intercept these native requests, turning them into asynchronous updates that feel modern and snappy without losing the native fallback capability.


a. Anatomy of an Action

An action is defined in your +page.server.ts file as a named export called actions. You can define a default action or multiple named actions. Each action receives the RequestEvent, which includes the request object used to parse FormData.

// src/routes/signup/+page.server.ts
export const actions = {
  default: async ({ request }) => {
    const data = await request.formData(); // Parse the form data
    const email = data.get('email');
    // Save to database logic here
    return { success: true };
  }
};

When a user submits a form pointing to this route, SvelteKit calls the action, processes the logic, and—if successful—invalidates the current page data. This causes the load function to re-run, fetching the latest state from your database and providing it to the page components automatically.


b. Named Actions and Validation

For complex pages, you might have multiple forms, such as “Update Profile,” “Change Password,” and “Delete Account.” Named actions allow you to separate these concerns clearly within the same actions object. You trigger them by appending ?/actionName to the form’s action attribute.

export const actions = {
  update: async ({ request }) => { /* logic */ },
  delete: async ({ request }) => { /* logic */ }
};

Validation is often performed inside the action using the fail helper. If validation fails (e.g., a missing field), you return the fail object along with the form input values, allowing the user to correct their mistakes without losing the data they already typed.

import { fail } from '@sveltejs/kit';

// Inside an action:
if (!email) return fail(400, { email, missing: true });

c. Progressive Enhancement with use:enhance

The use:enhance directive is the core of SvelteKit’s progressive enhancement. When added to a <form>, it prevents the browser’s default behavior of a full-page reload and intercepts the submission to send it via fetch. If the JS doesn’t load, the form defaults to a native post, and the page reloads normally.

<script>
  import { enhance } from '$app/forms';
</script>

<form method="POST" use:enhance>
  <input name="email" type="email" />
  <button>Submit</button>
</form>

You can pass a callback to enhance to run custom logic during the submission, such as showing a loading spinner, or to perform client-side validation before the server even sees the request. This provides the “best of both worlds”: the reliability of native browser forms and the speed of an SPA.


Complete Example Session

// ============================================
// PART 1: THE ACTION DEFINITION
// ============================================
// src/routes/settings/+page.server.ts
export const actions = {
  updateName: async ({ request }) => {
    const data = await request.formData();
    // perform DB update
    return { success: true };
  }
};

// ============================================
// PART 2: THE FORM COMPONENT
// ============================================
// src/routes/settings/+page.svelte
<form method="POST" action="?/updateName" use:enhance>
  <input name="name" />
  <button>Save</button>
</form>

// ============================================
// PART 3: VALIDATION AND FAIL
// ============================================
import { fail } from '@sveltejs/kit';
// if (err) return fail(400, { name, error: 'Invalid' });

// ============================================
// PART 4: ACCESSING ACTION DATA
// ============================================
// export let form; (Available in +page.svelte)

// ============================================
// PART 5: REDIRECTS
// ============================================
import { redirect } from '@sveltejs/kit';
// throw redirect(303, '/success');

// ============================================
// PART 6: ENHANCE CALLBACKS
// ============================================
// use:enhance(({ formElement, formData, action, cancel }) => {
//   return async ({ result }) => { ... };
// });

// ============================================
// PART 7: NATIVE FALLBACK
// ============================================
// Without 'use:enhance', it's a standard POST.

// ============================================
// PART 8: SERVER-SIDE VALIDATION
// ============================================
// Action returns form state, UI responds.

// ============================================
// PART 9: TYPE SAFETY
// ============================================
// import type { Actions } from './$types';

// ============================================
// PART 10: COOKIE MUTATION
// ============================================
// cookies.set('...', '...'); // In the action

These parts illustrate the action flow from server-side definition and validation to client-side enhancement.


Quick Reference

Form Action Helpers

FunctionPurpose
fail(status, data)Return errors while keeping UI state
redirect(status, path)Redirect user after success
request.formData()Parse the POST body

Enhance Options

HookPurpose
updateDefault Svelte behavior (re-runs load)
cancelStop submission (e.g., failed client validation)
resultAccess the server’s return object

Best Practices

✅ Do This:

// Use fail for validation errors
return fail(400, { email, missing: true });                // ✅

// Always use use:enhance for SPA feel
<form use:enhance>                                         // ✅

// Destructure formData for cleanliness
const data = await request.formData();                     // ✅

// Handle errors at the page level with 'form' prop
{#if form?.error} <p>{form.error}</p> {/if}                // ✅

❌ Don’t Do This:

// Don't leak sensitive data in 'fail' return
return fail(400, { secret: '123' });                       // ❌

// Don't rely on client-side JS alone
// Always ensure the action works natively                 // ❌

// Don't use large data in hidden inputs
// Use database lookups instead                            // ❌

// Don't forget 'method="POST"'
// Actions require POST requests                           // ❌

Common Pitfalls

PitfallWhy It HappensFix
No JS executionuse:enhance missingAdd to form tag
Action 405Method is GETChange to POST
Data lossForgot fail() returnReturn fail with inputs
Wrong actionMisspelled action nameCheck ?/actionName

Real-World Examples

1. Simple submission

export const actions = { default: async ({ request }) => { ... } };

2. Named action

export const actions = { login: async (...) => { ... } };

3. Validation failure

return fail(400, { email: 'invalid' });

4. Enhancing a form

<form use:enhance />

5. Handling result in enhance

use:enhance(() => { return async ({ result }) => { ... } })

6. Redirecting

throw redirect(303, '/dashboard');

7. Parsing form data

const data = await request.formData();

8. Typed actions

export const actions: Actions = { ... };

9. Setting cookies

cookies.set('session', '...');

10. Returning success

return { success: true };

Visual

The Submission Lifecycle

┌──────────────────────────────────────┐
│  Browser: Form Submit (POST)         │
│         │                            │
│  Server: Actions (Action Name)       │
│         │                            │
│  Server: Re-run Load()               │
│         │                            │
│  Browser: UI Updated                 │
└──────────────────────────────────────┘

Enhance vs Native

┌──────────────────────────────────────┐
│  NATIVE: Form -> Reload -> HTML      │
│                                      │
│  ENHANCED: Form -> Fetch -> JSON     │
│             -> Patch DOM             │
└──────────────────────────────────────┘

Summary

ItemValue
Definingexport const actions
Triggeraction="?/name"
ProgressiveNative HTML POST
SPA-feeluse:enhance
Validationfail() helper

Key takeaways:

  • Actions are server-only. They run in the secure server environment, providing a perfect place for database mutations and auth checks.
  • Native defaults are safe. Because SvelteKit forms are standard HTML, they work even without client-side JavaScript.
  • use:enhance is the upgrade. Adding this directive converts standard form submissions into efficient, asynchronous updates without changing your server code.
  • fail() preserves state. Always use the fail helper for validation errors to ensure the user doesn’t have to re-type their form data.
  • Colocation is powerful. Defining the submission logic in the same file as the page content simplifies code navigation and makes data management more intuitive.

Remember: Form Actions represent the bridge between the old world of full-page-reload web development and the modern world of reactive, SPA-like interfaces. By defaulting to native browser behavior and selectively upgrading it with use:enhance, you create applications that are both reliable for all users and modern for those with capable devices.

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!