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

features

212 notes in this subject, read out of this brain and free to use. This is page 2 of 4.

form field rendering with .as() method

A form is composed of fields defined by the schema. To get attributes for a field, call its .as(...) method, specifying which input type to use. For most input types, you can also pass a second argument .as(type, value) to control the rendered value. The .as() method sets the correct input type, name, value population, and aria-invalid state.

form field naming and type coercion

The generated name attribute uses JS object notation (e.g. nested.array[0].value). String keys that require quotes such as object['nested-array'][0].value are not supported. Boolean checkbox and number field names are prefixed with b: and n: respectively to signal SvelteKit to coerce values from strings prior to validation.

form field nesting and value types

Fields can be nested in objects and arrays, and their values can be strings, numbers, booleans, or File objects. Nested objects and arrays are supported in the schema structure.

form file input handling

When a form contains file inputs, add an enctype="multipart/form-data" attribute to the form element. File inputs cannot be populated with default values via the second argument to .as().

form checkbox input handling

If a checkbox input is unchecked, the value is not included in the FormData object. Therefore, the value must be made optional in the schema. In Valibot use v.optional(v.boolean(), false), while in Zod use z.coerce.boolean<boolean>().

form radio and checkbox value binding

For radio and checkbox inputs that all belong to the same field, the value must be specified as a second argument to .as(...). Use .as('radio', value) or .as('checkbox', value) to bind specific values to individual inputs.

form select and select multiple inputs

Alternative to radio and checkbox groups, you can use select and select multiple inputs. Use .as('select') for single selection and .as('select multiple') for multiple selections.

form select no-selection handling

If no selections are made in a select or select multiple input, the data will be undefined. For this reason, make the field optional in the schema, such as v.optional(v.array(...), []).

form programmatic validation with invalid helper

In addition to declarative schema validation, you can programmatically mark fields as invalid using the invalid helper from @sveltejs/kit. It throws like redirect or error and accepts multiple arguments that can be strings (for form-level issues) or standard-schema-compliant issues (for field-specific issues). Use the issue parameter for type-safe creation of such issues.

form validation error handling

If submitted data doesn't pass the schema validation, the callback will not run. Each invalid field's issues() method returns an array of { message: string } objects, and the aria-invalid attribute is set to true.

form programmatic validation with validate()

You can call validate() programmatically on a form to validate data without waiting for submission. This is useful for oninput callbacks (validating on every keystroke) or onchange callbacks. By default, issues are ignored for form controls that haven't been interacted with. Call validate({ includeUntouched: true }) to validate all inputs.

form client-side preflight validation

For client-side validation, specify a preflight schema by calling createPost.preflight(schema). This will populate issues() and prevent data from being sent to the server if validation fails. The preflight schema can be the same object as the server-side schema, though it won't be able to do server-side checks.

form schema export location

You cannot export a schema from a .remote.ts or .remote.js file. The schema must either be exported from a shared module or from a <script module> block in the component containing the <form>.

form field all issues with fields.allIssues()

To get a list of all issues rather than those belonging to a single field, use the fields.allIssues() method. This will return undefined if the form is valid or has not yet been validated.

form field value access with value() method

Each field has a value() method that reflects its current value. As the user interacts with the form, it is automatically updated. Alternatively, fields.value() returns an object with all field values.

form field default values behavior

The value() of a field does not reflect defaults provided as a second argument to .as() (as in fields.title.as('text', '...')) until it is edited or submitted.

form field programmatic updates with set()

You can programmatically update a field or collection of fields via the set(...) method. Both createPost.fields.set({ title: '...', content: '...' }) and individual field updates like createPost.fields.title.set('...') are supported.

form sensitive data handling with underscore prefix

Prevent sensitive data (such as passwords and credit card numbers) from being sent back to the user by using a field name with a leading underscore. When form data is invalid and the page reloads, fields with underscore-prefixed names will not be populated with their submitted values.

form result property for return values

The form callback can return data, which is available as createPost.result. This value is ephemeral — it will vanish if you resubmit, navigate away, or reload the page. The result value need not indicate success and can also contain validation errors and data for repopulating the form on page reload.

form redirect handling

Instead of returning data, the form callback can use the redirect(...) function to send the user to a new page. This sends a redirect response to the client.

form error handling during submission

If an error occurs during form submission, the nearest +error.svelte page will be rendered.

form enhance method for customization

You can customize what happens when the form is submitted using the enhance method. It receives a copy of the form instance with the same properties and methods except enhance. Call form.submit() to perform the submission directly without re-running the enhance callback. Inside the callback, form.element is always defined.

Service worker update checking behavior

Browsers check for an updated service worker when a full-page navigation happens within its scope and after functional events such as push and sync. Client-side navigations do not trigger checks, so navigating around the app will not cause a new deployment's service worker to be picked up.

SvelteKit service worker update error recovery

SvelteKit calls registration.update() only as part of error recovery. If a route module fails to load or a navigation results in an error status, and version polling detects that the app has been redeployed, the service worker is updated before SvelteKit falls back to a full-page navigation.

Manual service worker registration

You can disable automatic service worker registration in configuration and register the service worker with your own logic.

Triggering service worker update check

You can trigger a service worker update check using navigator.serviceWorker.getRegistration() and calling update() on the returned registration. This does not immediately activate a new service worker; instead it installs in the background and takes over when the number of tabs managed by the existing service worker drops to zero.

Service worker caching considerations

Be careful when caching in service workers. In some cases, stale data might be worse than data unavailable while offline. Browsers will empty caches if they get too full, so you should be careful about caching large assets like video files.

Service worker file location

In SvelteKit, if you have a src/service-worker.js file or src/service-worker/index.js file, it will be bundled and automatically registered.

$service-worker module exports

The $service-worker module provides access to: build (the app files), files (everything in static), version (an app version string for creating unique cache names), and base (the deployment's base path). If Vite config specifies define for global variable replacements, this will be applied to service workers.

Service worker automatic registration default

The default automatic registration checks if serviceWorker exists in navigator, then on the load event registers the service worker at ./path/to/service-worker.js with type 'module' in development and 'classic' in production.

Service worker bundling behavior

The service worker is bundled for production but not during development. build and prerendered are empty arrays during development.

Creating server-only modules with .server filename

A module can be made server-only by adding .server to the filename, for example secrets.server.js.

Creating server-only modules in $lib/server directory

A module can be made server-only by placing it in $lib/server, for example $lib/server/secrets.js.

SvelteKit prevents import chains that leak server-only code to browser

SvelteKit errors when public-facing code imports from server-only modules, even indirectly through intermediate modules. This prevents server-only code from ending up in JavaScript downloaded by the browser. The error message traces the import chain and explains the security risk. This check applies even when the public-facing code only uses non-secret exports from the intermediate module.

Server-only modules prevent sensitive data leaks

SvelteKit prevents accidental imports of sensitive data into front-end code through server-only modules. This ensures that backend secrets cannot be bundled into JavaScript downloaded by browsers.

$env/static/private and $env/dynamic/private import restrictions

The $env/static/private and $env/dynamic/private modules can only be imported into modules that only run on the server, such as hooks.server.js or +page.server.js.

Type-only imports do not trigger server-only module errors

Importing from server-only modules as a type using import type will not trigger the security error, as it does not leak sensitive information into the browser bundle.

Server-only module protection works with dynamic imports

SvelteKit's server-only module protection applies to dynamic imports, including interpolated ones like await import(`./${foo}.js`).

$app/server module import restrictions

The $app/server module, which contains a read function for reading assets from the filesystem, can only be imported by code that runs on the server.

snapshot data serialization requirement

Snapshot data must be serializable as JSON so it can be persisted to sessionStorage. This allows the state to be restored when the page is reloaded or when the user navigates back from a different site.

snapshot export object signature

Export a snapshot object from +page.svelte or +layout.svelte with two methods: capture() and restore(value). The capture method is called immediately before the page updates and returns a value to associate with the current history entry. The restore method is called with the stored value as soon as the page updates after navigation back.

snapshot capture method type

The capture method signature is capture: () => T, where T is the type parameter for Snapshot<T>. It takes no arguments and returns the value to be captured.

snapshot restore method type

The restore method signature is restore: (value: T) => void, where T is the type parameter for Snapshot<T>. It receives the stored value and performs side effects to restore the state.

snapshot large object performance pitfall

Avoid returning very large objects from capture because captured objects are retained in memory for the duration of the session and may be too large to persist to sessionStorage in extreme cases.

snapshot preserve ephemeral DOM state

Snapshots preserve ephemeral DOM state such as scroll positions on sidebars and the content of input elements that would otherwise be discarded when navigating between pages.

Observability feature available since version 2.31

SvelteKit's observability features for OpenTelemetry spans have been available since version 2.31.

What events emit OpenTelemetry spans

SvelteKit can emit server-side OpenTelemetry spans for: the handle hook and handle functions running in a sequence (which show up as children of each other and the root handle hook), server load functions and universal load functions when run on the server, form actions, and remote functions.

Instrumentation setup file location

SvelteKit provides src/instrumentation.server.ts as a place to write tracing setup and instrumentation code. It is guaranteed to be run prior to application code being imported, provided the deployment platform supports it and the adapter is aware of it.

Configuration options to enable tracing

Observability features are experimental and must be explicitly opt-in by setting kit.experimental.tracing.server to true and kit.experimental.instrumentation.server to true in svelte.config.js.

Access to spans in request events

SvelteKit provides access to the root span and current span on the request event. The root span is associated with the root handle function. The current span could be associated with handle, load, a form action, or a remote function depending on context. Spans can be annotated with custom attributes using the setAttribute method.

Getting current span from request event

Use getRequestEvent() from '$app/server' to access the event object, which contains event.tracing.root and event.tracing.current for accessing spans.

@opentelemetry/api as optional peer dependency

SvelteKit uses @opentelemetry/api to generate spans. It is declared as an optional peer dependency so users not needing traces see no impact on install size or runtime performance. It is usually satisfied by dependencies of tracing libraries like @opentelemetry/sdk-node or @vercel/otel. If SvelteKit cannot find @opentelemetry/api after setting up trace collection, you can install it manually.

Multiple export points in package.json

A library can expose multiple entry points through the exports field. For example, a ./Foo.svelte export allows consumers to import directly from 'your-library/Foo.svelte'. Each export path requires corresponding type definitions and export conditions.

svelte-package command output directory

Running the svelte-package command from @sveltejs/package generates a dist directory containing all files from src/lib with Svelte components preprocessed and TypeScript files transpiled to JavaScript.

Type definitions generation in @sveltejs/package

Type definitions (d.ts files) are automatically generated for Svelte, JavaScript and TypeScript files by @sveltejs/package. TypeScript version 4.0.0 or higher is required. Type definitions are placed next to their implementation, and hand-written d.ts files are copied as-is.

@sveltejs/package version 2 package.json behavior

@sveltejs/package version 2 no longer generates a package.json file. Instead, it uses the package.json from the project and validates that it is correct.

Component library directory structure

A component library in SvelteKit has the same structure as a SvelteKit app, except that src/lib is the public-facing bit and the root package.json is used to publish the package. src/routes might be a documentation or demo site, or a development sandbox.

package.json files field for npm packaging

The files field tells npm which files to pack and upload to npm. It should contain the output folder (dist by default). The package.json, README, and LICENSE files are always included. Use .npmignore to exclude unnecessary files like unit tests.

package.json exports field structure

The exports field contains the package's entry points. Each key is the path users will import from, and the value is either a file path or a map of export conditions. Export conditions include types (for TypeScript) and svelte (for Svelte-aware tooling). A single root export uses "." as the key.

Export conditions in package.json

Export conditions tell tooling what file to import: types condition is used by TypeScript to look up type definition files; svelte condition is used by Svelte-aware tooling to recognize a Svelte component library; default condition can be used for non-Svelte libraries or where svelte is not appropriate.

Give your agent this brain