Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 35 ยท SvelteKit

Form Actions and Progressive Enhancement

Handle forms in SvelteKit with actions - default and named actions, FormData, validation with fail(), redirect after success, use:enhance and the form prop.

Forms are how the web sends data to a server, and they worked long before JavaScript frameworks. SvelteKit builds on that: a <form method="POST"> posts to an action defined in +page.server.js. The page works with JavaScript turned off, and when JavaScript is on, one line (use:enhance) upgrades it to an in-place update with no full reload. That idea is called progressive enhancement.

SvelteKit is read-only on this site (it needs a server). The <TryIt> blocks are stand-ins: plain JavaScript that models an action pipeline (FormData in, fail/redirect/data out) so you can run the logic.

A default action

JavaScript
// src/routes/login/+page.server.js
import { fail, redirect } from '@sveltejs/kit';

export const actions = {
  default: async ({ request, cookies }) => {
    const data = await request.formData();
    const email = String(data.get('email') ?? '').trim();
    const password = String(data.get('password') ?? '');

    if (!email.includes('@')) {
      return fail(400, { email, error: 'Enter a valid email address.' });
    }
    const user = await checkLogin(email, password);
    if (!user) {
      return fail(401, { email, error: 'Wrong email or password.' });
    }

    cookies.set('session', user.sessionId, { path: '/', httpOnly: true, sameSite: 'lax', secure: true });
    redirect(303, '/dashboard');
  },
};
HTML
<!-- src/routes/login/+page.svelte -->
<script>
  import { enhance } from '$app/forms';
  let { form } = $props();
</script>

<form method="POST" use:enhance>
  {#if form?.error}<p role="alert">{form.error}</p>{/if}

  <label>Email <input name="email" type="email" value={form?.email ?? ''} required /></label>
  <label>Password <input name="password" type="password" required /></label>
  <button>Log in</button>
</form>

Reading it from the top:

  • request.formData() gives you a standard FormData object. Every value is a string (or a File), so convert and validate.
  • fail(status, data) returns validation errors without throwing. The data comes back to the page as the form prop, and the response status is status. Return the submitted values (but never the password) so the user does not retype them.
  • redirect(303, '/dashboard') sends the browser away after success. Use 303 so the browser follows with a GET.
  • use:enhance intercepts the submit, sends it with fetch, updates form and resets the form on success; the page does not reload.

Without JavaScript the same form submits normally, and the server re-renders the page with form set. Same logic, two paths.

Named actions

A page can handle several buttons with named actions. Post to ?/name:

JavaScript
export const actions = {
  add: async ({ request }) => { /* ... */ },
  remove: async ({ request }) => {
    const id = Number((await request.formData()).get('id'));
    await removeTodo(id);
    return { removed: id };
  },
};
HTML
<form method="POST" action="?/add" use:enhance> ... </form>

<form method="POST" action="?/remove" use:enhance>
  <input type="hidden" name="id" value={todo.id} />
  <button aria-label="Delete {todo.text}">x</button>
</form>

A single <button formaction="?/archive"> can also pick an action for one form. You cannot mix a default action with named ones on the same page.

What the action returns

Action returns Result
plain object { saved: true } form prop receives it, status 200
fail(400, {...}) form receives it, status 400, nothing else invalidated
redirect(303, url) navigation
thrown error(...) nearest +error.svelte

After a successful action, SvelteKit re-runs the page's load functions (all of them), so lists on the page show the new data. That is why a todo list needs no manual update code.

An action pipeline, as code

Here is the same flow in plain JavaScript: parse FormData, validate, return fail or success, with named actions chosen like ?/name:

JS Running form actions against FormData

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Customizing use:enhance

use:enhance takes an optional callback that runs on submit and returns another callback for the result. Use it for a loading state or to keep the default behavior while adding your own:

HTML
<script>
  import { enhance } from '$app/forms';
  let saving = $state(false);
</script>

<form
  method="POST"
  use:enhance={() => {
    saving = true;
    return async ({ update }) => {
      await update();      // apply the default behavior (set form, reset, invalidate)
      saving = false;
    };
  }}
>
  <button disabled={saving}>{saving ? 'Saving...' : 'Save'}</button>
</form>

Security notes

  • CSRF: SvelteKit rejects cross-origin form POSTs by default (an origin check), which protects actions. Do not turn it off unless you know why.
  • Validate on the server. Browser required and type="email" are for convenience only.
  • Never send secrets back in fail() data: it is rendered into the page.
  • Actions only exist for POST. A GET form belongs in a load function reading url.searchParams.
JS Validating FormData like a real action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does a SvelteKit form action live?

    Actions are exported from +page.server.js, so they run on the server with access to cookies, databases and secrets.
  2. 2. What does fail(400, { error }) do?

    fail is for expected validation problems; the data is available as form in the page and no error page is rendered.
  3. 3. What does use:enhance add?

    It is progressive enhancement: the plain POST works anyway, enhance only improves the experience.
  4. 4. How do you target a named action called remove?

    Named actions are chosen with a query string that starts with a slash: ?/remove.

Summary

  • Export actions from +page.server.js; read request.formData(), validate and return data, fail() or redirect().
  • The page reads results through the form prop; named actions use action="?/name".
  • use:enhance upgrades a plain form without JavaScript to a smooth in-place one; pass a callback for loading state.
  • After a successful action load re-runs, so lists refresh by themselves.
  • Validate on the server, never echo secrets and rely on the built-in origin check.

Next: Hooks and Server Endpoints