Svelte & SvelteKit (50 Qs)•Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)
SvelteKit Form Actions & Progressive Enhancement with `use:enhance`.
senior LevelCode ExampleState ManagementFormsSystem Design
In Simple Words:
Form Actions in SvelteKit handle HTML <form> submissions on the server in +page.server.ts. Using the use:enhance action, forms progressively enhance into seamless client-side fetch submissions without page reloads while remaining 100% functional if JavaScript is disabled.
typescript
// src/routes/contact/+page.server.ts
import { fail } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
default: async ({ request }) => {
const data = await request.formData();
const email = data.get('email');
if (!email) return fail(400, { missing: true });
await db.saveLead(String(email));
return { success: true };
}
};
svelte
<!-- src/routes/contact/+page.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
let { form } = $props();
</script>
<form method="POST" use:enhance>
<input name="email" type="email" required />
<button type="submit">Subscribe</button>
{#if form?.success}<p>Subscribed successfully!</p>{/if}
</form>