Ever filled in a long form, then lost everything you typed because of one wrong field? The order form at Mrs. Sri's stall mustn't work like that. In SvelteKit, a form is sent to a form action: a function in +page.server.js that receives the contents of a <form> when that form is sent with method="POST". It can turn the submission away while handing the input back, or accept it and send the customer to another page.
Picture the order slip at the cashier of Mrs. Sri's stall. A customer writes a name, a dish and a number of portions, then hands it to the cashier. If the name is empty, the cashier hands the slip back with a red note, and what was already written stays on it. If all is well, the cashier sends the customer to the waiting table. The slip is the <form>, the cashier is the action on the server, the slip handed back is fail(400, ...), and moving to the waiting table is redirect(303, ...).
The action in +page.server.js
The stall's /order page has two files. This is the server one:
// src/routes/order/+page.server.js
import { fail, redirect } from "@sveltejs/kit"
import { allDishes } from "#lib/menu.js"
export const actions = {
default: async ({ request }) => {
const data = await request.formData()
const name = String(data.get("name") ?? "").trim()
const menuId = Number(data.get("menu"))
const portions = Number(data.get("portions"))
if (!name) {
return fail(400, { name, menuId, portions, message: "The customer's name is required" })
}
if (portions < 1) {
return fail(400, { name, menuId, portions, message: "At least 1 portion" })
}
const menu = allDishes.find((m) => m.id === menuId)
console.log("order in:", name, menu.name, portions, "portions")
redirect(303, "/order/thank-you")
},
}
export const actionsis an object of actions. Thedefaultkey receives a form sent to this very page, that is a<form method="POST">with noactionattribute.request.formData()reads the form's contents.data.get("name")takes the field withname="name". Everything arrives as a string, so"3"goes throughNumber()first.fail(400, {...})rejects the submission with status 400, and its object reaches the page asform.redirect(303, "/order/thank-you")tells the browser to open another address. Likeerror(), it throws itself, so noreturnorthrowis needed.- Actions only belong in
+page.server.js. Put them in+page.jsand SvelteKit stops withInvalid export `actions` in `src/routes/order/+page.js` (`actions` is a valid export in +page.server.js).
The page: let { form } = $props()
<!-- src/routes/order/+page.svelte -->
<script>
import { allDishes } from "#lib/menu.js"
let { form } = $props()
</script>
<h2>Order</h2>
{#if form?.message}
<p class="error">{form.message}</p>
{/if}
<form method="POST">
<label>Name <input name="name" value={form?.name ?? ""} /></label>
<label>
Menu
<select name="menu">
{#each allDishes as m (m.id)}
<option value={m.id} selected={form?.menuId === m.id}>{m.name}</option>
{/each}
</select>
</label>
<label>Portions <input name="portions" type="number" value={form?.portions ?? 1} /></label>
<button>Order</button>
</form>
let { form } = $props()receives the last action's result. When the page is simply opened,formisnull, which is why it's writtenform?.message. If the page also has aload, take both:let { data, form } = $props().- Every field has a
name. A field withoutnameisn't sent, anddata.get(...)for it isnull. value={form?.portions ?? 1}fills the field from the rejected submission, or1when there is none.
The result, tried in SvelteKit 3 with JavaScript turned off:
| Input | Request | Server's answer | What shows |
|---|---|---|---|
| empty name, Chicken Noodles, 3 portions | POST /order, body name=&menu=2&portions=3 |
400, the /order page drawn again |
"The customer's name is required", Chicken Noodles and 3 still filled in |
| Andi, Chicken Noodles, 3 portions | POST /order, body name=Andi&menu=2&portions=3 |
303, location: /order/thank-you |
the browser opens GET /order/thank-you: "Thank you!" |
The server terminal logs order in: Andi Chicken Noodles 3 portions.
Send the input back through fail
Without JavaScript, the 400 answer is a new page. The browser forgets everything that was typed, and the fields get their contents from value={form?....}. When fail only returns { message }, the submission "empty name, Chicken Noodles, 3 portions" comes back as Fried Rice and 1 portion; the customer has to fill everything in again. With use:enhance (below) too, Name and Portions go back to their defaults as soon as form changes. So send the input back: fail(400, { name, menuId, portions, message }).
The exception is a password: never send it back. For a login form, return the email only.
It works without JavaScript
<form method="POST"> is plain HTML. The browser already knows how to send it without JavaScript, and the server answers with a whole page. So the order still arrives, even when JavaScript in the customer's browser is off or hasn't finished loading. Building this way is called progressive enhancement: the feature works first without JavaScript, then gets nicer when JavaScript is there. This is what form actions have over an API endpoint called with fetch: without JavaScript, fetch doesn't run at all.
The nicer part comes from use:enhance, a Svelte action (the Actions lesson) from $app/forms:
<script>
import { enhance } from "$app/forms"
import { allDishes } from "#lib/menu.js"
let { form } = $props()
</script>
<form method="POST" use:enhance>
<!-- the same fields -->
</form>
With JavaScript, use:enhance intercepts the submission and sends POST /order through fetch, with the header x-sveltekit-action: true. The server answers with JSON, not a page:
400 {"type":"failure","status":400,"location":"/order","data":"[{\"name\":1,\"menuId\":2,\"portions\":3,\"message\":4},\"\",2,3,\"The customer's name is required\"]"}
200 {"type":"redirect","status":303,"location":"/order/thank-you"}
- Failure: the page doesn't reload.
formis updated and the red message appears. - Success: SvelteKit moves to
/order/thank-youin the browser, without reloading the header. - Without JavaScript, the same form still works as in the table above.
Several buttons: named actions
A page can have several actions. Name them in the actions object, for example order: async ({ request }) => {...} and cancel: async ({ request }) => {...}, then point to one with the action attribute:
<form method="POST" action="?/order">...</form>
<form method="POST" action="?/cancel"><button>Cancel</button></form>
default can't be mixed with named actions; SvelteKit answers 500 and the terminal writes When using named actions, the default action cannot be used. A form without ?/... sent to a page that only has named actions gets a 404.
New projects: SvelteKit 3 and Svelte 5
The page in this lesson is written the same way as in a project from npx sv create: runes are on, so form is taken with let { form } = $props(). In older SvelteKit tutorials and repos you'll see export let form and export let data. They mean the same, but in a runes project that form is rejected with Cannot use export let in runes mode. Actions, fail, redirect and use:enhance are exactly the same in both versions.
Exercise: a login form
The exercise editor runs several route files at once, like a small SvelteKit: src/routes/login/+page.svelte, src/routes/login/+page.server.js and src/routes/dashboard/+page.svelte. A POST form sends its fields to the action in +page.server.js as a real Request, so await request.formData() works. There's no real server: the action runs in the preview.
// src/routes/login/+page.server.js
import { fail, redirect } from "@sveltejs/kit"
export const actions = {
default: async ({ request }) => {
const data = await request.formData()
const email = data.get("email")
const password = data.get("password")
if (password !== "secret123") {
return fail(400, { email, error: "Wrong password" })
}
redirect(303, "/dashboard")
},
}
The login page reads the result with let { form } = $props(). With a wrong password, fail sends its object to the page as form: the message Wrong password shows and the email already typed stays, through value={form?.email ?? ""}. With secret123, redirect takes you to /dashboard.
⚠️ Orders that vanish, arrive empty, or come in twice
- Forgetting
method="POST". A form without a method is sent as GET: the browser opens/order?name=Andi&menu=2&portions=3, the page shows as usual, and the action never runs. - A field without
name. Its contents aren't sent, sodata.get("password")isnulland the login always fails. failwithout the input. Without JavaScript, the customer has to type everything again. Send the input back, except a password.- A dish that isn't on the menu. Anyone can change a
<select>value in DevTools, or send the form directly withcurl, for examplemenu=99.allDishes.find(...)then returnsundefined, andmenu.namethrowsTypeError: Cannot read properties of undefined (reading 'name'). The customer sees a 500 error page. The server must not trust what a form sends, and that includes the choice from a<select>. Check the result offindbefore you use it:if (!menu) return fail(400, { name, menuId, portions, message: "Unknown dish" }). - Success without
redirect. If the action only doesreturn { success: true }, the page on screen is the answer to a POST. The customer presses refresh, the browser offers to send the form again, and the order goes in twice.redirect(303, ...)moves them to a plain GET page.
TL;DR: A form action is written in +page.server.js as export const actions = { default: async ({ request }) => {...} } and receives a <form method="POST">. Its contents are read with await request.formData() and data.get("name"), all strings, and only fields with a name are sent. fail(400, { ...input, message }) rejects the submission and sends its object to the page as form, read with let { form } = $props(); send the input back so nothing has to be retyped, except a password. redirect(303, "/order/thank-you") after success prevents a double submission on refresh. The server doesn't trust what a form sends, so the <select> choice is checked too before it is used. The form is plain HTML, so it works without JavaScript: that's progressive enhancement. use:enhance from $app/forms adds sending through fetch without reloading the page. Several actions get names and are pointed to with action="?/cancel", and can't be mixed with default. The exercise: a login form with <input name="email"> and <input name="password">, and an action that returns fail(400, { email, error: "Wrong password" }) or calls redirect(303, "/dashboard").
⚡ The action in +page.server.js
Write:
// src/routes/login/+page.server.js
import { fail, redirect } from "@sveltejs/kit"
export const actions = {
default: async ({ request }) => {
const data = await request.formData()
const email = data.get("email")
const password = data.get("password")
if (password !== "secret123") {
return fail(400, { email, error: "Wrong password" })
}
redirect(303, "/dashboard")
},
}
Meaning: export const actions in +page.server.js receives a <form method="POST">. request.formData() reads its contents, and data.get("email") takes the field with name="email". fail(400, {...}) rejects the submission, and redirect(303, ...) sends the browser to another address.
⚡ The result arrives as form
Write:
<script>
let { form } = $props()
</script>
{#if form?.error}
<p class="error">{form.error}</p>
{/if}
<form method="POST">
<input name="email" type="email" placeholder="Email" value={form?.email ?? ""} />
<input name="password" type="password" placeholder="Password" />
<button>Login</button>
</form>
Guess first: the password input is written without a name attribute. Can the login ever succeed?
Never. A field without name isn't sent, so data.get("password") is null and the login always fails.
Meaning: The object from fail reaches the page as form. What was typed comes back through value={form?.email ?? ""}, except the password.
⚡ It works without JavaScript
Meaning: <form method="POST"> is plain HTML, so it still works when JavaScript in the browser is off. This way of building is called progressive enhancement. use:enhance from $app/forms adds sending through fetch without reloading the page.