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

hooks

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

handle hook - server only

The handle hook runs every time the SvelteKit server receives a request, whether during app runtime or prerendering. It receives an event object and a resolve function, allowing modification of response headers or bodies, or bypassing SvelteKit entirely. If unimplemented, it defaults to ({ event, resolve }) => resolve(event). Requests for static assets are not handled by SvelteKit.

Hooks files location

There are three hooks files, all optional: src/hooks.server.js for server hooks, src/hooks.client.js for client hooks, and src/hooks.js for hooks that run on both client and server. Code in these modules runs when the application starts up, making them useful for initializing database clients.

handle hook - resolve parameter

The resolve function in handle accepts a second optional parameter object with the following fields: transformPageChunk(opts: { html: string, done: boolean }): MaybePromise<string | undefined> applies custom transforms to HTML; filterSerializedResponseHeaders(name: string, value: string): boolean determines which headers are included in serialized responses when a load function loads a resource with fetch; preload(input: { type: 'js' | 'css' | 'font' | 'asset', path: string }): boolean determines which files should be preloaded via <link> tags or Link response header.

handle hook - remote function behavior

When the handle hook runs as part of a remote function request, route, params and url relate to the page the remote function was called from, not the endpoint URL. These should not be used to determine authorization as they can be manipulated. Queries are not re-run on navigation unless the argument changes.

handle hook - prerendering

During prerendering, SvelteKit crawls pages for links and renders each route found, invoking the handle function and all route dependencies like load. To exclude code from running during prerendering, check that the app is not building beforehand.

handle hook - error handling

resolve(...) will never throw an error and always returns Promise<Response> with the appropriate status code. If an error is thrown elsewhere during handle, it is treated as fatal and SvelteKit responds with a JSON error representation or fallback error page depending on the Accept header. The fallback error page can be customized via src/error.html.

event.locals for custom data

To add custom data to requests passed to handlers in +server.js and server load functions, populate the event.locals object in the handle hook. Custom types should be declared in App.Locals interface.

event.locals response header caveats

When modifying response headers in handle, note that Response objects can have immutable headers (e.g. from Response.redirect()). Modifying immutable headers throws a TypeError. In such cases, clone the response or avoid creating a response object with immutable headers.

handleFetch hook

The handleFetch hook allows modification or replacement of event.fetch calls on the server or during prerendering inside endpoint, load, action, handle, handleError or reroute. It receives request and fetch parameters.

handleFetch - credentials model

Requests made with event.fetch follow the browser's credentials model: for same-origin requests, cookie and authorization headers are forwarded unless credentials option is set to omit. For cross-origin requests, cookie is included if the request URL belongs to a subdomain of the app.

handleFetch - sibling subdomains caveat

When the app and API are on sibling subdomains like www.my-domain.com and api.my-domain.com, a cookie belonging to the common parent domain will not be included because SvelteKit cannot determine which domain owns the cookie. Manually include the cookie using handleFetch in this case.

handleValidationError hook

The handleValidationError hook is called when a remote function is called with an argument that does not match the provided Standard Schema. It must return an object matching the shape of App.Error. It receives issues parameter and is useful for customizing error messages for validation failures.

handleError hook - server and client

The handleError hook can be added to src/hooks.server.js (type HandleServerError) or src/hooks.client.js (type HandleClientError). It is called when an unexpected error is thrown during loading, rendering, or from an endpoint. It receives error, event, status code and message parameters. In client hooks, event is a NavigationEvent rather than RequestEvent.

handleError hook behavior

The handleError hook allows logging errors and generating custom error representations safe to show users. For errors from user code, status is 500 and message is 'Internal Error'. The returned value (defaults to { message }) becomes the value of page.error. This hook is not called for expected errors thrown with the error function from @sveltejs/kit.

handleError - custom error shape

To add more information to the page.error object in a type-safe way, declare an App.Error interface which must include message: string. This allows appending additional properties like tracking IDs for user support reference.

handleError - error message safety

error.message may contain sensitive information that should not be exposed to users, while the message parameter is safe (though possibly meaningless). Use message rather than error.message when constructing responses to users.

handleError must never throw

Make sure that handleError never throws an error. Throwing from handleError will cause additional problems.

handleError - development syntax errors

During development, if an error occurs because of a syntax error in Svelte code, the passed in error has a frame property appended highlighting the location of the error.

init hook - server and client

The init hook can be added to src/hooks.server.js or src/hooks.client.js. It runs once when the server is created or the app starts in the browser. It is useful for asynchronous work such as initializing database connections.

init hook - top-level await

If the environment supports top-level await, the init function is no different from writing initialization logic at the top level of the module. However, some environments like Safari do not support this, making init necessary.

init hook - browser hydration delay

In the browser, asynchronous work in init will delay hydration, so be mindful of what is placed in there to avoid slow page loads.

reroute hook

The reroute hook can be added to src/hooks.js and runs on both server and client. It runs before handle and allows changing how URLs are translated into routes. The returned pathname (defaults to url.pathname) is used to select the route and its parameters. The hook does not change the browser's address bar or event.url value.

reroute hook - asynchronous support

Since version 2.18, the reroute hook can be asynchronous, allowing fetching data from the backend to decide rerouting. It receives a fetch parameter with the same benefits as fetch in load functions, with the caveat that params and id are unavailable to handleFetch because the route is not yet known.

reroute hook - purity requirement

The reroute hook is considered a pure, idempotent function. It must always return the same output for the same input and not have side effects. SvelteKit caches the result on the client so it is only called once per unique URL.

transport hook

The transport hook can be added to src/hooks.js and runs on both server and client. It is a collection of transporters that allow passing custom types returned from load and form actions across the server/client boundary. Each transporter contains an encode function (encodes values on server or returns falsy for non-matching types) and a corresponding decode function.

Auth cookies and server hooks integration

Auth cookies can be checked inside server hooks. If a user is found matching the provided credentials, the user information can be stored in locals.

afterNavigate hook for custom focus management

The afterNavigate hook imported from $app/navigation can be used to implement custom focus management logic. It allows you to programmatically focus specific elements after navigation occurs, enabling you to override SvelteKit's default focus-to-body behavior.

Improved error handling in v2 with handleError hook

In SvelteKit 2, the handleError hook receives two new properties: status and message. For errors thrown from your code, status will be 500 and message will be 'Internal Error'. The message property is safe to expose to users, while error.message may contain sensitive information.

Load function signature changes

The load function no longer has a this object, so this.fetch, this.error and this.redirect are not available. Instead, get fetch from the input methods, and both error and redirect are now thrown.

Preload function renamed to load

The preload function has been renamed to load. It now lives in a +page.js or +layout.js next to its +page.svelte or +layout.svelte. Its API has changed from two arguments (page and session) to a single event argument.

sequence preload behavior

In the sequence helper, preload options are applied in forward order, with the first defined preload option winning and no subsequent preload options being called.

defineEnvVars is deprecated

defineEnvVars is deprecated and should not be imported from @sveltejs/kit/hooks. Instead, import it from @sveltejs/kit/env.

sequence filterSerializedResponseHeaders behavior

In the sequence helper, filterSerializedResponseHeaders behaves the same as preload: it is applied in forward order, with the first defined option winning and no subsequent options being called.

sequence execution order example

When using sequence(first, second), the execution order is: first pre-processing, first preload (wins), second pre-processing, second filterSerializedResponseHeaders (wins), second transform, first transform, second post-processing, first post-processing.

sequence helper function

The sequence function from @sveltejs/kit/hooks is a helper for sequencing multiple handle calls in a middleware-like manner. It accepts multiple Handle functions and returns a single Handle. The signature is: function sequence(...handlers: Handle[]): Handle.

sequence transformPageChunk behavior

In the sequence helper, transformPageChunk options are applied in reverse order and merged. This means the last handle's transformPageChunk is applied first.

HandleValidationError hook signature

The HandleValidationError hook runs when the argument to a remote function fails validation. It receives issues array and event, and must return an object shape matching App.Error. Signature: HandleValidationError<Issue extends StandardSchemaV1.Issue = StandardSchemaV1.Issue> = (input: { issues: Issue[]; event: RequestEvent; }) => MaybePromise<App.Error>

HttpError interface

HttpError is the object returned by error(). It has status (number in range 400-599) and body (App.Error) properties.

BeforeNavigate cancel method

The BeforeNavigate callback parameter is a Navigation with a cancel() method that prevents the navigation from starting.

RequestEvent locals property

RequestEvent has locals property of type App.Locals that contains custom data added to the request within the server handle hook.

Reroute hook signature

Reroute hook (available since 2.3.0) has signature type Reroute = (event: {url: URL; fetch: typeof fetch}) => MaybePromise<void | string>. It allows modifying the URL before it is used to determine which route to render.

ServerInit hook type and purpose

ServerInit type (available since 2.10.0) has signature type ServerInit = () => MaybePromise<void>. The init hook is invoked before the server responds to its first request.

ServerInitOptions interface

ServerInitOptions has properties: env: Record<string, string> (map of environment variables), read?: (file: string) => MaybePromise<ReadableStream | null> (function turning asset filename into ReadableStream, required for read export from $app/server to work).

ClientInit hook type

ClientInit is invoked once the app starts in the browser. Available since 2.10.0. Signature: ClientInit = () => MaybePromise<void>

error() function signature and behavior

The error() function throws an HTTP error with a status code. It accepts a status number and an optional body. When called during request handling, it causes SvelteKit to return an error response without invoking handleError. The thrown error must not be caught, as catching it would prevent SvelteKit from handling it. Signature: error(status: number, body: App.Error): never

isHttpError() checks for HTTP errors

The isHttpError() function checks whether a value is an error thrown by error(). It can optionally check for a specific status code. Signature: isHttpError<T extends number>(e: unknown, status?: T): e is HttpError_1 & { status: T extends undefined ? never : T; }

Handle hook signature

The Handle hook runs every time the SvelteKit server receives a request and determines the response. It receives an event object and a resolve function. Signature: Handle = (input: { event: RequestEvent; resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response> }) => MaybePromise<Response>

HandleFetch hook signature

The HandleFetch hook allows modifying or replacing the result of event.fetch calls on the server or during prerendering. It runs inside endpoints, load, action, handle, handleError or reroute. Signature: HandleFetch = (input: { event: RequestEvent; request: Request; fetch: typeof fetch }) => MaybePromise<Response>

HandleServerError hook signature

The server-side HandleServerError hook runs when an unexpected error is thrown while responding to a request. It receives error, event, status, and message. Must never throw. Signature: HandleServerError = (input: { error: unknown; event: RequestEvent; status: number; message: string; }) => MaybePromise<void | App.Error>

Transport hook for custom types

Transport hook (available since 2.11.0) allows transporting custom types across server/client boundary. Type signature: type Transport = Record<string, Transporter>. Each transporter has encode and decode pair. On server, encode determines if value is custom type instance and returns non-falsy encoding (object or array, or false). In browser, decode turns encoding back into custom type instance.

Transporter interface structure

Transporter interface has: encode: (value: T) => false | U (determines if value is custom type and returns encoding), decode: (data: U) => T (turns encoding back into custom type instance).

$service-worker version constant

The version constant is a string that corresponds to config.kit.version. It is useful for generating unique cache names inside a service worker, so that a later deployment of the app can invalidate old caches.

$service-worker files constant

The files constant is an array of URL strings representing the files in the static directory, or whatever directory is specified by config.kit.files.assets. Which files are included from the static directory can be customized using config.kit.serviceWorker.files.

$service-worker prerendered constant

The prerendered constant is an array of pathnames corresponding to prerendered pages and endpoints. During development, this is an empty array.

$service-worker build constant

The build constant is an array of URL strings representing the files generated by Vite, suitable for caching with cache.addAll(build). During development, this is an empty array.

$service-worker base constant

The base constant is a string representing the base path of the deployment. It is typically equivalent to config.kit.paths.base, but is calculated from location.pathname so it continues to work correctly if the site is deployed to a subdirectory. There is a base constant but no assets constant, since service workers cannot be used if config.kit.paths.assets is specified.

$service-worker module overview

The $service-worker module provides constants that are only available to service workers. It can be imported with: import { base, build, files, prerendered, version } from '$service-worker';

Locals interface defines event.locals

The Locals interface defines the shape of event.locals, which can be accessed in server hooks (handle and handleError), server-only load functions, and +server.js files.

Give your agent this brain