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

development

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

SvelteKit uses Vite for development

SvelteKit reflects changes to your code in the browser instantly by leveraging Vite with a Svelte plugin to provide Hot Module Replacement (HMR) for a lightning-fast and feature-rich development experience.

hooks.client.js and hooks.server.js files

hooks.client.js contains client-side hooks and hooks.server.js contains server-side hooks for the application.

service-worker.js file

The service-worker.js file contains the service worker for the application.

instrumentation.server.js file

The instrumentation.server.js file contains observability setup and instrumentation code. It requires adapter support and if the adapter supports it, it is guaranteed to run prior to loading and running the application code.

Context state updates during SSR do not affect parent components

Updating the value of context-based state in deeper-level pages or components during SSR will not affect the value in the parent component because the parent has already been rendered. On the client side (CSR), the value will be propagated and higher components will react to the new value. To avoid values 'flashing' during state updates during hydration, it is recommended to pass state down into components rather than up.

Component and page state is preserved during navigation

When navigating around the application, SvelteKit reuses existing layout and page components instead of destroying and recreating them. This means the data prop will update, but lifecycle methods like onMount and onDestroy will not rerun, and values derived from props will not be recalculated. Use the $derived rune to make values reactive to prop changes.

Using afterNavigate and beforeNavigate for component lifecycle

If code in onMount and onDestroy needs to run again after navigation, use afterNavigate and beforeNavigate respectively.

Force component remount on navigation with {#key}

To completely destroy and remount a component on navigation, use the {#key} block with page.url.pathname as the key expression.

Storing state in URL search parameters

State that should survive a reload and/or affect SSR, such as filters or sorting rules, should be stored in URL search parameters (like ?sort=price&order=ascending). URL parameters can be set in href or action attributes, or programmatically via goto('?key=value'). They can be accessed inside load functions via the url parameter, and inside components via page.url.searchParams.

Storing ephemeral state in snapshots

UI state that is disposable (like 'is the accordion open?') and should persist when the user navigates to a different page and comes back, but does not need to be persisted to a database or URL, can be stored using SvelteKit snapshots, which associate component state with a history entry.

Avoid shared state on the server

Do not store data in shared variables on the server because servers are long-lived and shared by multiple users. Storing user data in shared variables will cause one user's data to be visible to other users. Instead, authenticate users using cookies and persist data to a database.

load functions must be pure

Load functions should be pure with no side-effects (except for the occasional console.log). Do not write to stores or global state inside load functions. Instead, return the data from the load function and pass it to components that need it, or use page.data.

Using context API for app state on the server

App state and app stores on the server use Svelte's context API. The state or store is attached to the component tree with setContext, and when you subscribe you retrieve it with getContext. When passing state into context, pass a function referencing the state to keep reactivity across boundaries.

Enable csr conditionally during development

You can enable csr during development by setting export const csr = dev where dev is imported from $app/environment. This allows you to take advantage of HMR during development while disabling CSR in production.

Private environment variables are default

By default, all variables are considered private. Private variables can be imported via $app/env/private and cannot be imported into code that runs in the browser to prevent accidentally revealing secrets.

Implicit environment variable modules

By default, every environment variable is implicitly available inside the app via these modules: $env/static/private, $env/static/public, $env/dynamic/private, and $env/dynamic/public.

Explicit environment variables feature in SvelteKit 2.63

As of SvelteKit 2.63, you can opt into explicit environment variables, in which case you instead import from $app/env/private and $app/env/public modules. The $app/environment module is renamed to $app/env.

Explicit environment variables becoming default in SvelteKit 3

Explicit environment variables will become the default in SvelteKit 3. The $env/* modules and $app/environment will be removed.

Enable explicit environment variables with explicitEnvironmentVariables config

To opt in to explicit environment variables, set kit.experimental.explicitEnvironmentVariables to true in svelte.config.js.

Create src/env.ts file for explicit environment variables

When using explicit environment variables, create a src/env.ts (or src/env.js) file that exports a variables object using the defineEnvVars function.

defineEnvVars function and EnvVarConfig

The defineEnvVars function accepts an object where each key is a variable name and each value is an EnvVarConfig object that configures that environment variable. defineEnvVars returns its argument unaltered and exists purely to help with type safety.

Environment variables loaded from .env files

During development and at build time, variables defined in a .env or .env.local file will be added to the environment.

Public environment variable configuration

To expose an environment variable to the browser, specify public: true in the EnvVarConfig object. Public variables can be imported from $app/env/public.

Use public variables in app.html template

Public environment variables can be used in the src/app.html template using the %sveltekit.env.VARIABLE_NAME% placeholder syntax.

Environment variable validation with Standard Schema

You can specify a Standard Schema validator (such as Zod or Valibot) in the schema property of EnvVarConfig to check that an environment variable value is correct. If a value is invalid, the app will fail to start or build.

Making environment variables optional during build

To make variables optional when building but required when starting the app, use the building import from $app/env and configure the schema with a validator that accepts optional values during build.

Static environment variables for dead-code elimination

By default, variables are dynamic. If a variable is configured with static: true, it will be inlined into application code, enabling optimizations like dead-code elimination. Static variables must be set before building the app to be included.

Document environment variables with description

You can add a description property to an EnvVarConfig to document the purpose of an environment variable. Hovering over the variable name in app code will show the description.

Build process stages

Building a SvelteKit app happens in two stages when you run `vite build` (usually via `npm run build`). First, Vite creates an optimized production build of server code, browser code, and service worker if present, with prerendering executed at this stage if appropriate. Second, an adapter takes this production build and tunes it for the target environment.

Check building flag to prevent execution during build

Code that should not be executed during the build stage must check that `building` from `$app/environment` is `false`. For example, database initialization should be wrapped in `if (!building)` to prevent it from running during build time.

Files loaded during build analysis

SvelteKit loads `+page/layout(.server).js` files and all files they import for analysis during the build stage.

Preview production build with vite preview

After building, you can view your production build locally with `vite preview` (via `npm run preview`). This runs the app in Node and is not a perfect reproduction of your deployed app — adapter-specific adjustments like the `platform` object do not apply to previews.

Illegal import detection disabled during tests

When running tests, illegal import detection is disabled because unit testing frameworks like Vitest do not distinguish between server-only and public-facing code. This is determined by checking if process.env.TEST === 'true'.

Development quickstart using Jaeger

To set up local tracing collection for development, install Jaeger using their quickstart command. Then enable experimental flags in svelte.config.js and install OpenTelemetry dependencies: @opentelemetry/sdk-node, @opentelemetry/auto-instrumentations-node, @opentelemetry/exporter-trace-otlp-proto, and import-in-the-middle. Create src/instrumentation.server.js with NodeSDK configuration pointing to OTLPTraceExporter. Traces can then be viewed at localhost:16686.

Logger interface methods

Logger interface has methods: (msg: string): void (call as function), success(msg: string): void, error(msg: string): void, warn(msg: string): void, minor(msg: string): void, info(msg: string): void.

RequestEvent tracing property

RequestEvent has tracing property (available since v2.31.0) with structure: {enabled: boolean, root: Span (named 'sveltekit.handle.root'), current: Span (for current handle hook, load function, or form action)}. Access to spans for tracing. If tracing not enabled, spans do nothing.

ServerLoadEvent tracing property

ServerLoadEvent has tracing property (available since v2.31.0) with structure: {enabled: boolean, root: Span (named 'sveltekit.handle.root'), current: Span (for current server load function)}. Access to spans for tracing. If tracing not enabled, spans do nothing.

vite preview command

The `vite preview` command runs the production version locally.

svelte-kit sync command

The `svelte-kit sync` command creates the `tsconfig.json` and all generated types that can be imported as `./$types` inside routing files. This command is automatically run as the `prepare` script during npm lifecycle, so it should not ordinarily be run manually.

SvelteKit uses Vite CLI

SvelteKit projects use Vite, so most CLI commands are run via npm scripts that wrap Vite commands.

vite dev command

The `vite dev` command starts a development server.

vite build command

The `vite build` command builds a production version of the app.

Debug JavaScript Debug Terminal in VSCode

You can set up breakpoints in SvelteKit projects within VSCode using the built-in debug terminal. Open the command palette with CMD/Ctrl + Shift + P, find and launch "Debug: JavaScript Debug Terminal", then start your project (e.g., npm run dev) and set breakpoints in your client or server-side source code.

VSCode launch.json configuration for SvelteKit debugging

You can set up a .vscode/launch.json file in your project for debugging via the Run and Debug pane. A minimal example configuration uses type "node-terminal" with a "launch" request and runs a command like "npm run dev". Access the Run and Debug pane, select "Node.js..." from the Run menu, choose your run script (such as "Run script: dev"), and press the Start debugging play button or F5.

Node.js debugging with browser DevTools

You can debug Node.js applications using Google Chrome or Microsoft Edge browser DevTools. Start the Vite server with the --inspect flag (e.g., NODE_OPTIONS="--inspect" npm run dev), open your site in a browser tab (typically localhost:5173), open the browser's dev tools, and click the "Open dedicated DevTools for Node.js" icon near the top-left showing the Node.js logo. Alternatively, navigate to chrome://inspect or edge://inspect in the browser.

Browser DevTools Node.js debugging limitation

Browser-based debugging of Node.js applications using Google Chrome or Microsoft Edge DevTools only works with debugging client-side SvelteKit source maps.

Yarn 2 compatibility with SvelteKit

Yarn 2's Plug'n'Play feature (pnp) is broken because it deviates from the Node module resolution algorithm and doesn't work with native JavaScript modules that SvelteKit uses. You can use nodeLinker: 'node-modules' in your .yarnrc.yml file to disable pnp, but it's probably easier to use npm or pnpm.

Yarn 3 setup with SvelteKit

ESM support in Yarn 3 is currently considered experimental. To use Yarn 3 with SvelteKit, create a new application with yarn create svelte myapp, then enable Yarn Berry with yarn set version berry and yarn install. Add nodeLinker: node-modules to .yarnrc.yml to avoid build failures with enableGlobalCache set to true.

SvelteKit uses Rollup for production builds

SvelteKit uses Rollup to optimize apps for production, making them as fast and lean as possible. This includes extracting styles into static .css files.

SvelteKit uses Snowpack for development

SvelteKit uses Snowpack as its development server, which powers an unbundled development workflow. Instead of eagerly bundling the app, the dev server serves modules on-demand, meaning startup is essentially instantaneous however large the app becomes. Snowpack provides features like hot module reloading and error overlays.

Upgrading to SvelteKit 2 with migration tool

To upgrade to SvelteKit 2, run the automated migration tool: npx svelte-migrate sveltekit-2. The migration guide at /docs/kit/migrating-to-sveltekit-2 has more details about what is new.

OpenTelemetry spans emitted by SvelteKit

SvelteKit emits OpenTelemetry traces for: the handle hook (handle functions in a sequence show up as children of each other and the root handle hook), load functions (including universal load functions when they run on the server), form actions, and remote functions. Emitted spans include attributes describing the current request such as http.route, and surrounding context such as the +page or +layout file associated with a load function.

Node.js OpenTelemetry instrumentation example

Example Node.js instrumentation for SvelteKit using the OpenTelemetry Node SDK: import { NodeSDK } from '@opentelemetry/sdk-node'; import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'; import { createAddHookMessageChannel } from 'import-in-the-middle'; import { register } from 'module'; const { registerOptions } = createAddHookMessageChannel(); register('import-in-the-middle/hook.mjs', import.meta.url, registerOptions); const sdk = new NodeSDK({ serviceName: 'my-sveltekit-app', traceExporter: new OTLPTraceExporter(), instrumentations: [getNodeAutoInstrumentations()] }); sdk.start();

instrumentation.server.ts file for observability setup

SvelteKit now supports a src/instrumentation.server.ts file which, assuming your adapter supports it, is guaranteed to be loaded prior to your application code. This file provides a convenient home for all observability instrumentation setup.

Give your agent this brain