How to understand a SvelteKit codebase
SvelteKit uses folders under `src/routes/` as URLs, and special `+` files decide what each folder does: `+page.svelte` renders, `+page.ts` or `+page.server.ts` loads data, `+server.ts` serves an endpoint. `hooks.server.ts` runs on every request.
How to tell it's SvelteKit
@sveltejs/kitinpackage.jsonandsvelte.config.jswith an adapter- Files named
+page.svelte,+layout.svelte,+page.server.tsand+server.ts - Imports from
$lib,$app/navigationor$env/static/private
Where things usually live
- src/routes/**/+page.svelte
- The page component.
- src/routes/**/+page.ts
- Universal
load: runs on the server first, then in the browser on navigation. - src/routes/**/+page.server.ts
- Server-only
loadand formactions. - src/routes/**/+server.ts
- API endpoints exporting
GET,POSTand so on. - src/hooks.server.ts
handleruns for every request: auth, sessions, headers.- src/lib/
- Shared code (
$lib);src/lib/server/can only be imported on the server. - svelte.config.js
- Adapter (Node, Vercel, static and others), aliases, preprocessors.
Conventions, not rules. Real projects rename and move things, so confirm against the repository.
Where to start reading
src/hooks.server.ts, because it affects every request- The route folder for the URL:
+page.server.tsfirst, then+page.svelte src/lib/server/, for database and secrets
How a request moves through the code
handleinhooks.server.tsruns, often populatingevent.localswith the user.- Layout and page
loadfunctions run, from the outermost layout inward. +page.sveltereceives the merged data as itsdataprop.- Form submissions hit
actionsin+page.server.ts;use:enhancemakes them work without a full reload. - Endpoints in
+server.tsserve fetch calls from the page or from outside.
Questions to ask about the repository
- What does
hooks.server.tsput onlocals, and which routes rely on it? - Which
loadfunctions run only on the server and which also in the browser? - Where are form actions defined, and how are they validated?
- Which adapter does this app deploy with?
What trips people up
+page.tscode also runs in the browser, so it must not touch secrets; that belongs in+page.server.ts.- Layout
loaddata is inherited by child pages, so a value can appear in a page without being loaded there. - Older SvelteKit code uses different file names (
__layout.svelte); check the version if names don't match.