new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Svelte · SvelteKit · all subjects

file-based routing

34 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Page creation with file-based routing

Pages are created by adding Svelte component files to the src/routes directory. Each page of a SvelteKit app is a Svelte component. Pages are server-rendered on the user's first visit to the app for maximum speed, then a client-side app takes over.

Optional src directory contents

Everything in the src directory except src/routes and src/app.html is optional.

static directory assets

Any static assets that should be served without alteration to the name, such as robots.txt, go in the static/ directory. It is generally preferable to minimize the number of assets in static/ and instead import them to allow Vite's built-in handling to give a unique name to assets based on a hash of their contents for caching.

src/lib directory structure

The src/lib directory contains library code (utilities and components) that can be imported via the $lib alias. It includes a server subdirectory containing server-only library code that can be imported via the $lib/server alias. SvelteKit prevents importing $lib/server code in client code.

src/params directory

The src/params directory contains param matchers that the application needs for advanced routing.

src/routes directory

The src/routes directory contains the routes of the application. Other components that are only used within a single route can be colocated here.

app.html placeholders

The app.html file is the page template and contains the following placeholders: %sveltekit.head% for <link> and <script> elements needed by the app plus any <svelte:head> content; %sveltekit.body% for the markup of a rendered page (should live inside a <div> or other element, not directly inside <body>); %sveltekit.assets% for either paths.assets if specified or a relative path to paths.base; %sveltekit.nonce% for a CSP nonce for manually included links and scripts if used; %sveltekit.env.[NAME]% which is replaced at render time with the [NAME] environment variable that must begin with the publicPrefix (usually PUBLIC_) or be defined as a public variable in src/env if using experimental.explicitEnvironmentVariables (fallback to empty string); %sveltekit.version% for the app version specified with the version configuration.

error.html placeholders

The error.html file is the page rendered when everything else fails. It contains the following placeholders: %sveltekit.status% for the HTTP status and %sveltekit.error.message% for the error message.

Filesystem-based router root directory

src/routes is the root route in SvelteKit. This directory can be changed by editing the project config.

Server and client execution rules

All files can run on the server. All files run on the client except +server files. +layout and +error files apply to subdirectories as well as the directory they live in.

Route files identified by + prefix

Each route directory contains route files identified by their + prefix, such as +page.svelte, +layout.svelte, +server.js, and +error.svelte.

Creating routes with directory structure

Routes are created using directories: src/routes/about creates an /about route. src/routes/blog/[slug] creates a route with a parameter called slug that can be used to load data dynamically.

Unicode escape sequences in routes

Unicode characters can be encoded in route filenames using [u+nnnn] format where nnnn is a hex value between 0000 and 10ffff. For example, src/routes/[u+d83e][u+dd2a]/+page.svelte and src/routes/🤪/+page.svelte are equivalent. This is useful when the filesystem doesn't allow certain characters like emoji in filenames.

Matchers for route parameters

Matchers validate route parameters by checking if they match a specific pattern. Create a matcher in src/params/[name].js that exports a function with signature match(param: string): boolean or (param: string): param is Type. The matcher is then used in routes as [page=fruit] instead of [page]. Matchers run on both server and browser. Unit test files named *.test.js and *.spec.js in src/params are not treated as matchers.

Route sorting priority rules

When multiple routes match a path, SvelteKit sorts them by priority: (1) More specific routes (no parameters) are higher priority than dynamic parameters; (2) Parameters with matchers ([name=type]) are higher priority than without ([name]); (3) [[optional]] and [...rest] are lowest priority unless they are the final part of the route; (4) Ties are resolved alphabetically. Example: for /foo-abc, src/routes/foo-abc/+page.svelte takes priority over src/routes/foo-[c]/+page.svelte.

Hexadecimal character encoding in routes

Characters that cannot be used directly in route filenames can be encoded using [x+nn] format where nn is hexadecimal: \ is [x+5c], / is [x+2f], : is [x+3a], * is [x+2a], ? is [x+3f], " is [x+22], < is [x+3c], > is [x+3e], | is [x+7c], # is [x+23], % is [x+25], [ is [x+5b], ] is [x+5d], ( is [x+28], ) is [x+29]. For example, /smileys/:-)becomes src/routes/smileys/[x+3a]-[x+29]/+page.svelte. Get hex code with ':'.charCodeAt(0).toString(16).

Rest parameters syntax

Rest parameters use the syntax [...name] in route segments to match an unknown number of route segments. For example, src/routes/[org]/[repo]/tree/[branch]/[...file] would match /sveltejs/kit/tree/main/documentation/docs/04-advanced-routing.md and make the file parameter available as 'documentation/docs/04-advanced-routing.md'. The rest parameter matches zero or more segments.

Rest parameters match zero segments

A route like src/routes/a/[...rest]/z/+page.svelte will match /a/z (where rest is zero segments) as well as /a/b/z and /a/b/c/z. You must validate that the rest parameter value is valid, such as using a matcher.

Using rest parameters for 404 pages

To render a custom error page using a rest parameter, create a route like src/routes/marx-brothers/[...path]/+page.js that catches unmatched requests. In that page's load function, use error(404, 'Not Found') to trigger the 404 error page. A nested +error.svelte file will only render if a route was matched; rest parameters allow matching any path to trigger the error explicitly.

Optional parameters syntax

Optional route parameters are created by wrapping the parameter in double brackets: [[name]]. For example, [[lang]]/home creates a route that matches both home and en/home. An optional parameter cannot follow a rest parameter because parameters are matched greedily and the optional would always be unused.

Regex routes no longer supported

Regex routes are no longer supported in SvelteKit. Use advanced route matching instead.

Rename error and layout files

Rename _error.svelte to +error.svelte and _layout.svelte files to +layout.svelte. Any other files are ignored.

File routing structure changes

Routes are made up of the folder name exclusively. Folder names leading up to a +page.svelte correspond to the route. Old routes/about/index.svelte becomes routes/about/+page.svelte. Old routes/about.svelte becomes routes/about/+page.svelte.

RouteId type definition

The RouteId type is a union of all route IDs in your app. It is used for page.route.id and event.route.id. Example: type RouteId = '/' | '/my-route' | '/my-other-route/[param]';

Pathname type definition

The Pathname type is a union of all valid pathnames in your app. Example: type Pathname = '/' | '/my-route' | `/my-other-route/${string}` & {};

ResolvedPathname type definition

The ResolvedPathname type is similar to Pathname but possibly prefixed with a base path. It is used for page.url.pathname. Example: type ResolvedPathname = `${'' | `/${string}`}/` | `${'' | `/${string}`}/my-route` | `${'' | `/${string}`}/my-other-route/${string}` | {};

RouteParams utility type

RouteParams is a utility type for getting the parameters associated with a given route. It takes a route ID as a generic parameter. Example: type BlogParams = RouteParams<'/blog/[slug]'>; // { slug: string }. The type signature is: type RouteParams<T extends RouteId> = { /* generated */ } | Record<string, never>;

LayoutParams utility type

LayoutParams is a utility type for getting the parameters associated with a given layout, similar to RouteParams but also including optional parameters for any child route. The type signature is: type RouteParams<T extends RouteId> = { /* generated */ } | Record<string, never>;

ParamMatcher type

ParamMatcher is a function type for matching route parameters. Signature: ParamMatcher = (param: string) => boolean

$lib import alias automatically available

SvelteKit automatically makes files under src/lib available using the $lib import alias. Components and other modules in src/lib can be imported from any route using this alias.

$lib import example for component

A component at src/lib/Component.svelte can be imported in a route file using import Component from '$lib/Component.svelte'; and then used in the template.

$types import path

Generated types created by `svelte-kit sync` can be imported from `./$types` inside routing files.

Sapper uses filesystem-based routing

Sapper uses filesystem-based routing, popularised by Next.js and adopted by many other frameworks. The project's file structure mirrors the structure of the app itself.

OPTIONS method support in +server.js

The OPTIONS HTTP method is now supported in `+server.js` files for handling OPTIONS requests.

Give your agent this brain