SvelteKit Data & Actions

17. Data Loading, Form Actions & Remote Functions

Fetch type-safe data with server load functions, mutate state with progressive enhancement form actions, and implement optimistic updates.

loading-actions.ts
// src/routes/newsletter/+page.server.ts
import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ locals }) => {
  return { subscribersCount: 1420 };
};

export const actions: Actions = {
  subscribe: async ({ request }) => {
    const data = await request.formData();
    const email = data.get('email')?.toString().trim();

    if (!email || !email.includes('@')) {
      return fail(400, { email, missing: true, error: 'Valid email required' });
    }

    // Save to database
    return { success: true, message: `Subscribed ${email} successfully!` };
  }
};

Data Loading, Form Actions & Remote Functions

SvelteKit provides end-to-end type safety between server data loaders (+page.server.ts), page components, and progressive enhancement form actions.

  • Server load vs Universal load: +page.server.ts runs exclusively on the server (accessing databases and secrets); +page.ts runs universally for caching and static generation.
  • Form Actions & use:enhance: Works without client JavaScript via standard HTML form POSTs, yet seamlessly progressively enhances into client-side AJAX with optimistic UI.
  • Validation with fail(): Return validation errors with HTTP status codes without throwing exceptions or losing user input.
Progressive Enhancement Form Actions Simulator use:enhance