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

routing

150 notes in this subject, read out of this brain and free to use. This is page 1 of 3.

SvelteKit provides routing

SvelteKit includes a router that updates your UI when a link is clicked, providing basic routing functionality for web applications.

+layout.server.js server-only layout load

+layout.server.js is used to run a layout's load function on the server only. Change the LayoutLoad type to LayoutServerLoad.

+page.svelte receives data and params props

Pages receive data from load functions via the data prop. As of 2.24, pages also receive a params prop which is typed based on route parameters.

IDE type inference for $types

When using VS Code or any IDE that supports the language server protocol and TypeScript plugins, you can omit $types imports entirely. Svelte's IDE tooling will insert the correct types automatically. This also works with the svelte-check command line tool.

+server.js error handling

If an error is thrown in +server.js (either error(...) or an unexpected error), the response will be a JSON representation of the error or a fallback error page depending on the Accept header. The +error.svelte component will not be rendered in this case.

+server.js API routes and HTTP handlers

A +server.js file defines routes with full control over the response. It exports functions corresponding to HTTP verbs like GET, POST, PATCH, PUT, DELETE, OPTIONS, and HEAD that take a RequestEvent argument and return a Response object.

+layout files no effect on +server.js

+layout files have no effect on +server.js files. To run logic before each request, add it to the server handle hook.

+layout.js load function

+layout.js exports a load function that populates data for the +layout.svelte component. Data returned from a layout's load function is also available to all its child pages.

+page.js load function

+page.js exports a load function that runs alongside +page.svelte. It runs on the server during server-side rendering and in the browser during client-side navigation.

Form actions preferred over +server.js for data submission

Form actions are a better way to submit data from the browser to the server than using +server.js POST handlers.

Nested layouts inheritance

Layouts can be nested. A nested layout inherits the layout above it and applies only to pages below that directory.

+error.svelte accesses error info

An +error.svelte component can access error information from $app/state, which was added in SvelteKit 2.12. In earlier versions or with Svelte 4, use $app/stores instead.

+server.js streaming and server-sent events

+server.js can accept a ReadableStream as the first argument to Response, making it possible to stream large amounts of data or create server-sent events (unless deploying to platforms that buffer responses, like AWS Lambda).

+error.svelte custom error pages

An +error.svelte file customizes error pages on a per-route basis. When an error occurs, SvelteKit walks up the tree looking for the closest error boundary. If no +error.svelte exists in nested routes, it tries parent routes until reaching src/routes/+error.svelte or the default error page.

Colocating components and modules with routes

Any files inside a route directory that are not route files are ignored by SvelteKit, allowing components and utility modules to be colocated with the routes that need them. For components needed by multiple routes, use $lib instead.

OPTIONS handler Access-Control headers injection

When creating an OPTIONS handler, Vite will inject Access-Control-Allow-Origin and Access-Control-Allow-Methods headers. These will not be present in production unless you add them.

+layout.js page options as defaults

If +layout.js exports page options (prerender, ssr, csr), they will be used as defaults for child pages.

Using <a> for navigation between routes

SvelteKit uses <a> elements to navigate between routes, rather than a framework-specific <Link> component.

+server.js HEAD request handling

If a GET handler is exported, a HEAD request will return the content-length of the GET handler's response body. For HEAD requests, the GET handler takes precedence over the fallback handler.

PageProps and LayoutProps type shortcuts

PageProps and LayoutProps are shortcuts for typing multiple props. PageProps includes data and form props. LayoutProps includes data and children props. These were added in version 2.16.0.

$types auto-generated type definitions

SvelteKit creates a $types.d.ts file in a hidden directory to provide type safety when using TypeScript or JavaScript with JSDoc type annotations. This file provides types like PageProps, LayoutProps, PageLoad, PageServerLoad, LayoutLoad, and LayoutServerLoad.

+layout.svelte receives children and data props

A +layout.svelte component receives a children prop (used with @render) and can receive data from +layout.js or +layout.server.js via the data prop when typed with LayoutProps.

Content negotiation for +page and +server

+server.js files can be placed in the same directory as +page files. PUT/PATCH/DELETE/OPTIONS requests are always handled by +server.js. GET/POST/HEAD requests are treated as page requests if the accept header prioritizes text/html, else they are handled by +server.js. GET responses include a Vary: Accept header.

+error.svelte fallback behavior

If an error occurs in a load function of the root +layout, SvelteKit renders a static fallback error page which can be customized by creating src/error.html. The +error.svelte component is not used when an error occurs inside handle or a +server.js request handler.

Component preservation during navigation

When navigating from page A to B, SvelteKit preserves the components that are common to both pages.

+server.js fallback handler for unhandled methods

Exporting a fallback handler in +server.js will match any unhandled request methods, including methods like MOVE which have no dedicated export.

+page.js page options exports

+page.js can export prerender (true, false, or 'auto'), ssr (true or false), and csr (true or false) to configure the page's behaviour.

+layout.svelte shared layout component

A +layout.svelte component applies to every page and can contain markup, styles, and behavior that should be visible on all pages. It must include a @render tag for the page content.

+page.server.js server-only load functions

+page.server.js is used when a load function can only run on the server, such as when fetching from a database or accessing private environment variables. The load function type changes from PageLoad to PageServerLoad. During client-side navigation, the returned value must be serializable using devalue.

getRequestEvent() retrieves event object in server functions

The getRequestEvent() function from $app/server retrieves the event object passed to server load functions. This allows shared logic like authentication guards to access information about the current request without needing it passed around. getRequestEvent() is available in server load functions and form actions.

Server load and page load run concurrently unless await parent() called

Layout and page load functions run concurrently unless await parent() is called. If using both +page.server.js and +page.js on the same page, the server load runs first, and the universal load can access its return value via the data property of its argument.

Layout load functions do not run on every request during client-side navigation

Layout load functions do not run on every request, such as during client-side navigation between child routes. This has implications for authentication checks. If a layout load throws during concurrent execution with a page load, the page load still runs but the client will not receive the returned data.

Rerunning load does not recreate component or reset state

When a load function reruns, it updates the data prop in the corresponding +layout.svelte or +page.svelte component, but does not cause the component to be recreated. Internal component state is preserved. To reset state, use an afterNavigate callback or wrap the component in a {#key ...} block.

Load functions rerun when params or url properties change

A load function will rerun if it references a property of params or url whose value changed. For url, properties like pathname and search trigger reruns. Properties in request.url are not tracked. Search parameters are tracked independently from the rest of the url.

invalidateAll() reruns every load function

The invalidateAll() function from $app/navigation reruns every active load function for the current page. This can be called from components or event handlers to force data refresh.

invalidate(url) reruns load functions depending on URL

The invalidate(url) function from $app/navigation reruns all load functions that depend on the given URL. A load function depends on a URL if it calls fetch(url) or depends(url). The url parameter can be a custom identifier starting with [a-z]: like 'app:random'.

Load functions rerun based on dependency tracking

SvelteKit tracks dependencies of each load function to avoid unnecessary reruns during navigation. A load function reruns if it references a property of params or url whose value changed, calls await parent() and a parent load reran, depends on a URL via fetch or depends() that was invalidated, or all load functions are forcibly rerun with invalidateAll(). Dependency tracking does not apply after the load function returns.

SvelteKit runs all load functions concurrently

When rendering or navigating to a page, SvelteKit runs all load functions concurrently, avoiding a waterfall of requests. During client-side navigation, results from multiple server load functions are grouped into a single response. The page renders once all load functions have returned.

Cannot setHeaders or redirect inside streamed promises

Once a response has started streaming, the headers and status code cannot be changed. Therefore you cannot call setHeaders or throw redirects inside a streamed promise.

+page.js load function returns data to page

A +page.svelte file can have a sibling +page.js file that exports a load function. The return value of this load function is available to the page component via the data prop. The load function receives parameters like params, and can return an object containing any data needed by the page.

redirect() helper throws to redirect users in load

The redirect() helper from @sveltejs/kit can be called in load functions to redirect users to another location. Use redirect(code, location) where code is a 3xx status code. Calling redirect() throws an exception making it easy to stop execution. Do not use redirect() inside a try block as it will immediately trigger the catch statement.

error() helper throws for expected errors in load

The error() helper from @sveltejs/kit can be called in load functions to specify an HTTP status code and optional message for expected errors. Calling error() throws an exception, stopping execution. This will render the nearest +error.svelte component. Use error(code, message) where code is the HTTP status code.

parent() function accesses parent load function data

A load function can call await parent() to access data from parent load functions. In +page.server.js and +layout.server.js, parent() returns data from parent +layout.server.js files. In +page.js or +layout.js, parent() returns data from parent +layout.js files, and also from parent +layout.server.js files that are not shadowed by a +layout.js file.

setHeaders function sets response headers during SSR

Both server and universal load functions have access to a setHeaders function that sets HTTP response headers when running on the server. This has no effect when running in the browser. Setting the same header multiple times is an error. The set-cookie header cannot be set with setHeaders; use cookies.set(name, value, options) instead.

Server load functions can get and set cookies

A server load function can access cookies via the cookies parameter, using cookies.get(name) to retrieve a cookie value. Cookies will only be passed through the provided fetch function if the target host is the same as the SvelteKit application or a more specific subdomain of it.

Streaming promises require noop catch to handle rejections

When streaming data with promises in server load functions, attach a noop catch handler to any manual promises to mark them as handled and prevent unhandled promise rejection errors. SvelteKit's fetch automatically handles this case. Syntax: promise.catch(() => {}).

fetch function in load has enhanced features over native fetch

The fetch function provided to load functions behaves identically to native fetch with enhancements: it can make credentialed requests on the server inheriting cookie and authorization headers, make relative requests on the server, make internal requests to +server.js routes directly without HTTP overhead, and during SSR the response is captured and inlined into rendered HTML by hooking into text, json, and arrayBuffer methods. During hydration the response is read from HTML guaranteeing consistency.

params derived from url.pathname and route.id

The params object passed to load functions is derived from url.pathname and route.id. For a route.id of '/a/[b]/[...c]' and url.pathname of '/a/x/y/z', the params object would be {"b": "x", "c": "y/z"}.

route parameter contains route directory name relative to src/routes

The route parameter passed to load functions contains the name of the current route directory relative to src/routes. For example, a route at src/routes/a/[b]/[...c]/+page.js would have route.id equal to '/a/[b]/[...c]'.

untrack() excludes values from dependency tracking

The untrack() function provided to load functions allows excluding specific values from the dependency tracking mechanism. For example, untrack(() => url.pathname === '/') will not cause the load function to rerun when pathname changes.

url parameter in load function is URL instance

The url parameter provided to load functions is an instance of URL containing properties like origin, hostname, pathname, and searchParams (a URLSearchParams object). url.hash cannot be accessed during load since it is unavailable on the server.

Server load functions must return devalue-serializable data

A server load function must return data that can be serialized with devalue. This includes anything representable as JSON plus BigInt, Date, Map, Set, RegExp, and repeated/cyclical references. Data can include promises which will be streamed to browsers. Universal load functions can return any values including custom classes and component constructors.

Universal load functions receive LoadEvent, server load functions receive ServerLoadEvent

Both universal and server load functions have access to properties describing the request: params, route, and url, plus functions: fetch, setHeaders, parent, depends, and untrack. Server load functions additionally receive ServerLoadEvent which inherits clientAddress, cookies, locals, platform, and request from RequestEvent. Universal load functions receive a LoadEvent which has a data property containing the return value of the server load function if both exist.

Accessing url.searchParams.get() makes load depend on that parameter

If a load function calls url.searchParams.get(name), url.searchParams.getAll(name), or url.searchParams.has(name), the load function will rerun when that specific search parameter changes. Accessing other properties of url.searchParams has the same effect as accessing url.search.

page.data provides access to all data in current route hierarchy

The page.data property is available in any +layout.svelte or +page.svelte component and contains merged data from all load functions in the current route hierarchy. This allows a parent layout to access data returned from child page load functions using page.data.

+layout.js and +layout.server.js can define load functions for layouts

Layout components can load data via +layout.js or +layout.server.js files. Data returned from layout load functions is available to child layout and page components. When multiple load functions return data with the same key, the last one wins.

+page.js runs on server and browser, +page.server.js runs only on server

A load function in +page.js runs both on the server during SSR and in the browser, unless ssr is disabled. A load function in +page.server.js always runs only on the server. Use +page.server.js when you need to access private environment variables or a database.

Both server and universal load receive load function in +page.server.js and +page.js

If both +page.server.js and +page.js exist for the same route, the server load function runs first. The universal load function can access the server load function's return value via the data property of its LoadEvent argument. The universal load then returns merged data.

PageLoad type annotation for universal load functions

Universal load functions in +page.js are typed as PageLoad. Server load functions in +page.server.js are typed as PageServerLoad. The generated $types module provides full type safety for load function signatures and return data.

depends() marks load as dependent on custom URL identifier

The depends(url) function can be called in a load function to mark it as dependent on a custom URL identifier. This allows rerunning the load with invalidate(url). The url can be a custom identifier starting with [a-z]: like 'app:random'.

Give your agent this brain