SvelteKit Form Actions
Form actions let a page send data to the server with a standard HTML form. The server code lives in a +page.server.js file, runs after the form submits, and decides what happens next. The approach works even when JavaScript fails to load in the browser.
A Default Action
Export an actions object from +page.server.js. The default action handles a form that posts to its own page.
// src/routes/subscribe/+page.server.js
import { fail } from "@sveltejs/kit";
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
const email = data.get("email");
if (!email || !email.toString().includes("@")) {
return fail(400, { email, invalid: true });
}
// Save the address in your database here
return { success: true };
}
};The fail helper returns a status code and data without throwing. The page receives that data and can show the problem.
The Matching Page
<script>
export let form;
</script>
<form method="POST">
<label for="email">Email</label>
<input id="email" name="email" value={form?.email ?? ""} />
<button>Subscribe</button>
</form>
{#if form?.invalid}
<p role="alert">Enter a valid email address.</p>
{/if}
{#if form?.success}
<p>Thank you for subscribing.</p>
{/if}The form prop stays undefined until the first submission. The question mark guards against that.
Form Journey Diagram
Visitor fills the form and presses Subscribe
|
v
Browser sends a POST request
|
v
actions.default() runs on the server
|
+--------+---------+
| |
Invalid input Valid input
| |
fail(400, data) return { success: true }
| |
+--------+---------+
|
v
Page re-renders with the form propNamed Actions
A page with several forms uses named actions. The form picks its action through a query string that starts with a slash.
export const actions = {
login: async ({ request }) => { /* check credentials */ },
register: async ({ request }) => { /* create account */ }
};
<form method="POST" action="?/login"> ... </form>
<form method="POST" action="?/register"> ... </form>A page cannot mix a default action with named actions.
Progressive Enhancement
Without extra code, a submission reloads the page. The enhance function upgrades the form: it submits through fetch, updates the form prop, and keeps scroll position and focus in place.
<script>
import { enhance } from "$app/forms";
export let form;
</script>
<form method="POST" use:enhance>
<input name="email" />
<button>Subscribe</button>
</form>Visitors with working JavaScript get a smooth experience, and visitors without it still complete the task.
Security Basics
- SvelteKit checks the origin of form posts to block cross-site request forgery by default
- Validate every field on the server, since browser checks can be skipped
- Never return passwords or private values from fail, because they travel back to the page
- Hash passwords with a trusted library before storing them
Action Summary
Piece Where It Lives Job
------------- ---------------------- ---------------------------
actions +page.server.js Process submitted data
fail() @sveltejs/kit Return errors with a status
form prop +page.svelte Show results from the action
use:enhance $app/forms Submit without a full reloadA Layman Analogy
Picture a paper form handed to a clerk at a service window. The clerk checks the entries, stamps accepted forms, and returns faulty ones with a note in the margin. The form prop is that returned paper, and the enhance function is a pneumatic tube that makes the exchange quicker.
Common Mistakes To Avoid
- Forgetting method POST on the form element
- Leaving out name attributes on inputs, which hides them from formData
- Throwing errors for ordinary validation problems rather than using fail
- Skipping server-side validation because the page already checks fields
Key Points
- Actions process form submissions in +page.server.js
- The fail helper sends validation errors back to the page
- Named actions support several forms on one page
- The enhance function adds a smooth experience on top of working forms
