SvelteKit Form Actions

fullstack
TypeScript
scaffolding
zen
Remix

Build forms with progressive enhancement using SvelteKit form actions.

12/8/2025

Prompt

SvelteKit Form Actions

Implement robust form handling in SvelteKit using Server Actions and progressive enhancement.

Requirements

1. Server Actions (+page.server.ts)

  • Define actions object satisfying Actions interface.
  • Implement default action or named actions (e.g., login, register).
  • Use request.formData() to retrieve data.
  • Validate input data and return fail(400, { error, values }) on failure.
  • Use redirect(303, url) for successful navigation.
  • Set cookies or manage sessions as needed.

2. Form Component (+page.svelte)

  • Import enhance from $app/forms.
  • Use <form method="POST" use:enhance> for progressive enhancement.
  • Handle form props (export let form: ActionData) to display server errors.
  • Implement custom submit logic with use:enhance callback for loading states:
    use:enhance(() => {
      loading = true;
      return async ({ result }) => {
        loading = false;
        await applyAction(result);
      };
    })
    

3. Type Safety

  • Use import type { Actions, PageServerLoad, ActionData } from './$types'.
  • Ensure strict typing for form data and responses.

Generate a complete example with a login form, including validation, error handling, and loading state.

Tags

sveltekit
forms
server-actions
progressive-enhancement

Tested Models

gpt-4
claude-3-5-sonnet

Comments (0)

Sign in to leave a comment

Sign In