Web frameworks · Intermediate · 24 min
Build pages, load data and handle forms in SvelteKit
By Padding · Updated 18 Nov 2026
Node.js 26 · SvelteKit 3.4.0 · Svelte 5.58.0 · adapter-node 6.0.5
You will build a SvelteKit 3.4 guestbook with a shared layout, server load functions, a form action that returns validation errors with fail(), use:enhance on top, and a production build running on Node.js with adapter-node.
On this page
SvelteKit is the application framework for Svelte. Each folder under src/routes is a URL, and the files inside it have fixed names with fixed jobs: +page.svelte is what the page shows, +page.server.ts loads its data and handles its form posts on the server, +layout.svelte wraps every page below it, and +error.svelte is shown when something fails. Every page is rendered on the server first, then Svelte takes over in the browser.
You will build a guestbook: a home page that lists entries and has a form to sign, one page per entry, an About page and a friendly 404. The form is a normal HTML form that posts to the server, so it works before any JavaScript has loaded, which matters on a low-end Android phone on prepaid data where scripts can arrive seconds after the page. Then you add use:enhance, so browsers that do run the JavaScript submit without a full page reload. Finally you build it with adapter-node and run it as a plain Node.js server.
SvelteKit 3 came out in 2026. If you have used SvelteKit 2, three changes show up in this tutorial: configuration lives in vite.config.ts (there is no svelte.config.js), the $lib alias is now #lib and imports name the file extension, and $app/stores is gone in favour of $app/state. The commands work the same on Linux and macOS.
Step 1 · Create the project
sv is the Svelte command-line tool. Its create command scaffolds a project. The options below answer every question it would otherwise ask: the minimal template, TypeScript, the Node.js adapter, and npm to install dependencies:
cd ~
npx -y sv@1.6.0 create sveltekit-guestbook-demo --template minimal --types ts --add sveltekit-adapter="adapter:node" --install npm
cd sveltekit-guestbook-demoThe template asks for version ranges, so pin the exact versions this tutorial was written against:
npm install -D @sveltejs/kit@3.4.0 svelte@5.58.0 @sveltejs/adapter-node@6.0.5Check it worked
npm ls @sveltejs/kit svelte @sveltejs/adapter-node --depth=0
cat vite.config.ts
grep -A 3 '"imports"' package.jsonnpm ls lists @sveltejs/kit@3.4.0, svelte@5.58.0 and @sveltejs/adapter-node@6.0.5. vite.config.ts passes adapter: adapter() to the sveltekit() plugin, along with a runes compiler option that turns on Svelte 5 runes for your own files. The imports field in package.json maps #lib/* to ./src/lib/*. That is a standard Node.js subpath import, which Vite and TypeScript both understand, and it replaces the old $lib alias.
The project also has an .npmrc with engine-strict=true, so npm refuses to install on a Node.js older than SvelteKit 3 supports (22.17).
Step 2 · Add a layout and a second page
Start the dev server in your second terminal, from the sveltekit-guestbook-demo folder, and leave it running:
npm run devIt prints Local: http://localhost:5173/. Leave it running while you work: it picks up saved files on its own.
src/routes/+layout.svelte wraps every page. The page itself arrives as a snippet called children, and {@render children()} says where it goes. Replace the starter layout with one that adds navigation:
cat > src/routes/+layout.svelte <<'SVELTE'
<script lang="ts">
import favicon from '#lib/assets/favicon.svg';
import type { LayoutProps } from './$types';
let { children }: LayoutProps = $props();
</script>
<svelte:head>
<link rel="icon" href={favicon} />
</svelte:head>
<nav aria-label="Main">
<a href="/">Guestbook</a>
<a href="/about">About</a>
</nav>
<main>
{@render children()}
</main>
<style>
nav,
main {
max-width: 36rem;
margin: 0 auto;
padding: 1rem;
font-family: system-ui, sans-serif;
}
nav {
display: flex;
gap: 1rem;
}
</style>
SVELTE./$types is generated by SvelteKit for each route folder, so LayoutProps always matches what this layout really receives. The styles in a <style> block apply only to this component.
A new page is a new folder with a +page.svelte in it. src/routes/about/+page.svelte answers /about:
mkdir -p src/routes/about
cat > src/routes/about/+page.svelte <<'SVELTE'
<svelte:head>
<title>About · Guestbook</title>
</svelte:head>
<h1>About this guestbook</h1>
<p>Visitors leave their name and a short message. The server keeps entries in a JSON file.</p>
SVELTECheck it worked
curl -s http://localhost:5173/about | grep -o '<title>[^<]*</title>'
curl -s http://localhost:5173/about | grep -o 'aria-label="Main"'The first command prints <title>About · Guestbook</title> and the second prints aria-label="Main": the server sent the finished page, with the layout around it. In a browser, the Guestbook and About links switch pages without a full reload, because SvelteKit handles links to its own routes in the browser once its JavaScript has loaded. If the dev server ever answers 404 for a folder you have just created, stop it with Ctrl+C and start it again.
Step 3 · Load entries on the server
Code that touches files, databases or secrets must never reach the browser. In SvelteKit 3, any file inside a folder called server (outside src/routes), and any file with server as a segment of its name, is server-only: the build fails if browser code imports it. Put the guestbook storage in src/lib/server/guestbook.ts. A JSON file is enough to learn with:
mkdir -p src/lib/server
cat > src/lib/server/guestbook.ts <<'TS'
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
export type Entry = { id: string; name: string; message: string; createdAt: string };
const FILE = 'data/guestbook.json';
export async function listEntries(): Promise<Entry[]> {
try {
return JSON.parse(await readFile(FILE, 'utf8'));
} catch {
return [];
}
}
export async function getEntry(id: string) {
const entries = await listEntries();
return entries.find((entry) => entry.id === id) ?? null;
}
export async function addEntry(name: string, message: string) {
const entries = await listEntries();
const entry: Entry = {
id: randomUUID().slice(0, 8),
name,
message,
createdAt: new Date().toISOString()
};
await mkdir('data', { recursive: true });
await writeFile(FILE, JSON.stringify([entry, ...entries], null, 2));
return entry;
}
TSA load function in +page.server.ts runs on the server before its page renders, on the first visit and on every in-app navigation to it. What it returns reaches the page as data. Note the .ts at the end of the #lib import: SvelteKit 3 imports name the file:
cat > src/routes/+page.server.ts <<'TS'
import { listEntries } from '#lib/server/guestbook.ts';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
const entries = await listEntries();
return { entries };
};
TS
cat > src/routes/+page.svelte <<'SVELTE'
<script lang="ts">
import type { PageProps } from './$types';
let { data }: PageProps = $props();
</script>
<svelte:head>
<title>Guestbook</title>
</svelte:head>
<h1>Guestbook</h1>
<h2>{data.entries.length} {data.entries.length === 1 ? 'entry' : 'entries'}</h2>
{#if data.entries.length === 0}
<p>No entries yet. Be the first to sign.</p>
{:else}
<ul>
{#each data.entries as entry (entry.id)}
<li><a href="/entries/{entry.id}">{entry.name}</a>: {entry.message}</li>
{/each}
</ul>
{/if}
SVELTE
npm run checkdata is fully typed: hover over data.entries in your editor and it shows Entry[], taken from the return value of load. Whatever load returns is also serialised into the page so the browser can take over without asking again, so return only what the page shows.
Check it worked
npm run check ends by reporting 0 errors and 0 warnings. Then fetch the home page:
curl -s http://localhost:5173/ | grep -o 'No entries yet[^<]*'The output is No entries yet. Be the first to sign., rendered on the server from the data load returned.
Step 4 · Handle the form with an action and fail()
A +page.server.ts can also export actions. A form with method="POST" and no action attribute posts to its own page, which runs the default action. The action below reads the form, checks it, and does one of two things:
- If anything is wrong, it returns
fail(400, {...}). The page renders again with a 400 status, and what you pass tofailreaches the page as theformprop, so the reader sees the errors next to the values they typed. - If all is well, it saves the entry and calls
redirect(303, '/'). The browser then loads the home page with a GET, so refreshing it does not post the form a second time.
The name check counts characters and nothing else. Names such as Adébáyọ̀, Nkechi or Ngũgĩ, written in any script, must pass, so never limit a name field to the letters A to Z:
cat > src/routes/+page.server.ts <<'TS'
import { fail, redirect } from '@sveltejs/kit';
import { addEntry, listEntries } from '#lib/server/guestbook.ts';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
const entries = await listEntries();
return { entries };
};
export const actions = {
default: async ({ request }) => {
const form = await request.formData();
const name = String(form.get('name') ?? '').trim();
const message = String(form.get('message') ?? '').trim();
const errors: { name?: string; message?: string } = {};
if (name.length === 0) errors.name = 'Enter your name.';
else if (name.length > 60) errors.name = 'Keep your name to 60 characters or fewer.';
if (message.length < 2) errors.message = 'Write a message of at least 2 characters.';
else if (message.length > 280) errors.message = 'Keep your message to 280 characters or fewer.';
if (errors.name || errors.message) {
return fail(400, { name, message, errors });
}
await addEntry(name, message);
redirect(303, '/');
}
} satisfies Actions;
TSNow add the form to the page. Each error has an id, and the field points to it with aria-describedby, so a screen reader reads the error when the field gets focus:
cat > src/routes/+page.svelte <<'SVELTE'
<script lang="ts">
import type { PageProps } from './$types';
let { data, form }: PageProps = $props();
</script>
<svelte:head>
<title>Guestbook</title>
</svelte:head>
<h1>Guestbook</h1>
<form method="POST">
<label for="name">Your name</label>
<input
id="name"
name="name"
autocomplete="name"
value={form?.name ?? ''}
aria-invalid={form?.errors.name ? 'true' : undefined}
aria-describedby={form?.errors.name ? 'name-error' : undefined}
/>
{#if form?.errors.name}
<p id="name-error" class="error">{form.errors.name}</p>
{/if}
<label for="message">Message</label>
<textarea
id="message"
name="message"
rows="3"
value={form?.message ?? ''}
aria-invalid={form?.errors.message ? 'true' : undefined}
aria-describedby={form?.errors.message ? 'message-error' : undefined}
></textarea>
{#if form?.errors.message}
<p id="message-error" class="error">{form.errors.message}</p>
{/if}
<button>Sign the guestbook</button>
</form>
<h2>{data.entries.length} {data.entries.length === 1 ? 'entry' : 'entries'}</h2>
{#if data.entries.length === 0}
<p>No entries yet. Be the first to sign.</p>
{:else}
<ul>
{#each data.entries as entry (entry.id)}
<li><a href="/entries/{entry.id}">{entry.name}</a>: {entry.message}</li>
{/each}
</ul>
{/if}
<style>
form {
display: grid;
gap: 0.5rem;
margin-bottom: 2rem;
}
.error {
color: #b00020;
margin: 0;
}
</style>
SVELTE
npm run checkThe form has no required attributes, so you can watch the server check work. In your own forms add them as well for instant feedback, but keep the server check: anyone can post to the URL directly.
Check it worked
curl runs no JavaScript, so it posts as a browser does before the scripts load. Add the Accept: text/html header a browser sends with a form post: without it, SvelteKit answers with the JSON that use:enhance expects instead of a page. Post an empty form, then a short message, then a valid entry:
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'Accept: text/html' -d 'name=&message=' http://localhost:5173/
curl -s -X POST -H 'Accept: text/html' -d 'name=Ada&message=x' http://localhost:5173/ | grep -o 'Write a message of at least 2 characters\.'
curl -s -i -X POST -H 'Accept: text/html' --data-urlencode 'name=Adébáyọ̀' --data-urlencode 'message=Greetings from Ibadan' http://localhost:5173/ | grep -i '^location'
curl -s http://localhost:5173/ | grep -o 'Greetings from Ibadan'The first command prints 400. The second prints Write a message of at least 2 characters. The third prints location: /, the 303 redirect. The fourth prints Greetings from Ibadan, now in the list. In a browser at http://localhost:5173/, submit the empty form: the errors appear under each field and whatever you typed in the other field stays.
Step 5 · Give each entry its own page
Square brackets in a folder name make a URL parameter. src/routes/entries/[id]/ matches /entries/anything, and the load function reads the value as params.id. When no entry has that ID, error(404, ...) stops the load and SvelteKit renders the nearest +error.svelte with a real 404 status:
mkdir -p 'src/routes/entries/[id]'
cat > 'src/routes/entries/[id]/+page.server.ts' <<'TS'
import { error } from '@sveltejs/kit';
import { getEntry } from '#lib/server/guestbook.ts';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params }) => {
const entry = await getEntry(params.id);
if (!entry) {
error(404, 'No guestbook entry has that ID.');
}
return { entry };
};
TS
cat > 'src/routes/entries/[id]/+page.svelte' <<'SVELTE'
<script lang="ts">
import type { PageProps } from './$types';
let { data }: PageProps = $props();
</script>
<svelte:head>
<title>{data.entry.name} · Guestbook</title>
</svelte:head>
<article>
<h1>{data.entry.name}</h1>
<p>{data.entry.message}</p>
<p>Signed <time datetime={data.entry.createdAt}>{new Date(data.entry.createdAt).toUTCString()}</time></p>
</article>
<a href="/">Back to the guestbook</a>
SVELTEThe error page reads the status and message from page in $app/state, which replaces the $page store from SvelteKit 2. Placed at the top of src/routes, it renders inside the layout, so the navigation stays:
cat > src/routes/+error.svelte <<'SVELTE'
<script lang="ts">
import { page } from '$app/state';
</script>
<svelte:head>
<title>{page.status} · Guestbook</title>
</svelte:head>
<h1>{page.status === 404 ? 'Not found' : 'Something went wrong'}</h1>
<p>{page.error?.message}</p>
<a href="/">Back to the guestbook</a>
SVELTE
npm run checkCheck it worked
Read the ID of the entry you saved, open its page, then ask for one that does not exist:
ENTRY_ID=$(node -p "JSON.parse(require('node:fs').readFileSync('data/guestbook.json', 'utf8'))[0].id")
curl -s "http://localhost:5173/entries/$ENTRY_ID" | grep -o '<title>[^<]*</title>'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5173/entries/nope
curl -s http://localhost:5173/entries/nope | grep -o 'No guestbook entry has that ID\.'The first command prints <title>Adébáyọ̀ · Guestbook</title>. The second prints 404, and the third prints the message from error(). In a browser, the names in the home page list now link to these pages.
Step 6 · Enhance the form with use:enhance
The form works, but every submit reloads the whole page. use:enhance from $app/forms changes that once the JavaScript has loaded. It sends the same form data with fetch, then does what the browser would have done: on a fail() it updates form in place, on a redirect it navigates, and on success it resets the form and reloads the page's data. Without JavaScript, nothing changes: the form still posts normally.
Passing a function to use:enhance lets you run code around the submit. Here it sets a sending flag, so the button reads Signing... and cannot be pressed twice while the post is on its way, then calls update() to keep the default behaviour:
cat > src/routes/+page.svelte <<'SVELTE'
<script lang="ts">
import { enhance } from '$app/forms';
import type { PageProps } from './$types';
let { data, form }: PageProps = $props();
let sending = $state(false);
</script>
<svelte:head>
<title>Guestbook</title>
</svelte:head>
<h1>Guestbook</h1>
<form
method="POST"
use:enhance={() => {
sending = true;
return async ({ update }) => {
await update();
sending = false;
};
}}
>
<label for="name">Your name</label>
<input
id="name"
name="name"
autocomplete="name"
value={form?.name ?? ''}
aria-invalid={form?.errors.name ? 'true' : undefined}
aria-describedby={form?.errors.name ? 'name-error' : undefined}
/>
{#if form?.errors.name}
<p id="name-error" class="error">{form.errors.name}</p>
{/if}
<label for="message">Message</label>
<textarea
id="message"
name="message"
rows="3"
value={form?.message ?? ''}
aria-invalid={form?.errors.message ? 'true' : undefined}
aria-describedby={form?.errors.message ? 'message-error' : undefined}
></textarea>
{#if form?.errors.message}
<p id="message-error" class="error">{form.errors.message}</p>
{/if}
<button disabled={sending}>{sending ? 'Signing...' : 'Sign the guestbook'}</button>
</form>
<h2>{data.entries.length} {data.entries.length === 1 ? 'entry' : 'entries'}</h2>
{#if data.entries.length === 0}
<p>No entries yet. Be the first to sign.</p>
{:else}
<ul>
{#each data.entries as entry (entry.id)}
<li><a href="/entries/{entry.id}">{entry.name}</a>: {entry.message}</li>
{/each}
</ul>
{/if}
<style>
form {
display: grid;
gap: 0.5rem;
margin-bottom: 2rem;
}
.error {
color: #b00020;
margin: 0;
}
</style>
SVELTE
npm run checkSvelteKit 3 also has an experimental alternative to form actions, the form remote function. The SvelteKit documentation says form actions stay fully supported, so learn these first: the remote version builds on the same ideas.
Check it worked
An enhanced submit is a POST that asks for JSON. Send one yourself with an Accept header, first invalid, then valid:
curl -s -w '\n%{http_code}\n' -X POST -H 'Accept: application/json' -d 'name=&message=' http://localhost:5173/ | grep -o '"type":"failure"\|^400$'
curl -s -X POST -H 'Accept: application/json' --data-urlencode 'name=Wanjiru' --data-urlencode 'message=Hello from Nairobi' http://localhost:5173/ | grep -o '"type":"redirect"'The first command prints "type":"failure" and 400: in SvelteKit 3, the status of an enhanced response is the one you passed to fail(). The second prints "type":"redirect", which use:enhance turns into a client-side navigation. In a browser, open the developer tools, set network throttling to a slow preset such as 3G, and sign the guestbook: the button reads Signing..., the Network tab shows a fetch request rather than a page load, and the new entry appears in the list. Then switch JavaScript off in the developer tools settings, reload, and sign again: it still works, with a full page load.
Step 7 · Build with adapter-node and run it
Stop the dev server with Ctrl+C, then build:
npm run build
ls buildbuild/ is the whole production app: index.js starts the server, handler.js is the request handler, client/ holds the browser files and server/ the rendered routes. Start it in your second terminal:
ORIGIN=http://localhost:3000 node buildIt listens on port 3000 on all interfaces. Set PORT and HOST to change that, for example HOST=127.0.0.1 PORT=4000. ORIGIN matters for forms. In production SvelteKit rejects a form post whose Origin header does not match the app's own origin, which blocks cross-site request forgery. Without ORIGIN, adapter-node assumes https, so posts from http://localhost:3000 would be refused. Behind a reverse proxy, set ORIGIN to your public address, such as https://guestbook.example.com.
To run it on a server you need build/, package.json, the lock file and npm ci --omit dev. Entries live in data/guestbook.json in the folder you start the server from.
Check it worked
curl -s http://localhost:3000/ | grep -o 'Greetings from Ibadan'
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'Accept: text/html' -d 'name=Ama&message=No origin header' http://localhost:3000/
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'Accept: text/html' -H 'Origin: http://localhost:3000' -d 'name=Ama&message=Same origin' http://localhost:3000/The first command prints Greetings from Ibadan, served by the production build. The second prints 403: curl sends no Origin header, so the production server treats the post as cross-site. The dev server skips this check, which is why the earlier curl posts worked. The third sends the header a browser would send from your own page and prints 303. A browser at http://localhost:3000/ signs the guestbook as before.
Step 8 · Clean up
Stop the production server with Ctrl+C, then remove the project:
cd ~
rm -rf ~/sveltekit-guestbook-demoCheck it worked
ls ~/sveltekit-guestbook-demo reports No such file or directory, and curl http://localhost:3000/ fails to connect. Node.js stays installed.
Next steps
- Go deeper on the runes this tutorial used,
$stateand$props: learn Svelte 5 runes. - Compare the same loader, action and progressive form ideas in React: build a server-rendered app with React Router framework mode.
- Put the
node buildserver behind Nginx with HTTPS, and setORIGINto the public address: put Nginx in front of a Node.js app. - The SvelteKit documentation at svelte.dev covers hooks and cookies for sign-in, named actions for several forms on one page, and prerendering pages that never change.
Part of these paths
Related tutorials
- Learn Svelte 5 runes: $state, $derived and $effectYou will build a small Svelte 5 app with Vite, a tip calculator and a to-do list that saves itself, using $state, $derived, $effect and $props, snippets and shared state in a .svelte.js module, and you will know how each rune maps to the Svelte 4 code you meet in older projects.
- Build a server-rendered app with React Router framework modeYou will build a server-rendered notes app with React Router 8.5 framework mode, with file-based routes, server loaders and actions, a form that works before JavaScript loads, validation errors and page titles, and run its production build with react-router-serve on Node.js.
- How to Put Nginx in Front of a Node.js App as a Reverse ProxyYou will install Node.js 26, run a small app on a local port, and configure Nginx 1.30 to pass public traffic to it with the headers your app needs.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials