Skip to content

SvelteKit Forms Explained — Form Actions and Validation

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about SvelteKit Forms Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

SvelteKit form actions in +page.server.js handle POST, PUT, and DELETE requests from HTML forms, providing server-side validation, data persistence, and progressive enhancement.

What You'll Learn

  • Form actions in +page.server.js
  • use:enhance for progressive enhancement
  • Validation and error return
  • File upload handling
  • Redirect after successful submission

Why It Matters

Form actions are SvelteKit's solution for form handling without client-side JavaScript by default, with progressive enhancement for JavaScript-enabled users.

// 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 = data.get("email");
    const password = data.get("password");

    if (!email || !email.includes("@")) {
      return fail(400, { email, error: "Invalid email" });
    }
    if (!password || password.length < 6) {
      return fail(400, { email, error: "Password too short" });
    }

    const user = await db.authenticate(email, password);
    if (!user) {
      return fail(401, { email, error: "Invalid credentials" });
    }

    cookies.set("session", user.sessionId, { path: "/", httpOnly: true });
    throw redirect(302, "/dashboard");
  },
};
<script>
  export let form;
  import { enhance } from "$app/forms";
</script>

<form method="POST" use:enhance>
  <input name="email" type="email" value={form?.email ?? ""} placeholder="Email" />
  <input name="password" type="password" placeholder="Password" />
  {#if form?.error}<p class="error">{form.error}</p>{/if}
  <button type="submit">Log In</button>
</form>

Expected output: Server-side validation returns errors as form data, use:enhance provides client-side updates, redirect on successful login.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro