@ogygia/router
Form actions
A page's actions answer a <form method="POST"> as Kit's form actions do, returning fail() to show the form again or throwing redirect() when done, with a typed form prop. use:enhance doesn't work on router pages; a remote form() in an island submits without a page load.
A sign-in form, a comment box or a settings page has to send something back to the server and show what happened. An action handles that post. You list a page’s actions under actions, keyed by name, and a plain <form method="POST"> on the page sends to them. The action reads the FormData itself, as in Kit, does the work, and says what happens next: return fail() to show the form again with a message, throw redirect() to move on, or return data for the page to show.
The redirect here is Kit’s, from @sveltejs/kit, not the router’s. Served from the hook, a cookie set or cleared before the router’s own redirect() is dropped and the sign-in silently fails; Kit’s carries it. Set cookies explains why. Anywhere no cookie is set, the router’s redirect() is the one to use.
The component reads what the action returned from its form prop. It’s undefined until the visitor posts, so read it with ?..
import { routes, page, fail } from '@ogygia/router';
import { redirect } from '@sveltejs/kit';
import Login from '$lib/views/Login.svelte';
import { auth } from '$lib/server/auth';
export const router = routes({
'/login': page(Login, {
actions: {
default: async (c) => {
const form = await c.request.formData();
const email = String(form.get('email') ?? '');
const session = await auth.login(
email,
String(form.get('password') ?? '')
);
if (!session)
return fail(400, {
email,
incorrect: true
});
c.cookies?.set('session', session.id, {
path: '/',
httpOnly: true
});
redirect(303, '/'); // Kit's redirect, so the cookie goes with it
}
}
})
});
export type App = typeof router.$infer;<script lang="ts">
import type { App } from '$lib/router';
let { form }: App['/login'] = $props();
</script>
<form method="POST">
<input name="email" type="email" value={form?.email ?? ''} />
<input name="password" type="password" />
{#if form?.incorrect}<p>Wrong email or password.</p>{/if}
<button>Sign in</button>
</form>Post lifecycle
- The browser posts the form. The SPA router doesn’t take form posts, so it’s a normal page load.
- The router picks the action (see Named actions) and runs it.
- Then every load on the page’s branch runs, so the page shows fresh data.
- The page renders with
formset to what the action returned.
A late region on that page doesn’t stream after a post.
The browser shows that rendered page at the form’s URL. Reloading it posts again, so when an action has changed something, finish with redirect(303, …) and let the browser GET the next page.
An island can read the same result from page.form in $app/state, with no prop. See Page data.
Return values
| The action | The answer |
|---|---|
| returns data | The page renders with form set to that data, status 200. |
| returns nothing | The page renders with no form, status 200. |
returns fail(status, data) | The page renders with form set to data, and the response has status. |
throws redirect(status, to) | A redirect to to. Use 303 after a post. |
throws error(status, msg) | The nearest error page renders, inside its layouts, with status. |
returns a Response | That response is sent as it is; nothing renders. |
fail() is returned, not thrown, as in Kit. A thrown fail() isn’t treated as a failure: the request answers with its data as JSON.
Named actions
A page can have several actions. The default one answers a post to the page’s own URL. A named one answers a post whose query starts with ?/name, Kit’s convention: action="?/logout" on the form, or formaction="?/delete" on a button.
- A post to a page with no actions answers
405, with anAllowheader ofGET, HEAD. - A post that names an action the page doesn’t have answers
404through the page’s error page. Thedefaultaction doesn’t run in its place. - A post with no
?/nameto a page with only named actions answers405. ItsAllowheader still listsPOST(#2293).
logout below clears the session cookie, so, like the sign-in above, it ends with Kit’s redirect() to get the cleared cookie to the browser from the hook.
import { routes, page } from '@ogygia/router';
import { redirect } from '@sveltejs/kit';
import Account from '$lib/views/Account.svelte';
import { auth } from '$lib/server/auth';
export const router = routes({
'/account': page(Account, {
load: async (c) => ({ user: await auth.user(c.cookies) }),
actions: {
rename: async (c) => {
const name = String(
(await c.request.formData()).get('name') ?? ''
);
await auth.rename(c.cookies, name);
return { renamed: name };
},
logout: async (c) => {
await auth.logout(c.cookies);
redirect(303, '/'); // Kit's redirect: the cleared cookie goes with it
}
}
})
});<script lang="ts">
import type { App } from '$lib/router';
let { data, form }: App['/account'] = $props();
</script>
<form method="POST" action="?/rename">
<input
name="name"
value={form?.renamed ?? data.user?.name ?? ''}
/>
<button>Rename</button>
</form>
<form method="POST" action="?/logout">
<button>Sign out</button>
</form>Types
App['/path']['form'] is built from what the actions return. It’s the union of every action’s return type, with each fail(status, data) unwrapped to its data, plus null. A page with no actions has form: null. An action that only redirects adds nothing, since redirect() never returns.
For the page above, App['/account']['form'] is { renamed: string } | null.
To write an action outside the table, check it with satisfies Action<'/pattern'>, which types c.params and keeps the return type (why not an annotation). action(fn) and action('/pattern', fn) wrap a function the same way load() does, but an action isn’t memoized: it runs once per post.
There’s no schema for form data: an action reads FormData itself, as in Kit. For typed, validated input, use a remote form() or command().
import { fail, type Action } from '@ogygia/router';
import { posts } from '$lib/server/posts';
export const savePost = (async (c) => {
const body = String(
(await c.request.formData()).get('body') ?? ''
);
if (!body) return fail(400, { empty: true });
await posts.save(c.params.id, body);
return { saved: true };
}) satisfies Action<'/posts/[id]/edit'>;Progressive enhancement
use:enhance from $app/forms doesn’t work on router pages. It posts with fetch and expects Kit’s JSON action result, but the router answers every post with the whole rendered page, and Kit’s client, which enhance hands the result to, isn’t on the page.
To submit without leaving the page, put the form in an island and use a remote form(). It sends its own request, shows its result in place, and refreshes the page’s data when it’s done. A plain <form method="POST"> to an action keeps working with no JavaScript at all.
Fields the visitor typed into islands come back when they return to the page, with no setup. See Half-filled forms.