Basic routing
Routes are created by adding files to thesrc/routes directory:
You can change
src/routes to a different directory by editing the project configuration.Route files
Each route directory contains one or more route files, which can be identified by their+ prefix.
Key routing rules
Server execution
All files can run on the server
Client execution
All files run on the client except
+server filesInheritance
+layout and +error files apply to subdirectoriesPage components
+page.svelte
A+page.svelte component defines a page of your app. By default, pages are rendered both on the server (SSR) for the initial request and in the browser (CSR) for subsequent navigation.
Receiving data
Pages can receive data fromload functions via the data prop:
Receiving params
As of SvelteKit 2.24, pages also receive aparams prop typed based on the route parameters:
Load functions
+page.js
Often, a page will need to load some data before it can be rendered. Add a+page.js module that exports a load function:
This function runs alongside
+page.svelte, which means it runs on the server during server-side rendering and in the browser during client-side navigation.+page.server.js
If yourload function can only run on the server — for example, if it needs to fetch data from a database or access private environment variables — rename +page.js to +page.server.js:
Layouts
+layout.svelte
To create a layout that applies to every page, make a file calledsrc/routes/+layout.svelte:
Nested layouts
Layouts can be nested. For example, create a layout that only applies to pages below/settings:
+layout.js
Your+layout.svelte component can get data from a load function in +layout.js:
Server routes
You can define routes with a+server.js file (API routes), which gives you full control over the response:
HTTP methods
Your+server.js file can export functions corresponding to HTTP verbs:
- GET
- POST
- Other methods
Error handling
+error.svelte
If an error occurs duringload, SvelteKit will render a default error page. Customize this error page on a per-route basis by adding an +error.svelte file:
SvelteKit will ‘walk up the tree’ looking for the closest error boundary. If no
+error.svelte file exists, it will try parent directories before rendering the default error page.Type safety
SvelteKit creates a$types.d.ts file for type safety when working with route files:
Next steps
Load functions
Learn how to load data for your pages
Form actions
Handle form submissions progressively