{"success":true,"metadata":{"total_documents":214,"filtered_documents":183,"total_size_kb":1062,"last_updated":"2026-03-04T02:00:04.103Z","generated_at":"2026-03-13T04:03:16.349Z"},"documents":[{"path":"apps/svelte.dev/content/docs/ai/10-introduction/10-overview.md","title":"Overview","filename":"10-overview.md","content":"The Svelte MCP ([Model Context Protocol](https://modelcontextprotocol.io/docs/getting-started/intro)) server can help your LLM or agent of choice write better Svelte code. It works by providing documentation relevant to the task at hand, and statically analysing generated code so that it can suggest fixes and best practices.\n\n## Setup\n\nThe setup varies based on the version of the MCP you prefer — remote or local — and your chosen MCP client (e.g. Claude Code, Codex CLI or GitHub Copilot):\n\n- [local setup](local-setup) using `@sveltejs/mcp`\n- [remote setup](remote-setup) using `https://mcp.svelte.dev/mcp`\n\n## Usage\n\nTo get the most out of the MCP server we recommend including the following prompt in your [`AGENTS.md`](https://agents.md) (or [`CLAUDE.md`](https://docs.claude.com/en/docs/claude-code/memory#claude-md-imports), if using Claude Code. Or [`GEMINI.md`](https://geminicli.com/docs/cli/gemini-md/), if using GEMINI). This will tell the LLM which tools are available and when it's appropriate to use them.\n\n\nYou are able to use the Svelte MCP server, where you have access to comprehensive Svelte 5 and SvelteKit documentation. Here's how to use the available tools effectively:\n\n## Available Svelte MCP Tools:\n\n### 1. list-sections\n\nUse this FIRST to discover all available documentation sections. Returns a structured list with titles, use_cases, and paths.\nWhen asked about Svelte or SvelteKit topics, ALWAYS use this tool at the start of the chat to find relevant sections.\n\n### 2. get-documentation\n\nRetrieves full documentation content for specific sections. Accepts single or multiple sections.\nAfter calling the list-sections tool, you MUST analyze the returned documentation sections (especially the use_cases field) and then use the get-documentation tool to fetch ALL documentation sections that are relevant for the user's task.\n\n### 3. svelte-autofixer\n\nAnalyzes Svelte code and returns issues and suggestions.\nYou MUST use this tool whenever writing Svelte code before sending it to the user. Keep calling it until no issues or suggestions are returned.\n\n### 4. playground-link\n\nGenerates a Svelte Playground link with the provided code.\nAfter completing the code, ask the user if they want a playground link. Only call this tool after user confirmation and NEVER if code was written to files in their project.\n\n\nIf your MCP client supports it, we also recommend using the [svelte-task](prompts#svelte-task) prompt to instruct the LLM on the best way to use the MCP server.","size_bytes":2535,"metadata":{"title":"Overview"},"created_at":"2026-02-28T02:00:03.889Z","updated_at":"2026-02-28T02:00:03.889Z"},{"path":"apps/svelte.dev/content/docs/ai/20-setup/20-local-setup.md","title":"Local setup","filename":"20-local-setup.md","content":"The local (or stdio) version of the MCP server is available via the [`@sveltejs/mcp`](https://www.npmjs.com/package/@sveltejs/mcp) npm package. You can either install it globally and then reference it in your configuration or run it with `npx`:\n\n```bash\nnpx -y @sveltejs/mcp\n```\n\nHere's how to set it up in some common MCP clients:\n\n## Claude Code\n\nTo include the local MCP version in Claude Code, simply run the following command:\n\n```bash\nclaude mcp add -t stdio -s [scope] svelte -- npx -y @sveltejs/mcp\n```\n\nThe `[scope]` must be `user`, `project` or `local`.\n\n## Claude Desktop\n\nIn the Settings > Developer section, click on Edit Config. It will open the folder with a `claude_desktop_config.json` file in it. Edit the file to include the following configuration:\n\n```json\n{\n\t\"mcpServers\": {\n\t\t\"svelte\": {\n\t\t\t\"command\": \"npx\",\n\t\t\t\"args\": [\"-y\", \"@sveltejs/mcp\"]\n\t\t}\n\t}\n}\n```\n\n## Codex CLI\n\nAdd the following to your `config.toml` (which defaults to `~/.codex/config.toml`, but refer to [the configuration documentation](https://github.com/openai/codex/blob/main/docs/config.md) for more advanced setups):\n\n```toml\n[mcp_servers.svelte]\ncommand = \"npx\"\nargs = [\"-y\", \"@sveltejs/mcp\"]\n```\n\n## Copilot CLI\n\nUse the Copilot CLI to interactively add the MCP server:\n\n```bash\n/mcp add\n```\n\nAlternatively, create or edit `~/.copilot/mcp-config.json` and add the following configuration:\n\n```json\n{\n\t\"mcpServers\": {\n\t\t\"svelte\": {\n\t\t\t\"command\": \"npx\",\n\t\t\t\"args\": [\"-y\", \"@sveltejs/mcp\"]\n\t\t}\n\t}\n}\n```\n\n## Gemini CLI\n\nTo include the local MCP version in Gemini CLI, simply run the following command:\n\n```bash\ngemini mcp add -t stdio -s [scope] svelte npx -y @sveltejs/mcp\n```\n\nThe `[scope]` must be `user`, `project` or `local`.\n\n## OpenCode\n\nYou can automatically configure the MCP server using the [OpenCode plugin](opencode-plugin) (recommended). If you prefer to configure the MCP server manually, run:\n\n```bash\nopencode mcp add\n```\n\nand follow the instructions, selecting 'Local' under the 'Select MCP server type' prompt:\n\n```bash\nopencode mcp add\n\n┌  Add MCP server\n│\n◇  Enter MCP server name\n│  svelte\n│\n◇  Select MCP server type\n│  Local\n│\n◆  Enter command to run\n│  npx -y @sveltejs/mcp\n```\n\n## VS Code\n\n- Open the command palette\n- Select \"MCP: Add Server...\"\n- Select \"Command (stdio)\"\n- Insert `npx -y @sveltejs/mcp` in the input and press `Enter`\n- When prompted for a name, insert `svelte`\n- Select if you want to add it as a `Global` or `Workspace` MCP server\n\n## Cursor\n\n- Open the command palette\n- Select \"View: Open MCP Settings\"\n- Click on \"Add custom MCP\"\n\nIt will open a file with your MCP servers where you can add the following configuration:\n\n```json\n{\n\t\"mcpServers\": {\n\t\t\"svelte\": {\n\t\t\t\"command\": \"npx\",\n\t\t\t\"args\": [\"-y\", \"@sveltejs/mcp\"]\n\t\t}\n\t}\n}\n```\n\n## Zed\n\nInstall the [Svelte MCP Server extension](https://zed.dev/extensions/svelte-mcp).\n\n<details>\n\n<summary>Configure Manually</summary>\n\n- Open the command palette\n- Search and select \"agent:open settings\"\n- In settings panel look for `Model Context Protocol (MCP) Servers`\n- Click on \"Add Server\"\n- Select: \"Add Custom Server\"\n\nIt will open a popup with MCP server config where you can add the following configuration:\n\n```json\n{\n\t\"svelte\": {\n\t\t\"command\": \"npx\",\n\t\t\"args\": [\"-y\", \"@sveltejs/mcp\"]\n\t}\n}\n```\n\n</details>\n\n## Other clients\n\nIf we didn't include the MCP client you are using, refer to their documentation for `stdio` servers and use `npx` as the command and `-y @sveltejs/mcp` as the arguments.","size_bytes":3533,"metadata":{"title":"Local setup"},"created_at":"2026-02-28T02:00:03.940Z","updated_at":"2026-02-28T02:00:03.940Z"},{"path":"apps/svelte.dev/content/docs/ai/20-setup/30-remote-setup.md","title":"Remote setup","filename":"30-remote-setup.md","content":"The remote version of the MCP server is available at `https://mcp.svelte.dev/mcp`.\n\nHere's how to set it up in some common MCP clients:\n\n## Claude Code\n\nTo include the remote MCP version in Claude Code, simply run the following command:\n\n```bash\nclaude mcp add -t http -s [scope] svelte https://mcp.svelte.dev/mcp\n```\n\nYou can choose your preferred `scope` (it must be `user`, `project` or `local`) and `name`.\n\nIf you prefer you can also install the `svelte` plugin in [the Svelte Claude Code Marketplace](plugin) that will give you both the remote server and useful [skills](skills).\n\n## Claude Desktop\n\n- Open Settings > Connectors\n- Click on Add Custom Connector\n- When prompted for a name, enter `svelte`\n- Under the Remote MCP server URL input, use `https://mcp.svelte.dev/mcp`\n- Click Add\n\n## Codex CLI\n\nAdd the following to your `config.toml` (which defaults to `~/.codex/config.toml`, but refer to [the configuration documentation](https://github.com/openai/codex/blob/main/docs/config.md) for more advanced setups):\n\n```toml\nexperimental_use_rmcp_client = true\n[mcp_servers.svelte]\nurl = \"https://mcp.svelte.dev/mcp\"\n```\n\n## Copilot CLI\n\nUse the Copilot CLI to interactively add the MCP server:\n\n```bash\n/mcp add\n```\n\nAlternatively, create or edit `~/.copilot/mcp-config.json` and add the following configuration:\n\n```json\n{\n\t\"mcpServers\": {\n\t\t\"svelte\": {\n\t\t\t\"url\": \"https://mcp.svelte.dev/mcp\"\n\t\t}\n\t}\n}\n```\n\n## Gemini CLI\n\nTo use the remote MCP server with Gemini CLI, simply run the following command:\n\n```bash\ngemini mcp add -t http -s [scope] svelte https://mcp.svelte.dev/mcp\n```\n\nThe `[scope]` must be `user` or `project`.\n\n## OpenCode\n\nYou can automatically configure the MCP server using the [OpenCode plugin](opencode-plugin) (recommended). If you prefer to configure the MCP server manually, run:\n\n```bash\nopencode mcp add\n```\n\nand follow the instructions, selecting 'Remote' under the 'Select MCP server type' prompt:\n\n```bash\nopencode mcp add\n\n┌  Add MCP server\n│\n◇  Enter MCP server name\n│  svelte\n│\n◇  Select MCP server type\n│  Remote\n│\n◇  Enter MCP server URL\n│  https://mcp.svelte.dev/mcp\n```\n\n## VS Code\n\n- Open the command palette\n- Select \"MCP: Add Server...\"\n- Select \"HTTP (HTTP or Server-Sent-Events)\"\n- Insert `https://mcp.svelte.dev/mcp` in the input and press `Enter`\n- Insert your preferred name\n- Select if you want to add it as a `Global` or `Workspace` MCP server\n\n## Cursor\n\n- Open the command palette\n- Select \"View: Open MCP Settings\"\n- Click on \"Add custom MCP\"\n\nIt will open a file with your MCP servers where you can add the following configuration:\n\n```json\n{\n\t\"mcpServers\": {\n\t\t\"svelte\": {\n\t\t\t\"url\": \"https://mcp.svelte.dev/mcp\"\n\t\t}\n\t}\n}\n```\n\n## GitHub Coding Agent\n\n- Open your repository in GitHub\n- Go to Settings\n- Open Copilot > Coding agent\n- Edit the MCP configuration\n\n```json\n{\n\t\"mcpServers\": {\n\t\t\"svelte\": {\n\t\t\t\"type\": \"http\",\n\t\t\t\"url\": \"https://mcp.svelte.dev/mcp\",\n\t\t\t\"tools\": [\"*\"]\n\t\t}\n\t}\n}\n```\n\n- Click _Save MCP configuration_\n\n## Other clients\n\nIf we didn't include the MCP client you are using, refer to their documentation for `remote` servers and use `https://mcp.svelte.dev/mcp` as the URL.","size_bytes":3207,"metadata":{"title":"Remote setup"},"created_at":"2026-02-28T02:00:03.936Z","updated_at":"2026-02-28T02:00:03.936Z"},{"path":"apps/svelte.dev/content/docs/ai/30-capabilities/10-tools.md","title":"Tools","filename":"10-tools.md","content":"The following tools are provided by the MCP server to the model you are using, which can decide to call one or more of them during a session:\n\n## list-sections\n\nProvides a list of all the available documentation sections.\n\n## get-documentation\n\nAllows the model to get the full (and up-to-date) documentation for the requested sections directly from [svelte.dev/docs](/docs).\n\n## svelte-autofixer\n\nUses static analysis to provide suggestions for code that your LLM generates. It can be invoked in an agentic loop by your model until all issues and suggestions are resolved.\n\n## playground-link\n\nGenerates an ephemeral playground link with the generated code. It's useful when the generated code is not written to a file in your project and you want to quickly test the generated solution. The code is not stored anywhere except the URL itself (which will often, as a consequence, be quite large).","size_bytes":919,"metadata":{"title":"Tools"},"created_at":"2026-02-28T02:00:03.933Z","updated_at":"2026-02-28T02:00:03.933Z"},{"path":"apps/svelte.dev/content/docs/ai/30-capabilities/20-resources.md","title":"Resources","filename":"20-resources.md","content":"This is the list of available resources provided by the MCP server. Resources are included by the user (not by the LLM) and are useful if you want to include specific knowledge in your session. For example, if you know that the component will need to use transitions you can include the transition documentation directly without asking the LLM to do it for you.\n\n## doc-section\n\nThis dynamic resource allows you to add every section of the Svelte documentation as a resource. The URI looks like this `svelte://slug-of-the-docs.md` and the returned resource will contain the `llms.txt` version of the specific page you selected.","size_bytes":654,"metadata":{"title":"Resources"},"created_at":"2026-02-28T02:00:03.933Z","updated_at":"2026-02-28T02:00:03.933Z"},{"path":"apps/svelte.dev/content/docs/ai/30-capabilities/30-prompts.md","title":"Prompts","filename":"30-prompts.md","content":"This is the list of available prompts provided by the MCP server. Prompts are selected by the user and are sent as a user message. They can be useful to write repetitive instructions for the LLM on how to properly use the MCP server.\n\n## svelte-task\n\nThis prompt should be used whenever you are asking the model to work on a Svelte-related task. It will instruct the LLM which documentation sections are available, which tools to invoke, when to invoke them, and how to interpret the results.\n\n<details>\n\t<summary>Copy the prompt</summary>\n\n```md\nYou are a Svelte expert tasked to build components and utilities for Svelte developers. If you need documentation for anything related to Svelte you can invoke the tool `get-documentation` with one of the following paths. However: before invoking the `get-documentation` tool, try to answer the users query using your own knowledge and the `svelte-autofixer` tool. Be mindful of how many section you request, since it is token-intensive!\n<available-docs>\n\ntitle: Overview, use_cases: project setup, creating new svelte apps, scaffolding, cli tools, initializing projects, path: cli/overview\ntitle: Frequently asked questions, use_cases: project setup, initializing new svelte projects, troubleshooting cli installation, package manager configuration, path: cli/faq\ntitle: sv create, use_cases: project setup, starting new sveltekit app, initializing project, creating from playground, choosing project template, path: cli/sv-create\ntitle: sv add, use_cases: project setup, adding features to existing projects, integrating tools, testing setup, styling setup, authentication, database setup, deployment adapters, path: cli/sv-add\ntitle: sv check, use_cases: code quality, ci/cd pipelines, error checking, typescript projects, pre-commit hooks, finding unused css, accessibility auditing, production builds, path: cli/sv-check\ntitle: sv migrate, use_cases: migration, upgrading svelte versions, upgrading sveltekit versions, modernizing codebase, svelte 3 to 4, svelte 4 to 5, sveltekit 1 to 2, adopting runes, refactoring deprecated apis, path: cli/sv-migrate\ntitle: devtools-json, use_cases: development setup, chrome devtools integration, browser-based editing, local development workflow, debugging setup, path: cli/devtools-json\ntitle: drizzle, use_cases: database setup, sql queries, orm integration, data modeling, postgresql, mysql, sqlite, server-side data access, database migrations, type-safe queries, path: cli/drizzle\ntitle: eslint, use_cases: code quality, linting, error detection, project setup, code standards, team collaboration, typescript projects, path: cli/eslint\ntitle: lucia, use_cases: authentication, login systems, user management, registration pages, session handling, auth setup, path: cli/lucia\ntitle: mcp, use_cases: use title and path to estimate use case, path: cli/mcp\ntitle: mdsvex, use_cases: blog, content sites, markdown rendering, documentation sites, technical writing, cms integration, article pages, path: cli/mdsvex\ntitle: paraglide, use_cases: internationalization, multi-language sites, i18n, translation, localization, language switching, global apps, multilingual content, path: cli/paraglide\ntitle: playwright, use_cases: browser testing, e2e testing, integration testing, test automation, quality assurance, ci/cd pipelines, testing user flows, path: cli/playwright\ntitle: prettier, use_cases: code formatting, project setup, code style consistency, team collaboration, linting configuration, path: cli/prettier\ntitle: storybook, use_cases: component development, design systems, ui library, isolated component testing, documentation, visual testing, component showcase, path: cli/storybook\ntitle: sveltekit-adapter, use_cases: deployment, production builds, hosting setup, choosing deployment platform, configuring adapters, static site generation, node server, vercel, cloudflare, netlify, path: cli/sveltekit-adapter\ntitle: tailwindcss, use_cases: project setup, styling, css framework, rapid prototyping, utility-first css, design systems, responsive design, adding tailwind to svelte, path: cli/tailwind\ntitle: vitest, use_cases: testing, unit tests, component testing, test setup, quality assurance, ci/cd pipelines, test-driven development, path: cli/vitest\ntitle: add-on, use_cases: use title and path to estimate use case, path: cli/add-on\ntitle: Introduction, use_cases: learning sveltekit, project setup, understanding framework basics, choosing between svelte and sveltekit, getting started with full-stack apps, path: kit/introduction\ntitle: Creating a project, use_cases: project setup, starting new sveltekit app, initial development environment, first-time sveltekit users, scaffolding projects, path: kit/creating-a-project\ntitle: Project types, use_cases: deployment, project setup, choosing adapters, ssg, spa, ssr, serverless, mobile apps, desktop apps, pwa, offline apps, browser extensions, separate backend, docker containers, path: kit/project-types\ntitle: Project structure, use_cases: project setup, understanding file structure, organizing code, starting new project, learning sveltekit basics, path: kit/project-structure\ntitle: Web standards, use_cases: always, any sveltekit project, data fetching, forms, api routes, server-side rendering, deployment to various platforms, path: kit/web-standards\ntitle: Routing, use_cases: routing, navigation, multi-page apps, project setup, file structure, api endpoints, data loading, layouts, error pages, always, path: kit/routing\ntitle: Loading data, use_cases: data fetching, api calls, database queries, dynamic routes, page initialization, loading states, authentication checks, ssr data, form data, content rendering, path: kit/load\ntitle: Form actions, use_cases: forms, user input, data submission, authentication, login systems, user registration, progressive enhancement, validation errors, path: kit/form-actions\ntitle: Page options, use_cases: prerendering static sites, ssr configuration, spa setup, client-side rendering control, url trailing slash handling, adapter deployment config, build optimization, path: kit/page-options\ntitle: State management, use_cases: sveltekit, server-side rendering, ssr, state management, authentication, data persistence, load functions, context api, navigation, component lifecycle, path: kit/state-management\ntitle: Remote functions, use_cases: data fetching, server-side logic, database queries, type-safe client-server communication, forms, user input, mutations, authentication, crud operations, optimistic updates, path: kit/remote-functions\ntitle: Building your app, use_cases: production builds, deployment preparation, build process optimization, adapter configuration, preview before deployment, path: kit/building-your-app\ntitle: Adapters, use_cases: deployment, production builds, hosting setup, choosing deployment platform, configuring adapters, path: kit/adapters\ntitle: Zero-config deployments, use_cases: deployment, production builds, hosting setup, choosing deployment platform, ci/cd configuration, path: kit/adapter-auto\ntitle: Node servers, use_cases: deployment, production builds, node.js hosting, custom server setup, environment configuration, reverse proxy setup, docker deployment, systemd services, path: kit/adapter-node\ntitle: Static site generation, use_cases: static site generation, ssg, prerendering, deployment, github pages, spa mode, blogs, documentation sites, marketing sites, path: kit/adapter-static\ntitle: Single-page apps, use_cases: spa mode, single-page apps, client-only rendering, static hosting, mobile app wrappers, no server-side logic, adapter-static setup, fallback pages, path: kit/single-page-apps\ntitle: Cloudflare, use_cases: deployment, cloudflare workers, cloudflare pages, hosting setup, production builds, serverless deployment, edge computing, path: kit/adapter-cloudflare\ntitle: Cloudflare Workers, use_cases: deploying to cloudflare workers, cloudflare workers sites deployment, legacy cloudflare adapter, wrangler configuration, cloudflare platform bindings, path: kit/adapter-cloudflare-workers\ntitle: Netlify, use_cases: deployment, netlify hosting, production builds, serverless functions, edge functions, static site hosting, path: kit/adapter-netlify\ntitle: Vercel, use_cases: deployment, vercel hosting, production builds, serverless functions, edge functions, isr, image optimization, environment variables, path: kit/adapter-vercel\ntitle: Writing adapters, use_cases: custom deployment, building adapters, unsupported platforms, adapter development, custom hosting environments, path: kit/writing-adapters\ntitle: Advanced routing, use_cases: advanced routing, dynamic routes, file viewers, nested paths, custom 404 pages, url validation, route parameters, multi-level navigation, path: kit/advanced-routing\ntitle: Hooks, use_cases: authentication, logging, error tracking, request interception, api proxying, custom routing, internationalization, database initialization, middleware logic, session management, path: kit/hooks\ntitle: Errors, use_cases: error handling, custom error pages, 404 pages, api error responses, production error logging, error tracking, type-safe errors, path: kit/errors\ntitle: Link options, use_cases: routing, navigation, multi-page apps, performance optimization, link preloading, forms with get method, search functionality, focus management, scroll behavior, path: kit/link-options\ntitle: Service workers, use_cases: offline support, pwa, caching strategies, performance optimization, precaching assets, network resilience, progressive web apps, path: kit/service-workers\ntitle: Server-only modules, use_cases: api keys, environment variables, sensitive data protection, backend security, preventing data leaks, server-side code isolation, path: kit/server-only-modules\ntitle: Snapshots, use_cases: forms, user input, preserving form data, multi-step forms, navigation state, preventing data loss, textarea content, input fields, comment systems, surveys, path: kit/snapshots\ntitle: Shallow routing, use_cases: modals, dialogs, image galleries, overlays, history-driven ui, mobile-friendly navigation, photo viewers, lightboxes, drawer menus, path: kit/shallow-routing\ntitle: Observability, use_cases: performance monitoring, debugging, observability, tracing requests, production diagnostics, analyzing slow requests, finding bottlenecks, monitoring server-side operations, path: kit/observability\ntitle: Packaging, use_cases: building component libraries, publishing npm packages, creating reusable svelte components, library development, package distribution, path: kit/packaging\ntitle: Auth, use_cases: authentication, login systems, user management, session handling, jwt tokens, protected routes, user credentials, authorization checks, path: kit/auth\ntitle: Performance, use_cases: performance optimization, slow loading pages, production deployment, debugging performance issues, reducing bundle size, improving load times, path: kit/performance\ntitle: Icons, use_cases: icons, ui components, styling, css frameworks, tailwind, unocss, performance optimization, dependency management, path: kit/icons\ntitle: Images, use_cases: image optimization, responsive images, performance, hero images, product photos, galleries, cms integration, cdn setup, asset management, path: kit/images\ntitle: Accessibility, use_cases: always, any sveltekit project, screen reader support, keyboard navigation, multi-page apps, client-side routing, internationalization, multilingual sites, path: kit/accessibility\ntitle: SEO, use_cases: seo optimization, search engine ranking, content sites, blogs, marketing sites, public-facing apps, sitemaps, amp pages, meta tags, performance optimization, path: kit/seo\ntitle: Frequently asked questions, use_cases: troubleshooting package imports, library compatibility issues, client-side code execution, external api integration, middleware setup, database configuration, view transitions, yarn configuration, path: kit/faq\ntitle: Integrations, use_cases: project setup, css preprocessors, postcss, scss, sass, less, stylus, typescript setup, adding integrations, tailwind, testing, auth, linting, formatting, path: kit/integrations\ntitle: Breakpoint Debugging, use_cases: debugging, breakpoints, development workflow, troubleshooting issues, vscode setup, ide configuration, inspecting code execution, path: kit/debugging\ntitle: Migrating to SvelteKit v2, use_cases: migration, upgrading from sveltekit 1 to 2, breaking changes, version updates, path: kit/migrating-to-sveltekit-2\ntitle: Migrating from Sapper, use_cases: migrating from sapper, upgrading legacy projects, sapper to sveltekit conversion, project modernization, path: kit/migrating\ntitle: Additional resources, use_cases: troubleshooting, getting help, finding examples, learning sveltekit, project templates, common issues, community support, path: kit/additional-resources\ntitle: Glossary, use_cases: rendering strategies, performance optimization, deployment configuration, seo requirements, static sites, spas, server-side rendering, prerendering, edge deployment, pwa development, path: kit/glossary\ntitle: @sveltejs/kit, use_cases: forms, form actions, server-side validation, form submission, error handling, redirects, json responses, http errors, server utilities, path: kit/@sveltejs-kit\ntitle: @sveltejs/kit/hooks, use_cases: middleware, request processing, authentication chains, logging, multiple hooks, request/response transformation, path: kit/@sveltejs-kit-hooks\ntitle: @sveltejs/kit/node/polyfills, use_cases: node.js environments, custom servers, non-standard runtimes, ssr setup, web api compatibility, polyfill requirements, path: kit/@sveltejs-kit-node-polyfills\ntitle: @sveltejs/kit/node, use_cases: node.js adapter, custom server setup, http integration, streaming files, node deployment, server-side rendering with node, path: kit/@sveltejs-kit-node\ntitle: @sveltejs/kit/vite, use_cases: project setup, vite configuration, initial sveltekit setup, build tooling, path: kit/@sveltejs-kit-vite\ntitle: $app/environment, use_cases: always, conditional logic, client-side code, server-side code, build-time logic, prerendering, development vs production, environment detection, path: kit/$app-environment\ntitle: $app/forms, use_cases: forms, user input, data submission, progressive enhancement, custom form handling, form validation, path: kit/$app-forms\ntitle: $app/navigation, use_cases: routing, navigation, multi-page apps, programmatic navigation, data reloading, preloading, shallow routing, navigation lifecycle, scroll handling, view transitions, path: kit/$app-navigation\ntitle: $app/paths, use_cases: static assets, images, fonts, public files, base path configuration, subdirectory deployment, cdn setup, asset urls, links, navigation, path: kit/$app-paths\ntitle: $app/server, use_cases: remote functions, server-side logic, data fetching, form handling, api endpoints, client-server communication, prerendering, file reading, batch queries, path: kit/$app-server\ntitle: $app/state, use_cases: routing, navigation, multi-page apps, loading states, url parameters, form handling, error states, version updates, page metadata, shallow routing, path: kit/$app-state\ntitle: $app/stores, use_cases: legacy projects, sveltekit pre-2.12, migration from stores to runes, maintaining older codebases, accessing page data, navigation state, app version updates, path: kit/$app-stores\ntitle: $app/types, use_cases: routing, navigation, type safety, route parameters, dynamic routes, link generation, pathname validation, multi-page apps, path: kit/$app-types\ntitle: $env/dynamic/private, use_cases: api keys, secrets management, server-side config, environment variables, backend logic, deployment-specific settings, private data handling, path: kit/$env-dynamic-private\ntitle: $env/dynamic/public, use_cases: environment variables, client-side config, runtime configuration, public api keys, deployment-specific settings, multi-environment apps, path: kit/$env-dynamic-public\ntitle: $env/static/private, use_cases: server-side api keys, backend secrets, database credentials, private configuration, build-time optimization, server endpoints, authentication tokens, path: kit/$env-static-private\ntitle: $env/static/public, use_cases: environment variables, public config, client-side data, api endpoints, build-time configuration, public constants, path: kit/$env-static-public\ntitle: $lib, use_cases: project setup, component organization, importing shared components, reusable ui elements, code structure, path: kit/$lib\ntitle: $service-worker, use_cases: offline support, pwa, service workers, caching strategies, progressive web apps, offline-first apps, path: kit/$service-worker\ntitle: Configuration, use_cases: project setup, configuration, adapters, deployment, build settings, environment variables, routing customization, prerendering, csp security, csrf protection, path configuration, typescript setup, path: kit/configuration\ntitle: Command Line Interface, use_cases: project setup, typescript configuration, generated types, ./$types imports, initial project configuration, path: kit/cli\ntitle: Types, use_cases: typescript, type safety, route parameters, api endpoints, load functions, form actions, generated types, jsconfig setup, path: kit/types\ntitle: Overview, use_cases: use title and path to estimate use case, path: mcp/overview\ntitle: Local setup, use_cases: use title and path to estimate use case, path: mcp/local-setup\ntitle: Remote setup, use_cases: use title and path to estimate use case, path: mcp/remote-setup\ntitle: Tools, use_cases: use title and path to estimate use case, path: mcp/tools\ntitle: Resources, use_cases: use title and path to estimate use case, path: mcp/resources\ntitle: Prompts, use_cases: use title and path to estimate use case, path: mcp/prompts\ntitle: Overview, use_cases: use title and path to estimate use case, path: mcp/plugin\ntitle: Skill, use_cases: use title and path to estimate use case, path: mcp/skill\ntitle: Subagent, use_cases: use title and path to estimate use case, path: mcp/subagent\ntitle: Overview, use_cases: use title and path to estimate use case, path: mcp/opencode-plugin\ntitle: Subagent, use_cases: use title and path to estimate use case, path: mcp/opencode-subagent\ntitle: Overview, use_cases: always, any svelte project, getting started, learning svelte, introduction, project setup, understanding framework basics, path: svelte/overview\ntitle: Getting started, use_cases: project setup, starting new svelte project, initial installation, choosing between sveltekit and vite, editor configuration, path: svelte/getting-started\ntitle: .svelte files, use_cases: always, any svelte project, component creation, project setup, learning svelte basics, path: svelte/svelte-files\ntitle: .svelte.js and .svelte.ts files, use_cases: shared reactive state, reusable reactive logic, state management across components, global stores, custom reactive utilities, path: svelte/svelte-js-files\ntitle: What are runes?, use_cases: always, any svelte 5 project, understanding core syntax, learning svelte 5, migration from svelte 4, path: svelte/what-are-runes\ntitle: $state, use_cases: always, any svelte project, core reactivity, state management, counters, forms, todo apps, interactive ui, data updates, class-based components, path: svelte/$state\ntitle: $derived, use_cases: always, any svelte project, computed values, reactive calculations, derived data, transforming state, dependent values, path: svelte/$derived\ntitle: $effect, use_cases: canvas drawing, third-party library integration, dom manipulation, side effects, intervals, timers, network requests, analytics tracking, path: svelte/$effect\ntitle: $props, use_cases: always, any svelte project, passing data to components, component communication, reusable components, component props, path: svelte/$props\ntitle: $bindable, use_cases: forms, user input, two-way data binding, custom input components, parent-child communication, reusable form fields, path: svelte/$bindable\ntitle: $inspect, use_cases: debugging, development, tracking state changes, reactive state monitoring, troubleshooting reactivity issues, path: svelte/$inspect\ntitle: $host, use_cases: custom elements, web components, dispatching custom events, component library, framework-agnostic components, path: svelte/$host\ntitle: Basic markup, use_cases: always, any svelte project, basic markup, html templating, component structure, attributes, events, props, text rendering, path: svelte/basic-markup\ntitle: {#if ...}, use_cases: always, conditional rendering, showing/hiding content, dynamic ui, user permissions, loading states, error handling, form validation, path: svelte/if\ntitle: {#each ...}, use_cases: always, lists, arrays, iteration, product listings, todos, tables, grids, dynamic content, shopping carts, user lists, comments, feeds, path: svelte/each\ntitle: {#key ...}, use_cases: animations, transitions, component reinitialization, forcing component remount, value-based ui updates, resetting component state, path: svelte/key\ntitle: {#await ...}, use_cases: async data fetching, api calls, loading states, promises, error handling, lazy loading components, dynamic imports, path: svelte/await\ntitle: {#snippet ...}, use_cases: reusable markup, component composition, passing content to components, table rows, list items, conditional rendering, reducing duplication, path: svelte/snippet\ntitle: {@render ...}, use_cases: reusable ui patterns, component composition, conditional rendering, fallback content, layout components, slot alternatives, template reuse, path: svelte/@render\ntitle: {@html ...}, use_cases: rendering html strings, cms content, rich text editors, markdown to html, blog posts, wysiwyg output, sanitized html injection, dynamic html content, path: svelte/@html\ntitle: {@attach ...}, use_cases: tooltips, popovers, dom manipulation, third-party libraries, canvas drawing, element lifecycle, interactive ui, custom directives, wrapper components, path: svelte/@attach\ntitle: {@const ...}, use_cases: computed values in loops, derived calculations in blocks, local variables in each iterations, complex list rendering, path: svelte/@const\ntitle: {@debug ...}, use_cases: debugging, development, troubleshooting, tracking state changes, monitoring variables, reactive data inspection, path: svelte/@debug\ntitle: bind:, use_cases: forms, user input, two-way data binding, interactive ui, media players, file uploads, checkboxes, radio buttons, select dropdowns, contenteditable, dimension tracking, path: svelte/bind\ntitle: use:, use_cases: custom directives, dom manipulation, third-party library integration, tooltips, click outside, gestures, focus management, element lifecycle hooks, path: svelte/use\ntitle: transition:, use_cases: animations, interactive ui, modals, dropdowns, notifications, conditional content, show/hide elements, smooth state changes, path: svelte/transition\ntitle: in: and out:, use_cases: animation, transitions, interactive ui, conditional rendering, independent enter/exit effects, modals, tooltips, notifications, path: svelte/in-and-out\ntitle: animate:, use_cases: sortable lists, drag and drop, reorderable items, todo lists, kanban boards, playlist editors, priority queues, animated list reordering, path: svelte/animate\ntitle: style:, use_cases: dynamic styling, conditional styles, theming, dark mode, responsive design, interactive ui, component styling, path: svelte/style\ntitle: class, use_cases: always, conditional styling, dynamic classes, tailwind css, component styling, reusable components, responsive design, path: svelte/class\ntitle: await, use_cases: async data fetching, loading states, server-side rendering, awaiting promises in components, async validation, concurrent data loading, path: svelte/await-expressions\ntitle: Scoped styles, use_cases: always, styling components, scoped css, component-specific styles, preventing style conflicts, animations, keyframes, path: svelte/scoped-styles\ntitle: Global styles, use_cases: global styles, third-party libraries, css resets, animations, styling body/html, overriding component styles, shared keyframes, base styles, path: svelte/global-styles\ntitle: Custom properties, use_cases: theming, custom styling, reusable components, design systems, dynamic colors, component libraries, ui customization, path: svelte/custom-properties\ntitle: Nested <style> elements, use_cases: component styling, scoped styles, dynamic styles, conditional styling, nested style tags, custom styling logic, path: svelte/nested-style-elements\ntitle: <svelte:boundary>, use_cases: error handling, async data loading, loading states, error recovery, flaky components, error reporting, resilient ui, path: svelte/svelte-boundary\ntitle: <svelte:window>, use_cases: keyboard shortcuts, scroll tracking, window resize handling, responsive layouts, online/offline detection, viewport dimensions, global event listeners, path: svelte/svelte-window\ntitle: <svelte:document>, use_cases: document events, visibility tracking, fullscreen detection, pointer lock, focus management, document-level interactions, path: svelte/svelte-document\ntitle: <svelte:body>, use_cases: mouse tracking, hover effects, cursor interactions, global body events, drag and drop, custom cursors, interactive backgrounds, body-level actions, path: svelte/svelte-body\ntitle: <svelte:head>, use_cases: seo optimization, page titles, meta tags, social media sharing, dynamic head content, multi-page apps, blog posts, product pages, path: svelte/svelte-head\ntitle: <svelte:element>, use_cases: dynamic content, cms integration, user-generated content, configurable ui, runtime element selection, flexible components, path: svelte/svelte-element\ntitle: <svelte:options>, use_cases: migration, custom elements, web components, legacy mode compatibility, runes mode setup, svg components, mathml components, css injection control, path: svelte/svelte-options\ntitle: Stores, use_cases: shared state, cross-component data, reactive values, async data streams, manual control over updates, rxjs integration, extracting logic, path: svelte/stores\ntitle: Context, use_cases: shared state, avoiding prop drilling, component communication, theme providers, user context, authentication state, configuration sharing, deeply nested components, path: svelte/context\ntitle: Lifecycle hooks, use_cases: component initialization, cleanup tasks, timers, subscriptions, dom measurements, chat windows, autoscroll features, migration from svelte 4, path: svelte/lifecycle-hooks\ntitle: Imperative component API, use_cases: project setup, client-side rendering, server-side rendering, ssr, hydration, testing, programmatic component creation, tooltips, dynamic mounting, path: svelte/imperative-component-api\ntitle: Hydratable data, use_cases: use title and path to estimate use case, path: svelte/hydratable\ntitle: Testing, use_cases: testing, quality assurance, unit tests, integration tests, component tests, e2e tests, vitest setup, playwright setup, test automation, path: svelte/testing\ntitle: TypeScript, use_cases: typescript setup, type safety, component props typing, generic components, wrapper components, dom type augmentation, project configuration, path: svelte/typescript\ntitle: Custom elements, use_cases: web components, custom elements, component library, design system, framework-agnostic components, embedding svelte in non-svelte apps, shadow dom, path: svelte/custom-elements\ntitle: Svelte 4 migration guide, use_cases: upgrading svelte 3 to 4, version migration, updating dependencies, breaking changes, legacy project maintenance, path: svelte/v4-migration-guide\ntitle: Svelte 5 migration guide, use_cases: migrating from svelte 4 to 5, upgrading projects, learning svelte 5 syntax changes, runes migration, event handler updates, path: svelte/v5-migration-guide\ntitle: Frequently asked questions, use_cases: getting started, learning svelte, beginner setup, project initialization, vs code setup, formatting, testing, routing, mobile apps, troubleshooting, community support, path: svelte/faq\ntitle: svelte, use_cases: migration from svelte 4 to 5, upgrading legacy code, component lifecycle hooks, context api, mounting components, event dispatchers, typescript component types, path: svelte/svelte\ntitle: svelte/action, use_cases: typescript types, actions, use directive, dom manipulation, element lifecycle, custom behaviors, third-party library integration, path: svelte/svelte-action\ntitle: svelte/animate, use_cases: animated lists, sortable items, drag and drop, reordering elements, todo lists, kanban boards, playlist management, smooth position transitions, path: svelte/svelte-animate\ntitle: svelte/attachments, use_cases: library development, component libraries, programmatic element manipulation, migrating from actions to attachments, spreading props onto elements, path: svelte/svelte-attachments\ntitle: svelte/compiler, use_cases: build tools, custom compilers, ast manipulation, preprocessors, code transformation, migration scripts, syntax analysis, bundler plugins, dev tools, path: svelte/svelte-compiler\ntitle: svelte/easing, use_cases: animations, transitions, custom easing, smooth motion, interactive ui, modals, dropdowns, carousels, page transitions, scroll effects, path: svelte/svelte-easing\ntitle: svelte/events, use_cases: window events, document events, global event listeners, event delegation, programmatic event handling, cleanup functions, media queries, path: svelte/svelte-events\ntitle: svelte/legacy, use_cases: migration from svelte 4 to svelte 5, upgrading legacy code, event modifiers, class components, imperative component instantiation, path: svelte/svelte-legacy\ntitle: svelte/motion, use_cases: animation, smooth transitions, interactive ui, sliders, counters, physics-based motion, drag gestures, accessibility, reduced motion, path: svelte/svelte-motion\ntitle: svelte/reactivity/window, use_cases: responsive design, viewport tracking, scroll effects, window resize handling, online/offline detection, zoom level tracking, path: svelte/svelte-reactivity-window\ntitle: svelte/reactivity, use_cases: reactive data structures, state management with maps/sets, game boards, selection tracking, url manipulation, query params, real-time clocks, media queries, responsive design, path: svelte/svelte-reactivity\ntitle: svelte/server, use_cases: server-side rendering, ssr, static site generation, seo optimization, initial page load, pre-rendering, node.js server, custom server setup, path: svelte/svelte-server\ntitle: svelte/store, use_cases: state management, shared data, reactive stores, cross-component communication, global state, computed values, data synchronization, legacy svelte projects, path: svelte/svelte-store\ntitle: svelte/transition, use_cases: animations, transitions, interactive ui, modals, dropdowns, tooltips, notifications, svg animations, list animations, page transitions, path: svelte/svelte-transition\ntitle: Compiler errors, use_cases: animation, transitions, keyed each blocks, list animations, path: svelte/compiler-errors\ntitle: Compiler warnings, use_cases: accessibility, a11y compliance, wcag standards, screen readers, keyboard navigation, aria attributes, semantic html, interactive elements, path: svelte/compiler-warnings\ntitle: Runtime errors, use_cases: debugging errors, error handling, troubleshooting runtime issues, migration to svelte 5, component binding, effects and reactivity, path: svelte/runtime-errors\ntitle: Runtime warnings, use_cases: debugging state proxies, console logging reactive values, inspecting state changes, development troubleshooting, path: svelte/runtime-warnings\ntitle: Overview, use_cases: migrating from svelte 3/4 to svelte 5, maintaining legacy components, understanding deprecated features, gradual upgrade process, path: svelte/legacy-overview\ntitle: Reactive let/var declarations, use_cases: migration, legacy svelte projects, upgrading from svelte 4, understanding old reactivity, maintaining existing code, learning runes differences, path: svelte/legacy-let\ntitle: Reactive $: statements, use_cases: legacy mode, migration from svelte 4, reactive statements, computed values, derived state, side effects, path: svelte/legacy-reactive-assignments\ntitle: export let, use_cases: legacy mode, migration from svelte 4, maintaining older projects, component props without runes, exporting component methods, renaming reserved word props, path: svelte/legacy-export-let\ntitle: $$props and $$restProps, use_cases: legacy mode migration, component wrappers, prop forwarding, button components, reusable ui components, spreading props to child elements, path: svelte/legacy-$$props-and-$$restProps\ntitle: on:, use_cases: legacy mode, event handling, button clicks, forms, user interactions, component communication, event forwarding, event modifiers, path: svelte/legacy-on\ntitle: <slot>, use_cases: legacy mode, migrating from svelte 4, component composition, reusable components, passing content to components, modals, layouts, wrappers, path: svelte/legacy-slots\ntitle: $$slots, use_cases: legacy mode, conditional slot rendering, optional content sections, checking if slots provided, migrating from legacy to runes, path: svelte/legacy-$$slots\ntitle: <svelte:fragment>, use_cases: named slots, component composition, layout systems, avoiding wrapper divs, legacy svelte projects, slot content organization, path: svelte/legacy-svelte-fragment\ntitle: <svelte:component>, use_cases: dynamic components, component switching, conditional rendering, legacy mode migration, tabbed interfaces, multi-step forms, path: svelte/legacy-svelte-component\ntitle: <svelte:self>, use_cases: recursive components, tree structures, nested menus, file explorers, comment threads, hierarchical data, path: svelte/legacy-svelte-self\ntitle: Imperative component API, use_cases: migration from svelte 3/4 to 5, legacy component api, maintaining old projects, understanding deprecated patterns, path: svelte/legacy-component-api\n\n</available-docs>\n\nThese are the available documentation sections that `list-sections` will return, you do not need to call it again.\n\nEvery time you write a Svelte component or a Svelte module you MUST invoke the `svelte-autofixer` tool providing the code. The tool will return a list of issues or suggestions. If there are any issues or suggestions you MUST fix them and call the tool again with the updated code. You MUST keep doing this until the tool returns no issues or suggestions. Only then you can return the code to the user.\n\nThis is the task you will work on:\n\n<task>\n[YOUR TASK HERE]\n</task>\n\nIf you are not writing the code into a file, once you have the final version of the code ask the user if it wants to generate a playground link to quickly check the code in it and if it answer yes call the `playground-link` tool and return the url to the user nicely formatted. The playground link MUST be generated only once you have the final version of the code and you are ready to share it, it MUST include an entry point file called `App.svelte` where the main component should live. If you have multiple files to include in the playground link you can include them all at the root.\n```\n\n</details>","size_bytes":35276,"metadata":{"title":"Prompts"},"created_at":"2026-02-28T02:00:03.938Z","updated_at":"2026-02-28T02:00:03.938Z"},{"path":"apps/svelte.dev/content/docs/ai/40-claude-plugin/plugin.md","title":"Overview","filename":"plugin.md","content":"The open source [repository](https://github.com/sveltejs/ai-tools) containing the code for the MCP server is also a Claude Code Marketplace plugin.\n\nThe marketplace allows you to install the `svelte` plugin which will give you the remote MCP server, [skills](skills) to instruct the LLM on how to properly write Svelte 5 code, and a specialized agent for editing Svelte files.\n\nIf possible, we recommend that you instruct the LLM to execute MCP calls with the agent (you can explicitly mention an agent in your message to delegate work to it) when creating or editing `.svelte` files or `.svelte.ts`/`.svelte.js` modules as it helps save context by handling Svelte-specific tasks more efficiently.\n\n## Installation\n\nTo add the repository as a marketplace, launch Claude Code and type the following:\n\n```bash\n/plugin marketplace add sveltejs/ai-tools\n```\n\nThen, install the Svelte plugin:\n\n```bash\n/plugin install svelte\n```","size_bytes":949,"metadata":{"title":"Overview"},"created_at":"2026-02-28T02:00:03.889Z","updated_at":"2026-02-28T02:00:03.889Z"},{"path":"apps/svelte.dev/content/docs/ai/40-claude-plugin/subagent.md","title":"Subagent","filename":"subagent.md","content":"The Svelte plugin includes a specialized subagent called `svelte-file-editor` designed for creating, editing, and reviewing Svelte files.\n\n## Benefits\n\nThe subagent has access to its own context window, allowing it to fetch the documentation, iterate with the `svelte-autofixer` tool and write to the file system without wasting context in the main agent.\n\nThe delegation should happen automatically when appropriate, but you can also explicitly request the subagent be used for Svelte-related tasks.","size_bytes":526,"metadata":{"title":"Subagent"},"created_at":"2026-02-28T02:00:03.891Z","updated_at":"2026-02-28T02:00:03.891Z"},{"path":"apps/svelte.dev/content/docs/ai/50-opencode-plugin/opencode-plugin.md","title":"Overview","filename":"opencode-plugin.md","content":"OpenCode has a [plugin system](https://opencode.ai/docs/plugins/) that allows developers to add MCP servers, agents and commands programmatically. Svelte has an OpenCode plugin published under `@sveltejs/opencode`.\n\n## Installation\n\nTo install the plugin in OpenCode you can edit your [OpenCode config]() (either the global or the local one), adding `@sveltejs/opencode` to the list of plugins.\n\n```json\n{\n\t\"$schema\": \"https://opencode.ai/config.json\",\n\t\"plugin\": [\"@sveltejs/opencode\"]\n}\n```\n\nThat's it! You now have the Svelte MCP server, [skills](skills), and the [file editor subagent](opencode-subagent) configured for you.\n\n## Configuration\n\nThe default configuration for the Svelte OpenCode plugin looks like this...\n\n```json\n{\n\t\"$schema\": \"https://raw.githubusercontent.com/sveltejs/ai-tools/refs/heads/main/packages/opencode/schema.json\",\n\t\"mcp\": {\n\t\t\"type\": \"remote\",\n\t\t\"enabled\": true\n\t},\n\t\"subagent\": {\n\t\t\"enabled\": true\n\t},\n\t\"skills\": {\n\t\t\"enabled\": true\n\t},\n\t\"instructions\": {\n\t\t\"enabled\": true\n\t}\n}\n```\n\n...but if you prefer, you can enable only the subagent, only the MCP, only the skills, or configure the kind of MCP server you want to use (`local` or `remote`).\n\nYou can place this file in `./.opencode/svelte.json` (in your project), in `~/.config/opencode/svelte.json` or, if you have an `OPENCODE_CONFIG_DIR` environment variable specified, at `$OPENCODE_CONFIG_DIR/svelte.json`.","size_bytes":1427,"metadata":{"title":"Overview"},"created_at":"2026-02-28T02:00:03.896Z","updated_at":"2026-02-28T02:00:03.896Z"},{"path":"apps/svelte.dev/content/docs/ai/50-opencode-plugin/opencode-subagent.md","title":"Subagent","filename":"opencode-subagent.md","content":"The Svelte plugin includes a specialized subagent called `svelte-file-editor` designed for creating, editing, and reviewing Svelte files.\n\n## Benefits\n\nThe subagent has access to its own context window, allowing it to fetch the documentation, iterate with the `svelte-autofixer` tool and write to the file system without wasting context in the main agent.\n\nThe delegation should happen automatically when appropriate, but you can also explicitly request the subagent be used for Svelte-related tasks.","size_bytes":526,"metadata":{"title":"Subagent"},"created_at":"2026-02-28T02:00:03.896Z","updated_at":"2026-02-28T02:00:03.896Z"},{"path":"apps/svelte.dev/content/docs/ai/60-skills/10-skills.md","title":"Overview","filename":"10-skills.md","content":"This is the list of available skills provided by the Svelte MCP package. Skills are sets of instructions that AI agents can load on-demand to help with specific tasks.\n\nSkills are available in both the Claude Code plugin (installed via the marketplace) and the OpenCode plugin (`@sveltejs/opencode`). They can also be manually installed in your `.claude/skills/` or `.opencode/skills/` folder.\n\nYou can download the latest skills from the [releases page](https://github.com/sveltejs/ai-tools/releases) or find them in the [`plugins/svelte/skills`](https://github.com/sveltejs/ai-tools/tree/main/plugins/svelte/skills) folder.\n\n## `svelte-code-writer`\n\nCLI tools for Svelte 5 documentation lookup and code analysis. MUST be used whenever creating, editing or analyzing any Svelte component (.svelte) or Svelte module (.svelte.ts/.svelte.js). If possible, this skill should be executed within the svelte-file-editor agent for optimal results.\n\n<a href=\"https://github.com/sveltejs/ai-tools/releases?q=svelte-code-writer\" target=\"_blank\" rel=\"noopener noreferrer\">Open Releases page</a>\n\n<details>\n\t<summary>View skill content</summary>\n\n<!-- prettier-ignore-start -->\n````markdown\n# Svelte 5 Code Writer\n\n## CLI Tools\n\nYou have access to `@sveltejs/mcp` CLI for Svelte-specific assistance. Use these commands via `npx`:\n\n### List Documentation Sections\n\n```bash\nnpx @sveltejs/mcp list-sections\n```\n\nLists all available Svelte 5 and SvelteKit documentation sections with titles and paths.\n\n### Get Documentation\n\n```bash\nnpx @sveltejs/mcp get-documentation \"<section1>,<section2>,...\"\n```\n\nRetrieves full documentation for specified sections. Use after `list-sections` to fetch relevant docs.\n\n**Example:**\n\n```bash\nnpx @sveltejs/mcp get-documentation \"$state,$derived,$effect\"\n```\n\n### Svelte Autofixer\n\n```bash\nnpx @sveltejs/mcp svelte-autofixer \"<code_or_path>\" [options]\n```\n\nAnalyzes Svelte code and suggests fixes for common issues.\n\n**Options:**\n\n`--async` - Enable async Svelte mode (default: false)\n`--svelte-version` - Target version: 4 or 5 (default: 5)\n\n**Examples:**\n\n```bash\n# Analyze inline code (escape $ as \\$)\nnpx @sveltejs/mcp svelte-autofixer '<script>let count = \\$state(0);</script>'\n\n# Analyze a file\nnpx @sveltejs/mcp svelte-autofixer ./src/lib/Component.svelte\n\n# Target Svelte 4\nnpx @sveltejs/mcp svelte-autofixer ./Component.svelte --svelte-version 4\n```\n\n**Important:** When passing code with runes (`$state`, `$derived`, etc.) via the terminal, escape the `$` character as `\\$` to prevent shell variable substitution.\n\n## Workflow\n\n1. **Uncertain about syntax?** Run `list-sections` then `get-documentation` for relevant topics\n2. **Reviewing/debugging?** Run `svelte-autofixer` on the code to detect issues\n3. **Always validate** - Run `svelte-autofixer` before finalizing any Svelte component\n````\n<!-- prettier-ignore-end -->\n\n</details>\n\n## `svelte-core-bestpractices`\n\nGuidance on writing fast, robust, modern Svelte code. Load this skill whenever in a Svelte project and asked to write/edit or analyze a Svelte component or module. Covers reactivity, event handling, styling, integration with libraries and more.\n\n<a href=\"https://github.com/sveltejs/ai-tools/releases?q=svelte-core-bestpractices\" target=\"_blank\" rel=\"noopener noreferrer\">Open Releases page</a>\n\n<details>\n\t<summary>View skill content</summary>\n\n<!-- prettier-ignore-start -->\n````markdown\n## `$state`\n\nOnly use the `$state` rune for variables that should be _reactive_ — in other words, variables that cause an `$effect`, `$derived` or template expression to update. Everything else can be a normal variable.\n\nObjects and arrays (`$state({...})` or `$state([...])`) are made deeply reactive, meaning mutation will trigger updates. This has a trade-off: in exchange for fine-grained reactivity, the objects must be proxied, which has performance overhead. In cases where you're dealing with large objects that are only ever reassigned (rather than mutated), use `$state.raw` instead. This is often the case with API responses, for example.\n\n## `$derived`\n\nTo compute something from state, use `$derived` rather than `$effect`:\n\n```js\n// do this\nlet square = $derived(num * num);\n\n// don't do this\nlet square;\n\n$effect(() => {\n\tsquare = num * num;\n});\n```\n\n\nDeriveds are writable — you can assign to them, just like `$state`, except that they will re-evaluate when their expression changes.\n\nIf the derived expression is an object or array, it will be returned as-is — it is _not_ made deeply reactive. You can, however, use `$state` inside `$derived.by` in the rare cases that you need this.\n\n## `$effect`\n\nEffects are an escape hatch and should mostly be avoided. In particular, avoid updating state inside effects.\n\nIf you need to sync state to an external library such as D3, it is often neater to use [`{@attach ...}`](references/@attach.md)\nIf you need to run some code in response to user interaction, put the code directly in an event handler or use a [function binding](references/bind.md) as appropriate\nIf you need to log values for debugging purposes, use [`$inspect`](references/$inspect.md)\nIf you need to observe something external to Svelte, use [`createSubscriber`](references/svelte-reactivity.md)\n\nNever wrap the contents of an effect in `if (browser) {...}` or similar — effects do not run on the server.\n\n## `$props`\n\nTreat props as though they will change. For example, values that depend on props should usually use `$derived`:\n\n```js\n// @errors: 2451\nlet { type } = $props();\n\n// do this\nlet color = $derived(type === 'danger' ? 'red' : 'green');\n\n// don't do this — `color` will not update if `type` changes\nlet color = type === 'danger' ? 'red' : 'green';\n```\n\n## `$inspect.trace`\n\n`$inspect.trace` is a debugging tool for reactivity. If something is not updating properly or running more than it should you can add `$inspect.trace(label)` as the first line of an `$effect` or `$derived.by` (or any function they call) to trace their dependencies and discover which one triggered an update.\n\n## Events\n\nAny element attribute starting with `on` is treated as an event listener:\n\n```svelte\n<button onclick={() => {...}}>click me</button>\n\n<!-- attribute shorthand also works -->\n<button {onclick}>...</button>\n\n<!-- so do spread attributes -->\n<button {...props}>...</button>\n```\n\nIf you need to attach listeners to `window` or `document` you can use `<svelte:window>` and `<svelte:document>`:\n\n```svelte\n<svelte:window onkeydown={...} />\n<svelte:document onvisibilitychange={...} />\n```\n\nAvoid using `onMount` or `$effect` for this.\n\n## Snippets\n\n[Snippets](references/snippet.md) are a way to define reusable chunks of markup that can be instantiated with the [`{@render ...}`](references/@render.md) tag, or passed to components as props. They must be declared within the template.\n\n```svelte\n{#snippet greeting(name)}\n\t<p>hello {name}!</p>\n{/snippet}\n\n{@render greeting('world')}\n```\n\n\n## Each blocks\n\nPrefer to use [keyed each blocks](references/each.md) — this improves performance by allowing Svelte to surgically insert or remove items rather than updating the DOM belonging to existing items.\n\n\nAvoid destructuring if you need to mutate the item (with something like `bind:value={item.count}`, for example).\n\n## Using JavaScript variables in CSS\n\nIf you have a JS variable that you want to use inside CSS you can set a CSS custom property with the `style:` directive.\n\n```svelte\n<div style:--columns={columns}>...</div>\n```\n\nYou can then reference `var(--columns)` inside the component's `<style>`.\n\n## Styling child components\n\nThe CSS in a component's `<style>` is scoped to that component. If a parent component needs to control the child's styles, the preferred way is to use CSS custom properties:\n\n```svelte\n<!-- Parent.svelte -->\n<Child --color=\"red\" />\n\n<!-- Child.svelte -->\n<h1>Hello</h1>\n\n<style>\n\th1 {\n\t\tcolor: var(--color);\n\t}\n</style>\n```\n\nIf this impossible (for example, the child component comes from a library) you can use `:global` to override styles:\n\n```svelte\n<div>\n\t<Child />\n</div>\n\n<style>\n\tdiv :global {\n\t\th1 {\n\t\t\tcolor: red;\n\t\t}\n\t}\n</style>\n```\n\n## Context\n\nConsider using context instead of declaring state in a shared module. This will scope the state to the part of the app that needs it, and eliminate the possibility of it leaking between users when server-side rendering.\n\nUse `createContext` rather than `setContext` and `getContext`, as it provides type safety.\n\n## Async Svelte\n\nIf using version 5.36 or higher, you can use [await expressions](references/await-expressions.md) and [hydratable](references/hydratable.md) to use promises directly inside components. Note that these require the `experimental.async` option to be enabled in `svelte.config.js` as they are not yet considered fully stable.\n\n## Avoid legacy features\n\nAlways use runes mode for new code, and avoid features that have more modern replacements:\n\nuse `$state` instead of implicit reactivity (e.g. `let count = 0; count += 1`)\nuse `$derived` and `$effect` instead of `$:` assignments and statements (but only use effects when there is no better solution)\nuse `$props` instead of `export let`, `$$props` and `$$restProps`\nuse `onclick={...}` instead of `on:click={...}`\nuse `{#snippet ...}` and `{@render ...}` instead of `<slot>` and `$$slots` and `<svelte:fragment>`\nuse `<DynamicComponent>` instead of `<svelte:component this={DynamicComponent}>`\nuse `import Self from './ThisComponent.svelte'` and `<Self>` instead of `<svelte:self>`\nuse classes with `$state` fields to share reactivity between components, instead of using stores\nuse `{@attach ...}` instead of `use:action`\nuse clsx-style arrays and objects in `class` attributes, instead of the `class:` directive\n````\n<!-- prettier-ignore-end -->\n\n</details>","size_bytes":9792,"metadata":{"title":"Overview"},"created_at":"2026-02-28T02:00:03.897Z","updated_at":"2026-02-28T02:00:03.897Z"},{"path":"apps/svelte.dev/content/docs/cli/10-introduction/10-overview.md","title":"Overview","filename":"10-overview.md","content":"The command line interface (CLI), `sv`, is a toolkit for creating and maintaining Svelte applications.\n\n## Usage\n\nThe easiest way to run `sv` is with [`npx`](https://docs.npmjs.com/cli/v8/commands/npx) (or the equivalent command if you're using a different package manager — for example, `pnpm dlx` if you're using [pnpm](https://pnpm.io/)):\n\n```sh\nnpx sv <command> <args>\n```\n\nIf you're inside a project where `sv` is already installed, this will use the local installation, otherwise it will download the latest version and run it without installing it, which is particularly useful for [`sv create`](sv-create).\n\n## Acknowledgements\n\nThank you to [Christopher Brown](https://github.com/chbrown) who originally owned the `sv` name on npm for graciously allowing it to be used for the Svelte CLI. You can find the original `sv` package at [`@chbrown/sv`](https://www.npmjs.com/package/@chbrown/sv).","size_bytes":927,"metadata":{"title":"Overview"},"created_at":"2025-07-18T15:47:38.675Z","updated_at":"2026-03-01T14:00:04.020Z"},{"path":"apps/svelte.dev/content/docs/cli/10-introduction/20-faq.md","title":"Frequently asked questions","filename":"20-faq.md","content":"## How do I run the `sv` CLI?\n\nRunning `sv` looks slightly different for each package manager. Here is a list of the most common commands:\n\n- **npm** : `npx sv create`\n- **pnpm** : `pnpm dlx sv create`\n- **Bun** : `bunx sv create`\n- **Deno** : `deno run npm:sv create`\n- **Yarn** : `yarn dlx sv create`\n\n## `npx sv` is not working\n\nSome package managers prefer to run locally installed tools instead of downloading and executing packages from the registry. This issue mostly occurs with `npm` and `yarn`. This usually results in an error message or looks like the command you were trying to execute did not do anything.\n\nHere is a list of issues with possible solutions that users have encountered in the past:\n\n- [`npx sv` create does nothing](https://github.com/sveltejs/cli/issues/472)\n- [`sv` command name collides with `runit`](https://github.com/sveltejs/cli/issues/259)\n- [`sv` in windows powershell conflicts with `Set-Variable`](https://github.com/sveltejs/cli/issues/317)","size_bytes":1025,"metadata":{"title":"Frequently asked questions"},"created_at":"2025-07-18T15:47:38.676Z","updated_at":"2026-03-01T14:00:04.034Z"},{"path":"apps/svelte.dev/content/docs/cli/20-commands/10-sv-create.md","title":"sv create","filename":"10-sv-create.md","content":"`sv create` sets up a new SvelteKit project, with options to [setup additional functionality](sv-add#Official-add-ons).\n\n## Usage\n\n```sh\nnpx sv create [options] [path]\n```\n\n## Options\n\n### `--from-playground <url>`\n\nCreate a SvelteKit project from a [playground](/playground) URL. This downloads all playground files, detects external dependencies, and sets up a complete SvelteKit project structure with everything ready to go.\n\nExample:\n\n```sh\nnpx sv create --from-playground=\"https://svelte.dev/playground/hello-world\"\n```\n\n### `--template <name>`\n\nWhich project template to use:\n\n- `minimal` — barebones scaffolding for your new app\n- `demo` — showcase app with a word guessing game that works without JavaScript\n- `library` — template for a Svelte library, set up with `svelte-package`\n  <!-- TODO: JYC: Uncomment this when the addon template is ready -->\n  <!-- - `addon` — template for a community add-on, ready to be tested & published -->\n\n### `--types <option>`\n\nWhether and how to add typechecking to the project:\n\n- `ts` — default to `.ts` files and use `lang=\"ts\"` for `.svelte` components\n- `jsdoc` — use [JSDoc syntax](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) for types\n\n### `--no-types`\n\nPrevent typechecking from being added. Not recommended!\n\n### `--add [add-ons...]`\n\nAdd add-ons to the project in the `create` command. Following the same format as [sv add](sv-add#Usage).\n\nExample:\n\n```sh\nnpx sv create --add eslint prettier [path]\n```\n\n### `--no-add-ons`\n\nRun the command without the interactive add-ons prompt\n\n### `--install <package-manager>`\n\nInstalls dependencies with a specified package manager:\n\n- `npm`\n- `pnpm`\n- `yarn`\n- `bun`\n- `deno`\n\n### `--no-install`\n\nPrevents installing dependencies.\n\n### `--no-dir-check`\n\nSkip checking whether the target directory is empty.","size_bytes":1869,"metadata":{"title":"sv create"},"created_at":"2025-07-18T15:47:38.679Z","updated_at":"2026-02-14T01:33:24.838Z"},{"path":"apps/svelte.dev/content/docs/cli/20-commands/20-sv-add.md","title":"sv add","filename":"20-sv-add.md","content":"`sv add` updates an existing project with new functionality.\n\n## Usage\n\n```sh\nnpx sv add\n```\n\n```sh\nnpx sv add [add-ons]\n```\n\nYou can select multiple space-separated add-ons from [the list below](#Official-add-ons), or you can use the interactive prompt.\n\n## Options\n\n### `-C`, `--cwd`\n\nPath to the root of your Svelte(Kit) project.\n\n### `--no-git-check`\n\nEven if some files are dirty, no prompt will be shown\n\n### `--no-download-check`\n\nSkip all download confirmation prompts\n\n> [!IMPORTANT]\n> Svelte maintainers have not reviewed community add-ons for malicious code. Use at your discretion\n\n### `--install <package-manager>`\n\nInstalls dependencies with a specified package manager:\n\n- `npm`\n- `pnpm`\n- `yarn`\n- `bun`\n- `deno`\n\n### `--no-install`\n\nPrevents installing dependencies\n\n## Official add-ons\n\n- [`better-auth`](better-auth)\n- [`devtools-json`](devtools-json)\n- [`drizzle`](drizzle)\n- [`eslint`](eslint)\n- [`mcp`](mcp)\n- [`mdsvex`](mdsvex)\n- [`paraglide`](paraglide)\n- [`playwright`](playwright)\n- [`prettier`](prettier)\n- [`storybook`](storybook)\n- [`sveltekit-adapter`](sveltekit-adapter)\n- [`tailwindcss`](tailwind)\n- [`vitest`](vitest)\n\n## Community add-ons\n\n> Community add-ons are currently **experimental**. The API may change. Don't use them in production yet!\n\n> Svelte maintainers have not reviewed community add-ons for malicious code!\n\nYou can find [community add-ons on npm](https://www.npmjs.com/search?q=keywords%3Asv-add) by searching for `keywords:sv-add`.\n\n### How to install a community add-on\n\n```sh\nnpx sv add [PROTOCOL][COMMUNITY_ADDON]\n```\n\nYou can:\n\n- mix and match official and community add-ons\n- use the interactive prompt or give args to the cli\n- use the `--add` option in the `create` command\n\n```sh\nnpx sv add eslint \"@supacool\"\n```\n\n```sh\nnpx sv create --add eslint \"@supacool\"\n```\n\n### Package Protocols\n\n```sh\n# Scoped package: @org (preferred), we will look for @org/sv\nnpx sv add \"@supacool\"\n\n# Regular npm package (with or without scope)\nnpx sv add my-cool-addon\n\n# Local add-on\nnpx sv add file:../path/to/my-addon\n```\n\n### How to create a community add-on\n\nTo start on a good track, create your add-on with the `addon` template.\n\n```sh\nnpx sv create --template addon [path]\n```\n\nIn your new add-on directory, check out the `README.md` and `CONTRIBUTING.md` to get started.\n\nThen you can continue with the [API docs](/docs/cli/add-on) to start building your add-on. You can also have a look at the [official addons source code](https://github.com/sveltejs/cli/tree/main/packages/sv/src/addons) to get some inspiration on what can be done.","size_bytes":2610,"metadata":{"title":"sv add"},"created_at":"2025-07-18T15:47:38.680Z","updated_at":"2026-02-21T14:00:04.059Z"},{"path":"apps/svelte.dev/content/docs/cli/20-commands/30-sv-check.md","title":"sv check","filename":"30-sv-check.md","content":"`sv check` finds errors and warnings in your project, such as:\n\n- unused CSS\n- accessibility hints\n- JavaScript/TypeScript compiler errors\n\nRequires Node 16 or later.\n\n## Installation\n\nYou will need to have the `svelte-check` package installed in your project:\n\n```sh\nnpm i -D svelte-check\n```\n\n## Usage\n\n```sh\nnpx sv check\n```\n\n## Options\n\n### `--workspace <path>`\n\nPath to your workspace. All subdirectories except `node_modules` and those listed in `--ignore` are checked.\n\n### `--output <format>`\n\nHow to display errors and warnings. See [machine-readable output](#Machine-readable-output).\n\n- `human`\n- `human-verbose`\n- `machine`\n- `machine-verbose`\n\n### `--watch`\n\nKeeps the process alive and watches for changes.\n\n### `--preserveWatchOutput`\n\nPrevents the screen from being cleared in watch mode.\n\n### `--tsconfig <path>`\n\nPass a path to a `tsconfig` or `jsconfig` file. The path can be relative to the workspace path or absolute. Doing this means that only files matched by the `files`/`include`/`exclude` pattern of the config file are diagnosed. It also means that errors from TypeScript and JavaScript files are reported. If not given, will traverse upwards from the project directory looking for the next `jsconfig`/`tsconfig.json` file.\n\n### `--no-tsconfig`\n\nUse this if you only want to check the Svelte files found in the current directory and below and ignore any `.js`/`.ts` files (they will not be type-checked)\n\n### `--ignore <paths>`\n\nFiles/folders to ignore, relative to workspace root. Paths should be comma-separated and quoted. Example:\n\n```sh\nnpx sv check --ignore \"dist,build\"\n```\n\n<!-- TODO what the hell does this mean? is it possible to use --tsconfig AND --no-tsconfig? if so what would THAT mean? -->\n\nOnly has an effect when used in conjunction with `--no-tsconfig`. When used in conjunction with `--tsconfig`, this will only have effect on the files watched, not on the files that are diagnosed, which is then determined by the `tsconfig.json`.\n\n### `--fail-on-warnings`\n\nIf provided, warnings will cause `sv check` to exit with an error code.\n\n### `--compiler-warnings <warnings>`\n\nA quoted, comma-separated list of `code:behaviour` pairs where `code` is a [compiler warning code](../svelte/compiler-warnings) and `behaviour` is either `ignore` or `error`:\n\n```sh\nnpx sv check --compiler-warnings \"css_unused_selector:ignore,a11y_missing_attribute:error\"\n```\n\n### `--diagnostic-sources <sources>`\n\nA quoted, comma-separated list of sources that should run diagnostics on your code. By default, all are active:\n\n<!-- TODO would be nice to have a clearer definition of what these are -->\n- `js` (includes TypeScript)\n- `svelte`\n- `css`\n\nExample:\n\n```sh\nnpx sv check --diagnostic-sources \"js,svelte\"\n```\n\n### `--threshold <level>`\n\nFilters the diagnostics:\n\n- `warning` (default) — both errors and warnings are shown\n- `error` — only errors are shown\n\n## Troubleshooting\n\n[See the language-tools documentation](https://github.com/sveltejs/language-tools/blob/master/docs/README.md) for more information on preprocessor setup and other troubleshooting.\n\n## Machine-readable output\n\nSetting the `--output` to `machine` or `machine-verbose` will format output in a way that is easier to read\nby machines, e.g. inside CI pipelines, for code quality checks, etc.\n\nEach row corresponds to a new record. Rows are made up of columns that are separated by a\nsingle space character. The first column of every row contains a timestamp in milliseconds\nwhich can be used for monitoring purposes. The second column gives us the \"row type\", based\non which the number and types of subsequent columns may differ.\n\nThe first row is of type `START` and contains the workspace folder (wrapped in quotes). Example:\n\n```\n1590680325583 START \"/home/user/language-tools/packages/language-server/test/plugins/typescript/testfiles\"\n```\n\nAny number of `ERROR` or `WARNING` records may follow. Their structure is identical and depends on the output argument.\n\nIf the argument is `machine` it will tell us the filename, the starting line and column numbers, and the error message. The filename is relative to the workspace directory. The filename and the message are both wrapped in quotes. Example:\n\n```\n1590680326283 ERROR \"codeactions.svelte\" 1:16 \"Cannot find module 'blubb' or its corresponding type declarations.\"\n1590680326778 WARNING \"imported-file.svelte\" 0:37 \"Component has unused export property 'prop'. If it is for external reference only, please consider using `export const prop`\"\n```\n\nIf the argument is `machine-verbose` it will tell us the filename, the starting line and column numbers, the ending line and column numbers, the error message, the code of diagnostic, the human-friendly description of the code and the human-friendly source of the diagnostic (eg. svelte/typescript). The filename is relative to the workspace directory. Each diagnostic is represented as an [ndjson](https://en.wikipedia.org/wiki/JSON_streaming#Newline-Delimited_JSON) line prefixed by the timestamp of the log. Example:\n\n```\n1590680326283 {\"type\":\"ERROR\",\"fn\":\"codeaction.svelte\",\"start\":{\"line\":1,\"character\":16},\"end\":{\"line\":1,\"character\":23},\"message\":\"Cannot find module 'blubb' or its corresponding type declarations.\",\"code\":2307,\"source\":\"js\"}\n1590680326778 {\"type\":\"WARNING\",\"filename\":\"imported-file.svelte\",\"start\":{\"line\":0,\"character\":37},\"end\":{\"line\":0,\"character\":51},\"message\":\"Component has unused export property 'prop'. If it is for external reference only, please consider using `export\nconst prop`\",\"code\":\"unused-export-let\",\"source\":\"svelte\"}\n```\n\nThe output concludes with a `COMPLETED` message that summarizes total numbers of files, errors and warnings that were encountered during the check. Example:\n\n```\n1590680326807 COMPLETED 20 FILES 21 ERRORS 1 WARNINGS 3 FILES_WITH_PROBLEMS\n```\n\nIf the application experiences a runtime error, this error will appear as a `FAILURE` record. Example:\n\n```\n1590680328921 FAILURE \"Connection closed\"\n```\n\n## Credits\n\n- Vue's [VTI](https://github.com/vuejs/vetur/tree/master/vti) which laid the foundation for `svelte-check`\n\n## FAQ\n\n### Why is there no option to only check specific files (for example only staged files)?\n\n`svelte-check` needs to 'see' the whole project for checks to be valid. Suppose you renamed a component prop but didn't update any of the places where the prop is used — the usage sites are all errors now, but you would miss them if checks only ran on changed files.","size_bytes":6491,"metadata":{"title":"sv check"},"created_at":"2025-07-18T15:47:38.683Z","updated_at":"2025-07-26T14:00:05.881Z"},{"path":"apps/svelte.dev/content/docs/cli/20-commands/40-sv-migrate.md","title":"sv migrate","filename":"40-sv-migrate.md","content":"`sv migrate` migrates Svelte(Kit) codebases. It delegates to the [`svelte-migrate`](https://www.npmjs.com/package/svelte-migrate) package.\n\nSome migrations may annotate your codebase with tasks for completion that you can find by searching for `@migration`.\n\n## Usage\n\n```sh\nnpx sv migrate\n```\n\nYou can also specify a migration directly via the CLI:\n```sh\nnpx sv migrate [migration]\n```\n\n## Migrations\n\n### `app-state`\n\nMigrates `$app/stores` usage to `$app/state` in `.svelte` files. See the [migration guide](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated) for more details.\n\n### `svelte-5`\n\nUpgrades a Svelte 4 app to use Svelte 5, and updates individual components to use [runes](../svelte/what-are-runes) and other Svelte 5 syntax ([see migration guide](../svelte/v5-migration-guide)).\n\n### `self-closing-tags`\n\nReplaces all the self-closing non-void elements in your `.svelte` files. See the [pull request](https://github.com/sveltejs/kit/pull/12128) for more details.\n\n### `svelte-4`\n\nUpgrades a Svelte 3 app to use Svelte 4 ([see migration guide](../svelte/v4-migration-guide)).\n\n### `sveltekit-2`\n\nUpgrades a SvelteKit 1 app to SvelteKit 2 ([see migration guide](../kit/migrating-to-sveltekit-2)).\n\n### `package`\n\nUpgrades a library using `@sveltejs/package` version 1 to version 2. See the [pull request](https://github.com/sveltejs/kit/pull/8922) for more details.\n\n### `routes`\n\nUpgrades a pre-release SvelteKit app to use the filesystem routing conventions in SvelteKit 1. See the [pull request](https://github.com/sveltejs/kit/discussions/5774) for more details.","size_bytes":1631,"metadata":{"title":"sv migrate"},"created_at":"2025-07-18T15:47:38.684Z","updated_at":"2025-07-26T14:00:05.863Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/03-devtools-json.md","title":"devtools-json","filename":"03-devtools-json.md","content":"The `devtools-json` add-on installs [`vite-plugin-devtools-json`](https://github.com/ChromeDevTools/vite-plugin-devtools-json/), which is a Vite plugin for generating a Chromium DevTools project settings file on-the-fly in the development server. This file is served from `/.well-known/appspecific/com.chrome.devtools.json` and tells Chromium browsers where your project's source code lives so that you can use [the workspaces feature](https://developer.chrome.com/docs/devtools/workspaces) to edit source files in the browser.\n\n> Installing the plugin enables the feature for all users connecting to the dev server with a Chromium browser, and allows the browser to read and write all files within the directory. If you are using Chrome's AI Assistance feature, this may also result in data being sent to Google.\n\n## Alternatives\n\nIf you'd prefer not to install the plugin, but still want to avoid seeing a message about the missing file, you have a couple of options.\n\nFirstly, you can prevent the request from being issued on your machine by disabling the feature in your browser. You can do this in Chrome by visiting `chrome://flags` and disabling the \"DevTools Project Settings\". You may also be interested in disabling \"DevTools Automatic Workspace Folders\" since it’s closely related.\n\nYou can also prevent the web server from issuing a notice regarding the incoming request for all developers of your application by handling the request yourself. For example, you can create a file named `.well-known/appspecific/com.chrome.devtools.json` with the contents `\"Go away, Chrome DevTools!\"` or you can add logic to respond to the request in your [`handle`](https://svelte.dev/docs/kit/hooks#Server-hooks-handle) hook:\n\n```js\n/// file: src/hooks.server.js\nimport { dev } from '$app/environment';\n\nexport function handle({ event, resolve }) {\n\tif (dev && event.url.pathname === '/.well-known/appspecific/com.chrome.devtools.json') {\n\t\treturn new Response(undefined, { status: 404 });\n\t}\n\n\treturn resolve(event);\n}\n```\n\n## Usage\n\n```sh\nnpx sv add devtools-json\n```\n\n## What you get\n\n- `vite-plugin-devtools-json` added to your Vite plugin options","size_bytes":2181,"metadata":{"title":"devtools-json"},"created_at":"2025-07-18T15:47:38.687Z","updated_at":"2026-02-14T01:33:24.840Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/05-drizzle.md","title":"drizzle","filename":"05-drizzle.md","content":"[Drizzle ORM](https://orm.drizzle.team/) is a TypeScript ORM offering both relational and SQL-like query APIs, and which is serverless-ready by design.\n\n## Usage\n\n```sh\nnpx sv add drizzle\n```\n\n## What you get\n\n- a setup that keeps your database access in SvelteKit's server files\n- an `.env` file to store your credentials\n- compatibility with the Better Auth add-on\n- an optional Docker configuration to help with running a local database\n\n## Options\n\n### database\n\nWhich database variant to use:\n\n- `postgresql` — the most popular open source database\n- `mysql` — another popular open source database\n- `sqlite` — file-based database not requiring a database server\n\n```sh\nnpx sv add drizzle=\"database:postgresql\"\n```\n\n### client\n\nThe SQL client to use, depends on `database`:\n\n- For `postgresql`: `postgres.js`, `neon`,\n- For `mysql`: `mysql2`, `planetscale`\n- For `sqlite`: `better-sqlite3`, `libsql`, `turso`\n\n```sh\nnpx sv add drizzle=\"database:postgresql+client:postgres.js\"\n```\n\nDrizzle is compatible with well over a dozen database drivers. We just offer a few of the most common ones here for simplicity, but if you'd like to use another one you can choose one as a placeholder and swap it out for another after setup by choosing from [Drizzle's full list of compatible drivers](https://orm.drizzle.team/docs/connect-overview#next-steps).\n\n### docker\n\nWhether to add Docker Compose configuration. Only available for [`database`](#Options-database) `postgresql` or `mysql`\n\n```sh\nnpx sv add drizzle=\"database:postgresql+client:postgres.js+docker:yes\"\n```","size_bytes":1593,"metadata":{"title":"drizzle"},"created_at":"2025-07-18T15:47:38.689Z","updated_at":"2026-02-14T01:33:24.840Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/10-eslint.md","title":"eslint","filename":"10-eslint.md","content":"[ESLint](https://eslint.org/) finds and fixes problems in your code.\n\n## Usage\n\n```sh\nnpx sv add eslint\n```\n\n## What you get\n\n- the relevant packages installed including `eslint-plugin-svelte`\n- an `eslint.config.js` file\n- updated `.vscode/settings.json`\n- configured to work with TypeScript and `prettier` if you're using those packages","size_bytes":362,"metadata":{"title":"eslint"},"created_at":"2025-07-18T15:47:38.690Z","updated_at":"2025-07-26T14:00:05.866Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/16-better-auth.md","title":"better-auth","filename":"16-better-auth.md","content":"[Better Auth](https://www.better-auth.com/) is a framework-agnostic authentication library for TypeScript.\n\n## Usage\n\n```sh\nnpx sv add better-auth\n```\n\n## What you get\n\n- a complete auth setup for SvelteKit with Drizzle as the database adapter\n- email/password authentication enabled by default\n- optional demo registration and login pages\n\n## Options\n\n### demo\n\nWhich demo pages to include. Available values: `password` (Email & Password), `github` (GitHub OAuth).\n\n```sh\n# Email & Password only (default)\nnpx sv add better-auth=\"demo:password\"\n\n# GitHub OAuth only\nnpx sv add better-auth=\"demo:github\"\n\n# Both Email & Password and GitHub OAuth\nnpx sv add better-auth=\"demo:password,github\"\n```","size_bytes":724,"metadata":{"title":"better-auth"},"created_at":"2026-02-14T01:33:24.837Z","updated_at":"2026-02-14T01:33:24.837Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/17-mcp.md","title":"mcp","filename":"17-mcp.md","content":"[Svelte MCP](/docs/ai/overview) can help your LLM write better Svelte code.\n\n## Usage\n\n```sh\nnpx sv add mcp\n```\n\n## What you get\n\n- An MCP configuration for [local](https://svelte.dev/docs/ai/local-setup) or [remote](https://svelte.dev/docs/ai/remote-setup) setup\n- A [README for agents](https://agents.md/) to help you use the MCP server effectively\n\n## Options\n\n### ide\n\nThe IDE you want to use like `'claude-code'`, `'cursor'`, `'gemini'`, `'opencode'`, `'vscode'`, `'other'`.\n\n```sh\nnpx sv add mcp=\"ide:cursor,vscode\"\n```\n\n### setup\n\nThe setup you want to use.\n\n```sh\nnpx sv add mcp=\"setup:local\"\n```","size_bytes":625,"metadata":{"title":"mcp"},"created_at":"2025-10-18T14:00:06.307Z","updated_at":"2026-02-28T02:00:03.902Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/20-mdsvex.md","title":"mdsvex","filename":"20-mdsvex.md","content":"[mdsvex](https://mdsvex.pngwn.io) is a markdown preprocessor for Svelte components - basically MDX for Svelte. It allows you to use Svelte components in your markdown, or markdown in your Svelte components.\n\n## Usage\n\n```sh\nnpx sv add mdsvex\n```\n\n## What you get\n\n- mdsvex installed and configured in your `svelte.config.js`","size_bytes":348,"metadata":{"title":"mdsvex"},"created_at":"2025-07-18T15:47:38.726Z","updated_at":"2025-07-26T14:00:05.877Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/25-paraglide.md","title":"paraglide","filename":"25-paraglide.md","content":"[Paraglide from Inlang](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) is a compiler-based i18n library that emits tree-shakable message functions with small bundle sizes, no async waterfalls, full type-safety, and more.\n\n## Usage\n\n```sh\nnpx sv add paraglide\n```\n\n## What you get\n\n- Inlang project settings\n- paraglide Vite plugin\n- SvelteKit `reroute` and `handle` hooks\n- `text-direction` and `lang` attributes in `app.html`\n- updated `.gitignore`\n- an optional demo page showing how to use paraglide\n\n## Options\n\n### languageTags\n\nThe languages you'd like to support specified as IETF BCP 47 language tags.\n\n```sh\nnpx sv add paraglide=\"languageTags:en,es\"\n```\n\n### demo\n\nWhether to generate an optional demo page showing how to use paraglide.\n\n```sh\nnpx sv add paraglide=\"demo:yes\"\n```","size_bytes":826,"metadata":{"title":"paraglide"},"created_at":"2025-07-18T15:47:38.726Z","updated_at":"2025-07-26T14:00:05.790Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/30-playwright.md","title":"playwright","filename":"30-playwright.md","content":"[Playwright](https://playwright.dev) browser testing.\n\n## Usage\n\n```sh\nnpx sv add playwright\n```\n\n## What you get\n\n- scripts added in your `package.json`\n- a Playwright config file\n- an updated `.gitignore`\n- a demo test","size_bytes":248,"metadata":{"title":"playwright"},"created_at":"2025-07-18T15:47:38.737Z","updated_at":"2025-07-26T14:00:05.792Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/35-prettier.md","title":"prettier","filename":"35-prettier.md","content":"[Prettier](https://prettier.io) is an opinionated code formatter.\n\n## Usage\n\n```sh\nnpx sv add prettier\n```\n\n## What you get\n\n- scripts in your `package.json`\n- `.prettierignore` and `.prettierrc` files\n- updates to your eslint config if you're using that package","size_bytes":288,"metadata":{"title":"prettier"},"created_at":"2025-07-18T15:47:38.739Z","updated_at":"2025-07-26T14:00:05.793Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/40-storybook.md","title":"storybook","filename":"40-storybook.md","content":"[Storybook](https://storybook.js.org/) is a frontend component workshop.\n\n## Usage\n\n```sh\nnpx sv add storybook\n```\n\n## What you get\n\n- `npx storybook init` run for you from the same convenient `sv` CLI used for all other add-ons\n- [Storybook for SvelteKit](https://storybook.js.org/docs/get-started/frameworks/sveltekit) or [Storybook for Svelte & Vite](https://storybook.js.org/docs/get-started/frameworks/svelte-vite) with default config provided, easy mocking of many SvelteKit modules, automatic link handling, and more.","size_bytes":551,"metadata":{"title":"storybook"},"created_at":"2025-07-18T15:47:38.745Z","updated_at":"2025-07-26T14:00:05.794Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/45-sveltekit-adapter.md","title":"sveltekit-adapter","filename":"45-sveltekit-adapter.md","content":"[SvelteKit adapters](/docs/kit/adapters) allow you to deploy your site to numerous platforms. This add-on allows you to configure officially provided SvelteKit adapters, but a number of [community-provided adapters](https://www.sveltesociety.dev/packages?category=sveltekit-adapters) are also available.\n\n## Usage\n\n```sh\nnpx sv add sveltekit-adapter\n```\n\n## What you get\n\n- the chosen SvelteKit adapter installed and configured in your `svelte.config.js`\n\n## Options\n\n### adapter\n\nWhich SvelteKit adapter to use:\n\n- `auto` — [`@sveltejs/adapter-auto`](/docs/kit/adapter-auto) automatically chooses the proper adapter to use, but is less configurable\n- `node` — [`@sveltejs/adapter-node`](/docs/kit/adapter-node) generates a standalone Node server\n- `static` — [`@sveltejs/adapter-static`](/docs/kit/adapter-static) allows you to use SvelteKit as a static site generator (SSG)\n- `vercel` — [`@sveltejs/adapter-vercel`](/docs/kit/adapter-vercel) allows you to deploy to Vercel\n- `cloudflare` — [`@sveltejs/adapter-cloudflare`](/docs/kit/adapter-cloudflare) allows you to deploy to Cloudflare\n- `netlify` — [`@sveltejs/adapter-netlify`](/docs/kit/adapter-netlify) allows you to deploy to Netlify\n\n```sh\nnpx sv add sveltekit-adapter=\"adapter:node\"\n```\n\n### cloudflare target\n\nWhether to deploy to Cloudflare Workers or Pages. Only available for `cloudflare` adapter.\n\n```sh\nnpx sv add sveltekit-adapter=\"adapter:cloudflare+cfTarget:workers\"\n```","size_bytes":1487,"metadata":{"title":"sveltekit-adapter"},"created_at":"2025-07-18T15:47:38.744Z","updated_at":"2025-12-22T02:00:04.167Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/50-tailwind.md","title":"tailwindcss","filename":"50-tailwind.md","content":"[Tailwind CSS](https://tailwindcss.com/) allows you to rapidly build modern websites without ever leaving your HTML.\n\n## Usage\n\n```sh\nnpx sv add tailwindcss\n```\n\n## What you get\n\n- Tailwind setup following the [Tailwind for SvelteKit guide](https://tailwindcss.com/docs/installation/framework-guides/sveltekit)\n- Tailwind Vite plugin\n- updated `layout.css` and `+layout.svelte` (for SvelteKit) or `app.css` and `App.svelte` (for non-SvelteKit Vite apps)\n- integration with `prettier` if using that package\n\n## Options\n\n### plugins\n\nWhich plugin to use:\n\n- `typography` — [`@tailwindcss/typography`](https://github.com/tailwindlabs/tailwindcss-typography)\n- `forms` — [`@tailwindcss/forms`](https://github.com/tailwindlabs/tailwindcss-forms)\n\n```sh\nnpx sv add tailwindcss=\"plugins:typography\"\n```","size_bytes":828,"metadata":{"title":"tailwindcss"},"created_at":"2025-07-18T15:47:38.746Z","updated_at":"2025-11-18T02:00:05.498Z"},{"path":"apps/svelte.dev/content/docs/cli/30-add-ons/55-vitest.md","title":"vitest","filename":"55-vitest.md","content":"[Vitest](https://vitest.dev/) is a Vite-native testing framework.\n\n## Usage\n\n```sh\nnpx sv add vitest\n```\n\n## What you get\n\n- the relevant packages installed and scripts added to your `package.json`\n- client/server-aware testing setup for Svelte in your Vite config file\n- demo tests","size_bytes":306,"metadata":{"title":"vitest"},"created_at":"2025-07-18T15:47:38.748Z","updated_at":"2025-07-26T14:00:05.797Z"},{"path":"apps/svelte.dev/content/docs/cli/40-api/10-add-on.md","title":"add-on","filename":"10-add-on.md","content":"> Community add-ons are currently **experimental**. The API may change. Don't use them in production yet!\n\nThis guide covers how to create, test, and publish community add-ons for `sv`.\n\n## Quick start\n\nThe easiest way to create an add-on is using the addon template:\n\n```sh\nnpx sv create --template addon my-addon\ncd my-addon\n```\n\n## Add-on structure\n\nTypically, an add-on looks like this:\n\n_hover keywords in the code to have some more context_\n\n```js\nimport { parse, svelte } from '@sveltejs/sv-utils';\nimport { defineAddon, defineAddonOptions } from 'sv';\n\n// Define options that will be prompted to the user (or passed as arguments)\nconst options = defineAddonOptions()\n\t.add('who', {\n\t\tquestion: 'To whom should the addon say hello?',\n\t\ttype: 'string' // boolean | number | select | multiselect\n\t})\n\t.build();\n\n// your add-on definition, the entry point\nexport default defineAddon({\n\tid: 'your-addon-name',\n\n\toptions,\n\n\t// preparing step, check requirements and dependencies\n\tsetup: ({ dependsOn }) => {\n\t\tdependsOn('tailwindcss');\n\t},\n\n\t// actual execution of the addon\n\trun: ({ kit, cancel, sv, options }) => {\n\t\tif (!kit) return cancel('SvelteKit is required');\n\n\t\t// Add \"Hello [who]!\" to the root page\n\t\tsv.file(kit.routesDirectory + '/+page.svelte', (content) => {\n\t\t\tconst { ast, generateCode } = parse.svelte(content);\n\n\t\t\tsvelte.addFragment(ast, `<p>Hello ${options.who}!</p>`);\n\n\t\t\treturn generateCode();\n\t\t});\n\t}\n});\n```\n\n## Development with `file:` protocol\n\nWhile developing your add-on, you can test it locally using the `file:` protocol:\n\n```sh\n# In your test project\nnpx sv add file:../path/to/my-addon\n```\n\nThis allows you to iterate quickly without publishing to npm.\n\n## Testing with `sv/testing`\n\nThe `sv/testing` module provides utilities for testing your add-on:\n\n```js\nimport { test, expect } from 'vitest';\nimport { setupTest } from 'sv/testing';\nimport addon from './index.js';\n\ntest('adds hello message', async () => {\n\tconst { content } = await setupTest({\n\t\taddon,\n\t\toptions: { who: 'World' },\n\t\tfiles: {\n\t\t\t'src/routes/+page.svelte': '<h1>Welcome</h1>'\n\t\t}\n\t});\n\n\texpect(content('src/routes/+page.svelte')).toContain('Hello World!');\n});\n```\n\n## Publishing to npm\n\n### Package structure\n\nYour add-on must have `sv` as a dependency in `package.json`:\n\n```json\n{\n\t\"name\": \"@your-org/sv\",\n\t\"version\": \"1.0.0\",\n\t\"type\": \"module\",\n\t\"exports\": {\n\t\t\".\": \"./dist/index.js\"\n\t},\n\t\"dependencies\": {\n\t\t\"sv\": \"^0.11.0\"\n\t},\n\t\"keywords\": [\"sv-add\"]\n}\n```\n\n> Add the `sv-add` keyword so users can discover your add-on on npm.\n\n### Export options\n\nYour package can export the add-on in two ways:\n\n1. **Default export** (recommended for dedicated add-on packages):\n\n   ```json\n   {\n   \t\"exports\": {\n   \t\t\".\": \"./dist/index.js\"\n   \t}\n   }\n   ```\n\n2. **`/sv` export** (for packages that have other functionality):\n   ```json\n   {\n   \t\"exports\": {\n   \t\t\".\": \"./dist/main.js\",\n   \t\t\"./sv\": \"./dist/addon.js\"\n   \t}\n   }\n   ```\n\n### Naming conventions\n\n- **Scoped packages**: Use `@your-org/sv` as the package name. Users can then install with just `npx sv add @your-org`.\n- **Regular packages**: Any name works. Users install with `npx sv add your-package-name`.\n\n## Version compatibility\n\nYour add-on should specify the minimum `sv` version it requires in `package.json`. If a user's `sv` version has a different major version than what your add-on was built for, they will see a compatibility warning.","size_bytes":3439,"metadata":{"title":"add-on"},"created_at":"2026-02-21T14:00:04.059Z","updated_at":"2026-02-21T14:00:04.059Z"},{"path":"apps/svelte.dev/content/docs/cli/40-api/20-sv-utils.md","title":"sv-utils","filename":"20-sv-utils.md","content":"> `@sveltejs/sv-utils` is currently **experimental**. The API may change. Full documentation is not yet available.\n\n`@sveltejs/sv-utils` provides utilities for parsing, transforming, and generating code in add-ons.\n\n```sh\nnpm install @sveltejs/sv-utils\n```","size_bytes":282,"metadata":{"title":"sv-utils"},"created_at":"2026-02-21T14:00:04.062Z","updated_at":"2026-02-21T14:00:04.062Z"},{"path":"apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md","title":"Introduction","filename":"10-introduction.md","content":"## Before we begin\n\n>\n> If you get stuck, reach out for help in the [Discord chatroom](/chat).\n\n## What is SvelteKit?\n\nSvelteKit is a framework for rapidly developing robust, performant web applications using [Svelte](../svelte). If you're coming from React, SvelteKit is similar to Next. If you're coming from Vue, SvelteKit is similar to Nuxt.\n\nTo learn more about the kinds of applications you can build with SvelteKit, see the [documentation regarding project types](project-types).\n\n## What is Svelte?\n\nIn short, Svelte is a way of writing user interface components — like a navigation bar, comment section, or contact form — that users see and interact with in their browsers. The Svelte compiler converts your components to JavaScript that can be run to render the HTML for the page and to CSS that styles the page. You don't need to know Svelte to understand the rest of this guide, but it will help. If you'd like to learn more, check out [the Svelte tutorial](/tutorial).\n\n## SvelteKit vs Svelte\n\nSvelte renders UI components. You can compose these components and render an entire page with just Svelte, but you need more than just Svelte to write an entire app.\n\nSvelteKit helps you build web apps while following modern best practices and providing solutions to common development challenges. It offers everything from basic functionalities — like a [router](glossary#Routing) that updates your UI when a link is clicked — to more advanced capabilities. Its extensive list of features includes [build optimizations](https://vitejs.dev/guide/features.html#build-optimizations) to load only the minimal required code; [offline support](service-workers); [preloading](link-options#data-sveltekit-preload-data) pages before user navigation; [configurable rendering](page-options) to handle different parts of your app on the server via [SSR](glossary#SSR), in the browser through [client-side rendering](glossary#CSR), or at build-time with [prerendering](glossary#Prerendering); [image optimization](images); and much more. Building an app with all the modern best practices is fiendishly complicated, but SvelteKit does all the boring stuff for you so that you can get on with the creative part.\n\nIt reflects changes to your code in the browser instantly to provide a lightning-fast and feature-rich development experience by leveraging [Vite](https://vitejs.dev/) with a [Svelte plugin](https://github.com/sveltejs/vite-plugin-svelte) to do [Hot Module Replacement (HMR)](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#hot).","size_bytes":2598,"metadata":{"title":"Introduction"},"created_at":"2025-07-18T15:47:38.754Z","updated_at":"2025-07-18T15:47:39.991Z"},{"path":"apps/svelte.dev/content/docs/kit/10-getting-started/20-creating-a-project.md","title":"Creating a project","filename":"20-creating-a-project.md","content":"The easiest way to start building a SvelteKit app is to run `npx sv create`:\n\n```sh\nnpx sv create my-app\ncd my-app\nnpm run dev\n```\n\nThe first command will scaffold a new project in the `my-app` directory asking if you'd like to set up some basic tooling such as TypeScript. See [the CLI docs](/docs/cli/overview) for information about these options and [the integrations page](./integrations) for pointers on setting up additional tooling. `npm run dev` will then start the development server on [localhost:5173](http://localhost:5173) - make sure you install dependencies before running this if you didn't do so during project creation.\n\nThere are two basic concepts:\n\n- Each page of your app is a [Svelte](../svelte) component\n- You create pages by adding files to the `src/routes` directory of your project. These will be server-rendered so that a user's first visit to your app is as fast as possible, then a client-side app takes over\n\nTry editing the files to get a feel for how everything works.\n\n## Editor setup\n\nWe recommend using [Visual Studio Code (aka VS Code)](https://code.visualstudio.com/download) with [the Svelte extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode), but [support also exists for numerous other editors](https://sveltesociety.dev/collection/editor-support-c85c080efc292a34).","size_bytes":1377,"metadata":{"title":"Creating a project"},"created_at":"2025-07-18T15:47:38.756Z","updated_at":"2025-12-07T14:00:04.407Z"},{"path":"apps/svelte.dev/content/docs/kit/10-getting-started/25-project-types.md","title":"Project types","filename":"25-project-types.md","content":"SvelteKit offers configurable rendering, which allows you to build and deploy your project in several different ways. You can build all of the below types of applications and more with SvelteKit. Rendering settings are not mutually exclusive and you may choose the optimal manner with which to render different parts of your application.\n\nIf you don't have a particular way you'd like to build your application in mind, don't worry! The way your application is built, deployed, and rendered is controlled by which adapter you've chosen and a small amount of configuration and these can always be changed later. The [project structure](project-structure) and [routing](glossary#Routing) will be the same regardless of the project type that you choose.\n\n## Default rendering\n\nBy default, when a user visits a site, SvelteKit will render the first page with [server-side rendering (SSR)](glossary#SSR) and subsequent pages with [client-side rendering (CSR)](glossary#CSR). Using SSR for the initial render improves SEO and perceived performance of the initial page load. Client-side rendering then takes over and updates the page without having to rerender common components, which is typically faster and eliminates a flash when navigating between pages. Apps built with this hybrid rendering approach have also been called [transitional apps](https://www.youtube.com/watch?v=860d8usGC0o).\n\n## Static site generation\n\nYou can use SvelteKit as a [static site generator (SSG)](glossary#SSG) that fully [prerenders](glossary#Prerendering) your site with static rendering using [`adapter-static`](adapter-static). You may also use [the prerender option](page-options#prerender) to prerender only some pages and then choose a different adapter with which to dynamically server-render other pages.\n\nTools built solely to do static site generation may scale the prerendering process more efficiently during build when rendering a very large number of pages. When working with very large statically generated sites, you can avoid long build times with [Incremental Static Regeneration (ISR) if using `adapter-vercel`](adapter-vercel#Incremental-Static-Regeneration). And in contrast to purpose-built SSGs, SvelteKit allows for nicely mixing and matching different rendering types on different pages.\n\n## Single-page app\n\n[Single-page apps (SPAs)](glossary#SPA) exclusively use [client-side rendering (CSR)](glossary#CSR). You can [build single-page apps (SPAs)](single-page-apps) with SvelteKit. As with all types of SvelteKit applications, you can write your backend in SvelteKit or [another language or framework](#Separate-backend). If you are building an application with no backend or a [separate backend](#Separate-backend), you can simply skip over and ignore the parts of the docs talking about `server` files.\n\n## Multi-page app\n\nSvelteKit isn't typically used to build [traditional multi-page apps](glossary#MPA). However, in SvelteKit you can remove all JavaScript on a page with [`csr = false`](page-options#csr), which will render subsequent links on the server, or you can use [`data-sveltekit-reload`](link-options#data-sveltekit-reload) to render specific links on the server.\n\n## Separate backend\n\nIf your backend is written in another language such as Go, Java, PHP, Ruby, Rust, or C#, there are a couple of ways that you can deploy your application. The most recommended way would be to deploy your SvelteKit frontend separately from your backend utilizing `adapter-node` or a serverless adapter. Some users prefer not to have a separate process to manage and decide to deploy their application as a [single-page app (SPA)](single-page-apps) served by their backend server, but note that single-page apps have worse SEO and performance characteristics.\n\nIf you are using an external backend, you can simply skip over and ignore the parts of the docs talking about `server` files. You may also want to reference [the FAQ about how to make calls to a separate backend](faq#How-do-I-use-a-different-backend-API-server).\n\n## Serverless app\n\nSvelteKit apps are simple to run on serverless platforms. [The default zero config adapter](adapter-auto) will automatically run your app on a number of supported platforms or you can use [`adapter-vercel`](adapter-vercel), [`adapter-netlify`](adapter-netlify), or [`adapter-cloudflare`](adapter-cloudflare) to provide platform-specific configuration. And [community adapters](/packages#sveltekit-adapters) allow you to deploy your application to almost any serverless environment. Some of these adapters such as [`adapter-vercel`](adapter-vercel) and [`adapter-netlify`](adapter-netlify) offer an `edge` option, to support [edge rendering](glossary#Edge) for improved latency.\n\n## Your own server\n\nYou can deploy to your own server or VPS using [`adapter-node`](adapter-node).\n\n## Container\n\nYou can use [`adapter-node`](adapter-node) to run a SvelteKit app within a container such as Docker or LXC.\n\n## Library\n\nYou can create a library to be used by other Svelte apps with the [`@sveltejs/package`](packaging) add-on to SvelteKit by choosing the library option when running [`sv create`](/docs/cli/sv-create).\n\n## Offline app\n\nSvelteKit has full support for [service workers](service-workers) allowing you to build many types of applications such as offline apps and [progressive web apps](glossary#PWA).\n\n## Mobile app\n\nYou can turn a [SvelteKit SPA](single-page-apps) into a mobile app with [Tauri](https://v2.tauri.app/start/frontend/sveltekit/) or [Capacitor](https://capacitorjs.com/solution/svelte). Mobile features like the camera, geolocation, and push notifications are available via plugins for both platforms.\n\nThese mobile development platforms work by starting a local web server and then serving your application like a static host on your phone. You may find [`bundleStrategy: 'single'`](configuration#output) to be a helpful option to limit the number of requests made. E.g. at the time of writing, the Capacitor local server uses HTTP/1, which limits the number of concurrent connections.\n\n## Desktop app\n\nYou can turn a [SvelteKit SPA](single-page-apps) into a desktop app with [Tauri](https://v2.tauri.app/start/frontend/sveltekit/), [Wails](https://wails.io/docs/guides/sveltekit/), or [Electron](https://www.electronjs.org/).\n\n## Browser extension\n\nYou can build browser extensions using either [`adapter-static`](adapter-static) or [community adapters](/packages#sveltekit-adapters) specifically tailored towards browser extensions.\n\n## Embedded device\n\nBecause of its efficient rendering, Svelte can be run on low power devices. Embedded devices like microcontrollers and TVs may limit the number of concurrent connections. In order to reduce the number of concurrent requests, you may find [`bundleStrategy: 'single'`](configuration#output) to be a helpful option in this deployment configuration.","size_bytes":6901,"metadata":{"title":"Project types"},"created_at":"2025-07-18T15:47:38.757Z","updated_at":"2025-10-04T02:00:04.322Z"},{"path":"apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md","title":"Project structure","filename":"30-project-structure.md","content":"A typical SvelteKit project looks like this:\n\n```tree\nmy-project/\n├ src/\n│ ├ lib/\n│ │ ├ server/\n│ │ │ └ [your server-only lib files]\n│ │ └ [your lib files]\n│ ├ params/\n│ │ └ [your param matchers]\n│ ├ routes/\n│ │ └ [your routes]\n│ ├ app.html\n│ ├ error.html\n│ ├ hooks.client.js\n│ ├ hooks.server.js\n│ ├ service-worker.js\n│ └ instrumentation.server.js\n├ static/\n│ └ [your static assets]\n├ tests/\n│ └ [your tests]\n├ package.json\n├ svelte.config.js\n├ tsconfig.json\n└ vite.config.js\n```\n\nYou'll also find common files like `.gitignore` and `.npmrc` (and `.prettierrc` and `eslint.config.js` and so on, if you chose those options when running `npx sv create`).\n\n## Project files\n\n### src\n\nThe `src` directory contains the meat of your project. Everything except `src/routes` and `src/app.html` is optional.\n\n- `lib` contains your library code (utilities and components), which can be imported via the [`$lib`]($lib) alias, or packaged up for distribution using [`svelte-package`](packaging)\n  - `server` contains your server-only library code. It can be imported by using the [`$lib/server`](server-only-modules) alias. SvelteKit will prevent you from importing these in client code.\n- `params` contains any [param matchers](advanced-routing#Matching) your app needs\n- `routes` contains the [routes](routing) of your application. You can also colocate other components that are only used within a single route here\n- `app.html` is your page template — an HTML document containing the following placeholders:\n  - `%sveltekit.head%` — `<link>` and `<script>` elements needed by the app, plus any `<svelte:head>` content\n  - `%sveltekit.body%` — the markup for a rendered page. This should live inside a `<div>` or other element, rather than directly inside `<body>`, to prevent bugs caused by browser extensions injecting elements that are then destroyed by the hydration process. SvelteKit will warn you in development if this is not the case\n  - `%sveltekit.assets%` — either [`paths.assets`](configuration#paths), if specified, or a relative path to [`paths.base`](configuration#paths)\n  - `%sveltekit.nonce%` — a [CSP](configuration#csp) nonce for manually included links and scripts, if used\n  - `%sveltekit.env.[NAME]%` - this will be replaced at render time with the `[NAME]` environment variable, which must begin with the [`publicPrefix`](configuration#env) (usually `PUBLIC_`). It will fallback to `''` if not matched.\n  - `%sveltekit.version%` — the app version, which can be specified with the [`version`](configuration#version) configuration\n- `error.html` is the page that is rendered when everything else fails. It can contain the following placeholders:\n  - `%sveltekit.status%` — the HTTP status\n  - `%sveltekit.error.message%` — the error message\n- `hooks.client.js` contains your client [hooks](hooks)\n- `hooks.server.js` contains your server [hooks](hooks)\n- `service-worker.js` contains your [service worker](service-workers)\n- `instrumentation.server.js` contains your [observability](observability) setup and instrumentation code\n  - Requires adapter support. If your adapter supports it, it is guaranteed to run prior to loading and running your application code.\n\n(Whether the project contains `.js` or `.ts` files depends on whether you opt to use TypeScript when you create your project.)\n\nIf you added [Vitest](https://vitest.dev) when you set up your project, your unit tests will live in the `src` directory with a `.test.js` extension.\n\n### static\n\nAny static assets that should be served without any alteration to the name — such as `robots.txt` — go in here. It's generally preferable to minimize the number of assets in `static/` and instead `import` them. Using an `import` allows [Vite's built-in handling](images#Vite's-built-in-handling) to give a unique name to an asset based on a hash of its contents so that it can be cached.\n\n### tests\n\nIf you added [Playwright](https://playwright.dev/) for browser testing when you set up your project, the tests will live in this directory.\n\n### package.json\n\nYour `package.json` file must include `@sveltejs/kit`, `svelte` and `vite` as `devDependencies`.\n\nWhen you create a project with `npx sv create`, you'll also notice that `package.json` includes `\"type\": \"module\"`. This means that `.js` files are interpreted as native JavaScript modules with `import` and `export` keywords. Legacy CommonJS files need a `.cjs` file extension.\n\n### svelte.config.js\n\nThis file contains your Svelte and SvelteKit [configuration](configuration).\n\n### tsconfig.json\n\nThis file (or `jsconfig.json`, if you prefer type-checked `.js` files over `.ts` files) configures TypeScript, if you added typechecking during `npx sv create`. Since SvelteKit relies on certain configuration being set a specific way, it generates its own `.svelte-kit/tsconfig.json` file which your own config `extends`. To make changes to top-level options such as `include` and `exclude`, we recommend extending the generated config; see the [`typescript.config` setting](configuration#typescript) for more details.\n\n### vite.config.js\n\nA SvelteKit project is really just a [Vite](https://vitejs.dev) project that uses the [`@sveltejs/kit/vite`](@sveltejs-kit-vite) plugin, along with any other [Vite configuration](https://vitejs.dev/config/).\n\n## Other files\n\n### .svelte-kit\n\nAs you develop and build your project, SvelteKit will generate files in a `.svelte-kit` directory (configurable as [`outDir`](configuration#outDir)). You can ignore its contents, and delete them at any time (they will be regenerated when you next `dev` or `build`).","size_bytes":5717,"metadata":{"title":"Project structure"},"created_at":"2025-07-18T15:47:38.759Z","updated_at":"2026-02-26T02:00:03.889Z"},{"path":"apps/svelte.dev/content/docs/kit/10-getting-started/40-web-standards.md","title":"Web standards","filename":"40-web-standards.md","content":"Throughout this documentation, you'll see references to the standard [Web APIs](https://developer.mozilla.org/en-US/docs/Web/API) that SvelteKit builds on top of. Rather than reinventing the wheel, we _use the platform_, which means your existing web development skills are applicable to SvelteKit. Conversely, time spent learning SvelteKit will help you be a better web developer elsewhere.\n\nThese APIs are available in all modern browsers and in many non-browser environments like Cloudflare Workers, Deno, and Vercel Functions. During development, and in [adapters](adapters) for Node-based environments (including AWS Lambda), they're made available via polyfills where necessary (for now, that is — Node is rapidly adding support for more web standards).\n\nIn particular, you'll get comfortable with the following:\n\n## Fetch APIs\n\nSvelteKit uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for getting data from the network. It's available in [hooks](hooks) and [server routes](routing#server) as well as in the browser.\n\n\nBesides `fetch` itself, the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) includes the following interfaces:\n\n### Request\n\nAn instance of [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) is accessible in [hooks](hooks) and [server routes](routing#server) as `event.request`. It contains useful methods like `request.json()` and `request.formData()` for getting data that was posted to an endpoint.\n\n### Response\n\nAn instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) is returned from `await fetch(...)` and handlers in `+server.js` files. Fundamentally, a SvelteKit app is a machine for turning a `Request` into a `Response`.\n\n### Headers\n\nThe [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) interface allows you to read incoming `request.headers` and set outgoing `response.headers`. For example, you can get the `request.headers` as shown below, and use the [`json` convenience function](@sveltejs-kit#json) to send modified `response.headers`:\n\n```js\n// @errors: 2461\n/// file: src/routes/what-is-my-user-agent/+server.js\nimport { json } from '@sveltejs/kit';\n\n/** @type {import('./$types').RequestHandler} */\nexport function GET({ request }) {\n\t// log all headers\n\tconsole.log(...request.headers);\n\n\t// create a JSON Response using a header we received\n\treturn json({\n\t\t// retrieve a specific header\n\t\tuserAgent: request.headers.get('user-agent')\n\t}, {\n\t\t// set a header on the response\n\t\theaders: { 'x-custom-header': 'potato' }\n\t});\n}\n```\n\n## FormData\n\nWhen dealing with HTML native form submissions you'll be working with [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) objects.\n\n```js\n// @errors: 2461\n/// file: src/routes/hello/+server.js\nimport { json } from '@sveltejs/kit';\n\n/** @type {import('./$types').RequestHandler} */\nexport async function POST(event) {\n\tconst body = await event.request.formData();\n\n\t// log all fields\n\tconsole.log([...body]);\n\n\treturn json({\n\t\t// get a specific field's value\n\t\tname: body.get('name') ?? 'world'\n\t});\n}\n```\n\n## Stream APIs\n\nMost of the time, your endpoints will return complete data, as in the `userAgent` example above. Sometimes, you may need to return a response that's too large to fit in memory in one go, or is delivered in chunks, and for this the platform provides [streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) — [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), [WritableStream](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) and [TransformStream](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream).\n\n## URL APIs\n\nURLs are represented by the [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) interface, which includes useful properties like `origin` and `pathname` (and, in the browser, `hash`). This interface shows up in various places — `event.url` in [hooks](hooks) and [server routes](routing#server), [`page.url`]($app-state) in [pages](routing#page), `from` and `to` in [`beforeNavigate` and `afterNavigate`]($app-navigation) and so on.\n\n### URLSearchParams\n\nWherever you encounter a URL, you can access query parameters via `url.searchParams`, which is an instance of [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams):\n\n```js\n// @filename: ambient.d.ts\ndeclare global {\n\tconst url: URL;\n}\n\nexport {};\n\n// @filename: index.js\n//cut\nconst foo = url.searchParams.get('foo');\n```\n\n## Web Crypto\n\nThe [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) is made available via the `crypto` global. It's used internally for [Content Security Policy](configuration#csp) headers, but you can also use it for things like generating UUIDs:\n\n```js\nconst uuid = crypto.randomUUID();\n```","size_bytes":4924,"metadata":{"title":"Web standards"},"created_at":"2025-07-18T15:47:38.761Z","updated_at":"2025-07-18T15:47:40.005Z"},{"path":"apps/svelte.dev/content/docs/kit/20-core-concepts/10-routing.md","title":"Routing","filename":"10-routing.md","content":"At the heart of SvelteKit is a _filesystem-based router_. The routes of your app — i.e. the URL paths that users can access — are defined by the directories in your codebase:\n\n- `src/routes` is the root route\n- `src/routes/about` creates an `/about` route\n- `src/routes/blog/[slug]` creates a route with a _parameter_, `slug`, that can be used to load data dynamically when a user requests a page like `/blog/hello-world`\n\n\nEach route directory contains one or more _route files_, which can be identified by their `+` prefix.\n\nWe'll introduce these files in a moment in more detail, but here are a few simple rules to help you remember how SvelteKit's routing works:\n\n* All files can run on the server\n* All files run on the client except `+server` files\n* `+layout` and `+error` files apply to subdirectories as well as the directory they live in\n\n## +page\n\n### +page.svelte\n\nA `+page.svelte` component defines a page of your app. By default, pages are rendered both on the server ([SSR](glossary#SSR)) for the initial request and in the browser ([CSR](glossary#CSR)) for subsequent navigation.\n\n```svelte\n<!file: src/routes/+page.svelte>\n<h1>Hello and welcome to my site!</h1>\n<a href=\"/about\">About my site</a>\n```\n\n```svelte\n<!file: src/routes/about/+page.svelte>\n<h1>About this site</h1>\n<p>TODO...</p>\n<a href=\"/\">Home</a>\n```\n\n\nPages can receive data from `load` functions via the `data` prop.\n\n```svelte\n<!file: src/routes/blog/[slug]/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n</script>\n\n<h1>{data.title}</h1>\n<div>{@html data.content}</div>\n```\n\nAs of 2.24, pages also receive a `params` prop which is typed based on the route parameters. This is particularly useful alongside [remote functions](remote-functions):\n\n```svelte\n<!file: src/routes/blog/[slug]/+page.svelte>\n<script>\n\timport { getPost } from '../blog.remote';\n\n\t/** @type {import('./$types').PageProps} */\n\tlet { params } = $props();\n\n\tconst post = $derived(await getPost(params.slug));\n</script>\n\n<h1>{post.title}</h1>\n<div>{@html post.content}</div>\n```\n\n> [!LEGACY]\n> `PageProps` was added in 2.16.0. In earlier versions, you had to type the `data` property manually with `PageData` instead, see [$types](#\\$types).\n>\n> In Svelte 4, you'd use `export let data` instead.\n\n### +page.js\n\nOften, a page will need to load some data before it can be rendered. For this, we add a `+page.js` module that exports a `load` function:\n\n```js\n/// file: src/routes/blog/[slug]/+page.js\nimport { error } from '@sveltejs/kit';\n\n/** @type {import('./$types').PageLoad} */\nexport function load({ params }) {\n\tif (params.slug === 'hello-world') {\n\t\treturn {\n\t\t\ttitle: 'Hello world!',\n\t\t\tcontent: 'Welcome to our blog. Lorem ipsum dolor sit amet...'\n\t\t};\n\t}\n\n\terror(404, 'Not found');\n}\n```\n\nThis function runs alongside `+page.svelte`, which means it runs on the server during server-side rendering and in the browser during client-side navigation. See [`load`](load) for full details of the API.\n\nAs well as `load`, `+page.js` can export values that configure the page's behaviour:\n\n- `export const prerender = true` or `false` or `'auto'`\n- `export const ssr = true` or `false`\n- `export const csr = true` or `false`\n\nYou can find more information about these in [page options](page-options).\n\n### +page.server.js\n\nIf your `load` function can only run on the server — for example, if it needs to fetch data from a database or you need to access private [environment variables]($env-static-private) like API keys — then you can rename `+page.js` to `+page.server.js` and change the `PageLoad` type to `PageServerLoad`.\n\n```js\n/// file: src/routes/blog/[slug]/+page.server.js\n\n// @filename: ambient.d.ts\ndeclare global {\n\tconst getPostFromDatabase: (slug: string) => {\n\t\ttitle: string;\n\t\tcontent: string;\n\t}\n}\n\nexport {};\n\n// @filename: index.js\n//cut\nimport { error } from '@sveltejs/kit';\n\n/** @type {import('./$types').PageServerLoad} */\nexport async function load({ params }) {\n\tconst post = await getPostFromDatabase(params.slug);\n\n\tif (post) {\n\t\treturn post;\n\t}\n\n\terror(404, 'Not found');\n}\n```\n\nDuring client-side navigation, SvelteKit will load this data from the server, which means that the returned value must be serializable using [devalue](https://github.com/rich-harris/devalue). See [`load`](load) for full details of the API.\n\nLike `+page.js`, `+page.server.js` can export [page options](page-options) — `prerender`, `ssr` and `csr`.\n\nA `+page.server.js` file can also export _actions_. If `load` lets you read data from the server, `actions` let you write data _to_ the server using the `<form>` element. To learn how to use them, see the [form actions](form-actions) section.\n\n## +error\n\nIf an error occurs during `load`, SvelteKit will render a default error page. You can customise this error page on a per-route basis by adding an `+error.svelte` file:\n\n```svelte\n<!file: src/routes/blog/[slug]/+error.svelte>\n<script>\n\timport { page } from '$app/state';\n</script>\n\n<h1>{page.status}: {page.error.message}</h1>\n```\n\n> [!LEGACY]\n> `$app/state` was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use `$app/stores` instead.\n\nSvelteKit will 'walk up the tree' looking for the closest error boundary — if the file above didn't exist it would try `src/routes/blog/+error.svelte` and then `src/routes/+error.svelte` before rendering the default error page. If _that_ fails (or if the error was thrown from the `load` function of the root `+layout`, which sits 'above' the root `+error`), SvelteKit will bail out and render a static fallback error page, which you can customise by creating a `src/error.html` file.\n\nIf the error occurs inside a `load` function in `+layout(.server).js`, the closest error boundary in the tree is an `+error.svelte` file _above_ that layout (not next to it).\n\nIf no route can be found (404), `src/routes/+error.svelte` (or the default error page, if that file does not exist) will be used.\n\n\nYou can read more about error handling [here](errors).\n\n## +layout\n\nSo far, we've treated pages as entirely standalone components — upon navigation, the existing `+page.svelte` component will be destroyed, and a new one will take its place.\n\nBut in many apps, there are elements that should be visible on _every_ page, such as top-level navigation or a footer. Instead of repeating them in every `+page.svelte`, we can put them in _layouts_.\n\n### +layout.svelte\n\nTo create a layout that applies to every page, make a file called `src/routes/+layout.svelte`. The default layout (the one that SvelteKit uses if you don't bring your own) looks like this...\n\n```svelte\n<script>\n\tlet { children } = $props();\n</script>\n\n{@render children()}\n```\n\n...but we can add whatever markup, styles and behaviour we want. The only requirement is that the component includes a `@render` tag for the page content. For example, let's add a nav bar:\n\n```svelte\n<!file: src/routes/+layout.svelte>\n<script>\n\tlet { children } = $props();\n</script>\n\n<nav>\n\t<a href=\"/\">Home</a>\n\t<a href=\"/about\">About</a>\n\t<a href=\"/settings\">Settings</a>\n</nav>\n\n{@render children()}\n```\n\nIf we create pages for `/`, `/about` and `/settings`...\n\n```html\n/// file: src/routes/+page.svelte\n<h1>Home</h1>\n```\n\n```html\n/// file: src/routes/about/+page.svelte\n<h1>About</h1>\n```\n\n```html\n/// file: src/routes/settings/+page.svelte\n<h1>Settings</h1>\n```\n\n...the nav will always be visible, and clicking between the three pages will only result in the `<h1>` being replaced.\n\nLayouts can be _nested_. Suppose we don't just have a single `/settings` page, but instead have nested pages like `/settings/profile` and `/settings/notifications` with a shared submenu (for a real-life example, see [github.com/settings](https://github.com/settings)).\n\nWe can create a layout that only applies to pages below `/settings` (while inheriting the root layout with the top-level nav):\n\n```svelte\n<!file: src/routes/settings/+layout.svelte>\n<script>\n\t/** @type {import('./$types').LayoutProps} */\n\tlet { data, children } = $props();\n</script>\n\n<h1>Settings</h1>\n\n<div class=\"submenu\">\n\t{#each data.sections as section}\n\t\t<a href=\"/settings/{section.slug}\">{section.title}</a>\n\t{/each}\n</div>\n\n{@render children()}\n```\n\n> [!LEGACY]\n> `LayoutProps` was added in 2.16.0. In earlier versions, you had to [type the properties manually instead](#\\$types).\n\nYou can see how `data` is populated by looking at the `+layout.js` example in the next section just below.\n\nBy default, each layout inherits the layout above it. Sometimes that isn't what you want - in this case, [advanced layouts](advanced-routing#Advanced-layouts) can help you.\n\n### +layout.js\n\nJust like `+page.svelte` loading data from `+page.js`, your `+layout.svelte` component can get data from a [`load`](load) function in `+layout.js`.\n\n```js\n/// file: src/routes/settings/+layout.js\n/** @type {import('./$types').LayoutLoad} */\nexport function load() {\n\treturn {\n\t\tsections: [\n\t\t\t{ slug: 'profile', title: 'Profile' },\n\t\t\t{ slug: 'notifications', title: 'Notifications' }\n\t\t]\n\t};\n}\n```\n\nIf a `+layout.js` exports [page options](page-options) — `prerender`, `ssr` and `csr` — they will be used as defaults for child pages.\n\nData returned from a layout's `load` function is also available to all its child pages:\n\n```svelte\n<!file: src/routes/settings/profile/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n\n\tconsole.log(data.sections); // [{ slug: 'profile', title: 'Profile' }, ...]\n</script>\n```\n\n\n### +layout.server.js\n\nTo run your layout's `load` function on the server, move it to `+layout.server.js`, and change the `LayoutLoad` type to `LayoutServerLoad`.\n\nLike `+layout.js`, `+layout.server.js` can export [page options](page-options) — `prerender`, `ssr` and `csr`.\n\n## +server\n\nAs well as pages, you can define routes with a `+server.js` file (sometimes referred to as an 'API route' or an 'endpoint'), which gives you full control over the response. Your `+server.js` file exports functions corresponding to HTTP verbs like `GET`, `POST`, `PATCH`, `PUT`, `DELETE`, `OPTIONS`, and `HEAD` that take a [`RequestEvent`](@sveltejs-kit#RequestEvent) argument and return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object.\n\nFor example we could create an `/api/random-number` route with a `GET` handler:\n\n```js\n/// file: src/routes/api/random-number/+server.js\nimport { error } from '@sveltejs/kit';\n\n/** @type {import('./$types').RequestHandler} */\nexport function GET({ url }) {\n\tconst min = Number(url.searchParams.get('min') ?? '0');\n\tconst max = Number(url.searchParams.get('max') ?? '1');\n\n\tconst d = max - min;\n\n\tif (isNaN(d) || d < 0) {\n\t\terror(400, 'min and max must be numbers, and min must be less than max');\n\t}\n\n\tconst random = min + Math.random() * d;\n\n\treturn new Response(String(random));\n}\n```\n\nThe first argument to `Response` can be a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), making it possible to stream large amounts of data or create server-sent events (unless deploying to platforms that buffer responses, like AWS Lambda).\n\nYou can use the [`error`](@sveltejs-kit#error), [`redirect`](@sveltejs-kit#redirect) and [`json`](@sveltejs-kit#json) methods from `@sveltejs/kit` for convenience (but you don't have to).\n\nIf an error is thrown (either `error(...)` or an unexpected error), the response will be a JSON representation of the error or a fallback error page — which can be customised via `src/error.html` — depending on the `Accept` header. The [`+error.svelte`](#error) component will _not_ be rendered in this case. You can read more about error handling [here](errors).\n\n\n\n### Receiving data\n\nBy exporting `POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`HEAD` handlers, `+server.js` files can be used to create a complete API:\n\n```svelte\n<!file: src/routes/add/+page.svelte>\n<script>\n\tlet a = $state(0);\n\tlet b = $state(0);\n\tlet total = $state(0);\n\n\tasync function add() {\n\t\tconst response = await fetch('/api/add', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: JSON.stringify({ a, b }),\n\t\t\theaders: {\n\t\t\t\t'content-type': 'application/json'\n\t\t\t}\n\t\t});\n\n\t\ttotal = await response.json();\n\t}\n</script>\n\n<input type=\"number\" bind:value={a}> +\n<input type=\"number\" bind:value={b}> =\n{total}\n\n<button onclick={add}>Calculate</button>\n```\n\n```js\n/// file: src/routes/api/add/+server.js\nimport { json } from '@sveltejs/kit';\n\n/** @type {import('./$types').RequestHandler} */\nexport async function POST({ request }) {\n\tconst { a, b } = await request.json();\n\treturn json(a + b);\n}\n```\n\n\n\n### Fallback method handler\n\nExporting the `fallback` handler will match any unhandled request methods, including methods like `MOVE` which have no dedicated export from `+server.js`.\n\n```js\n/// file: src/routes/api/add/+server.js\nimport { json, text } from '@sveltejs/kit';\n\n/** @type {import('./$types').RequestHandler} */\nexport async function POST({ request }) {\n\tconst { a, b } = await request.json();\n\treturn json(a + b);\n}\n\n// This handler will respond to PUT, PATCH, DELETE, etc.\n/** @type {import('./$types').RequestHandler} */\nexport async function fallback({ request }) {\n\treturn text(`I caught your ${request.method} request!`);\n}\n```\n\n\n### Content negotiation\n\n`+server.js` files can be placed in the same directory as `+page` files, allowing the same route to be either a page or an API endpoint. To determine which, SvelteKit applies the following rules:\n\n- `PUT`/`PATCH`/`DELETE`/`OPTIONS` requests are always handled by `+server.js` since they do not apply to pages\n- `GET`/`POST`/`HEAD` requests are treated as page requests if the `accept` header prioritises `text/html` (in other words, it's a browser page request), else they are handled by `+server.js`.\n- Responses to `GET` requests will include a `Vary: Accept` header, so that proxies and browsers cache HTML and JSON responses separately.\n\n## $types\n\nThroughout the examples above, we've been importing types from a `$types.d.ts` file. This is a file SvelteKit creates for you in a hidden directory if you're using TypeScript (or JavaScript with JSDoc type annotations) to give you type safety when working with your root files.\n\nFor example, annotating `let { data } = $props()` with `PageProps` (or `LayoutProps`, for a `+layout.svelte` file) tells TypeScript that the type of `data` is whatever was returned from `load`:\n\n```svelte\n<!file: src/routes/blog/[slug]/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n</script>\n```\n\n> The `PageProps` and `LayoutProps` types, added in 2.16.0, are a shortcut for typing the `data` prop as `PageData` or `LayoutData`, as well as other props, such as `form` for pages, or `children` for layouts. In earlier versions, you had to type these properties manually. For example, for a page:\n>\n> ```js\n> /// file: +page.svelte\n> /** @type {{ data: import('./$types').PageData, form: import('./$types').ActionData }} */\n> let { data, form } = $props();\n> ```\n>\n> Or, for a layout:\n>\n> ```js\n> /// file: +layout.svelte\n> /** @type {{ data: import('./$types').LayoutData, children: Snippet }} */\n> let { data, children } = $props();\n> ```\n\nIn turn, annotating the `load` function with `PageLoad`, `PageServerLoad`, `LayoutLoad` or `LayoutServerLoad` (for `+page.js`, `+page.server.js`, `+layout.js` and `+layout.server.js` respectively) ensures that `params` and the return value are correctly typed.\n\nIf you're using VS Code or any IDE that supports the language server protocol and TypeScript plugins then you can omit these types _entirely_! Svelte's IDE tooling will insert the correct types for you, so you'll get type checking without writing them yourself. It also works with our command line tool `svelte-check`.\n\nYou can read more about omitting `$types` in our [blog post](/blog/zero-config-type-safety) about it.\n\n## Other files\n\nAny other files inside a route directory are ignored by SvelteKit. This means you can colocate components and utility modules with the routes that need them.\n\nIf components and modules are needed by multiple routes, it's a good idea to put them in [`$lib`]($lib).\n\n## Further reading\n\n- [Tutorial: Routing](/tutorial/kit/pages)\n- [Tutorial: API routes](/tutorial/kit/get-handlers)\n- [Docs: Advanced routing](advanced-routing)","size_bytes":16365,"metadata":{"title":"Routing"},"created_at":"2025-07-18T15:47:38.766Z","updated_at":"2026-02-14T01:33:24.839Z"},{"path":"apps/svelte.dev/content/docs/kit/20-core-concepts/20-load.md","title":"Loading data","filename":"20-load.md","content":"Before a [`+page.svelte`](routing#page-page.svelte) component (and its containing [`+layout.svelte`](routing#layout-layout.svelte) components) can be rendered, we often need to get some data. This is done by defining `load` functions.\n\n## Page data\n\nA `+page.svelte` file can have a sibling `+page.js` that exports a `load` function, the return value of which is available to the page via the `data` prop:\n\n```js\n/// file: src/routes/blog/[slug]/+page.js\n/** @type {import('./$types').PageLoad} */\nexport function load({ params }) {\n\treturn {\n\t\tpost: {\n\t\t\ttitle: `Title for ${params.slug} goes here`,\n\t\t\tcontent: `Content for ${params.slug} goes here`\n\t\t}\n\t};\n}\n```\n\n```svelte\n<!file: src/routes/blog/[slug]/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n</script>\n\n<h1>{data.post.title}</h1>\n<div>{@html data.post.content}</div>\n```\n\n> [!LEGACY]\n> Before version 2.16.0, the props of a page and layout had to be typed individually:\n> ```js\n> /// file: +page.svelte\n> /** @type {{ data: import('./$types').PageData }} */\n> let { data } = $props();\n> ```\n>\n> In Svelte 4, you'd use `export let data` instead.\n\nThanks to the generated `$types` module, we get full type safety.\n\nA `load` function in a `+page.js` file runs both on the server and in the browser (unless combined with `export const ssr = false`, in which case it will [only run in the browser](page-options#ssr)). If your `load` function should _always_ run on the server (because it uses private environment variables, for example, or accesses a database) then it would go in a `+page.server.js` instead.\n\nA more realistic version of your blog post's `load` function, that only runs on the server and pulls data from a database, might look like this:\n\n```js\n/// file: src/routes/blog/[slug]/+page.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function getPost(slug: string): Promise<{ title: string, content: string }>\n}\n\n// @filename: index.js\n//cut\nimport * as db from '$lib/server/database';\n\n/** @type {import('./$types').PageServerLoad} */\nexport async function load({ params }) {\n\treturn {\n\t\tpost: await db.getPost(params.slug)\n\t};\n}\n```\n\nNotice that the type changed from `PageLoad` to `PageServerLoad`, because server `load` functions can access additional arguments. To understand when to use `+page.js` and when to use `+page.server.js`, see [Universal vs server](load#Universal-vs-server).\n\n## Layout data\n\nYour `+layout.svelte` files can also load data, via `+layout.js` or `+layout.server.js`.\n\n```js\n/// file: src/routes/blog/[slug]/+layout.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function getPostSummaries(): Promise<Array<{ title: string, slug: string }>>\n}\n\n// @filename: index.js\n//cut\nimport * as db from '$lib/server/database';\n\n/** @type {import('./$types').LayoutServerLoad} */\nexport async function load() {\n\treturn {\n\t\tposts: await db.getPostSummaries()\n\t};\n}\n```\n\n```svelte\n<!file: src/routes/blog/[slug]/+layout.svelte>\n<script>\n\t/** @type {import('./$types').LayoutProps} */\n\tlet { data, children } = $props();\n</script>\n\n<main>\n\t<!-- +page.svelte is `@render`ed here -->\n\t{@render children()}\n</main>\n\n<aside>\n\t<h2>More posts</h2>\n\t<ul>\n\t\t{#each data.posts as post}\n\t\t\t<li>\n\t\t\t\t<a href=\"/blog/{post.slug}\">\n\t\t\t\t\t{post.title}\n\t\t\t\t</a>\n\t\t\t</li>\n\t\t{/each}\n\t</ul>\n</aside>\n```\n\n> [!LEGACY]\n> `LayoutProps` was added in 2.16.0. In earlier versions, properties had to be typed individually:\n> ```js\n> /// file: +layout.svelte\n> /** @type {{ data: import('./$types').LayoutData, children: Snippet }} */\n> let { data, children } = $props();\n> ```\n\nData returned from layout `load` functions is available to child `+layout.svelte` components and the `+page.svelte` component as well as the layout that it 'belongs' to.\n\n```svelte\n/// file: src/routes/blog/[slug]/+page.svelte\n<script>\n\timport { page } from '$app/state';\n\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n\n// we can access `data.posts` because it's returned from\n\t// the parent layout `load` function\n\tlet index = $derived(data.posts.findIndex(post => post.slug === page.params.slug));\n\tlet next = $derived(data.posts[index + 1]);\n</script>\n\n<h1>{data.post.title}</h1>\n<div>{@html data.post.content}</div>\n\n{#if next}\n\t<p>Next post: <a href=\"/blog/{next.slug}\">{next.title}</a></p>\n{/if}\n```\n\n\n## page.data\n\nThe `+page.svelte` component, and each `+layout.svelte` component above it, has access to its own data plus all the data from its parents.\n\nIn some cases, we might need the opposite — a parent layout might need to access page data or data from a child layout. For example, the root layout might want to access a `title` property returned from a `load` function in `+page.js` or `+page.server.js`. This can be done with `page.data`:\n\n```svelte\n<!file: src/routes/+layout.svelte>\n<script>\n\timport { page } from '$app/state';\n</script>\n\n<svelte:head>\n\t<title>{page.data.title}</title>\n</svelte:head>\n```\n\nType information for `page.data` is provided by `App.PageData`.\n\n> [!LEGACY]\n> `$app/state` was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use `$app/stores` instead.\n> It provides a `page` store with the same interface that you can subscribe to, e.g. `$page.data.title`.\n\n## Universal vs server\n\nAs we've seen, there are two types of `load` function:\n\n* `+page.js` and `+layout.js` files export _universal_ `load` functions that run both on the server and in the browser\n* `+page.server.js` and `+layout.server.js` files export _server_ `load` functions that only run server-side\n\nConceptually, they're the same thing, but there are some important differences to be aware of.\n\n### When does which load function run?\n\nServer `load` functions _always_ run on the server.\n\nBy default, universal `load` functions run on the server during SSR when the user first visits your page. They will then run again during hydration, reusing any responses from [fetch requests](#Making-fetch-requests). All subsequent invocations of universal `load` functions happen in the browser. You can customize the behavior through [page options](page-options). If you disable [server-side rendering](page-options#ssr), you'll get an SPA and universal `load` functions _always_ run on the client.\n\nIf a route contains both universal and server `load` functions, the server `load` runs first.\n\nA `load` function is invoked at runtime, unless you [prerender](page-options#prerender) the page — in that case, it's invoked at build time.\n\n### Input\n\nBoth universal and server `load` functions have access to properties describing the request (`params`, `route` and `url`) and various functions (`fetch`, `setHeaders`, `parent`, `depends` and `untrack`). These are described in the following sections.\n\nServer `load` functions are called with a `ServerLoadEvent`, which inherits `clientAddress`, `cookies`, `locals`, `platform` and `request` from `RequestEvent`.\n\nUniversal `load` functions are called with a `LoadEvent`, which has a `data` property. If you have `load` functions in both `+page.js` and `+page.server.js` (or `+layout.js` and `+layout.server.js`), the return value of the server `load` function is the `data` property of the universal `load` function's argument.\n\n### Output\n\nA universal `load` function can return an object containing any values, including things like custom classes and component constructors.\n\nA server `load` function must return data that can be serialized with [devalue](https://github.com/rich-harris/devalue) — anything that can be represented as JSON plus things like `BigInt`, `Date`, `Map`, `Set` and `RegExp`, or repeated/cyclical references — so that it can be transported over the network. Your data can include [promises](#Streaming-with-promises), in which case it will be streamed to browsers. If you need to serialize/deserialize custom types, use [transport hooks](hooks#Universal-hooks-transport).\n\n### When to use which\n\nServer `load` functions are convenient when you need to access data directly from a database or filesystem, or need to use private environment variables.\n\nUniversal `load` functions are useful when you need to `fetch` data from an external API and don't need private credentials, since SvelteKit can get the data directly from the API rather than going via your server. They are also useful when you need to return something that can't be serialized, such as a Svelte component constructor.\n\nIn rare cases, you might need to use both together — for example, you might need to return an instance of a custom class that was initialised with data from your server. When using both, the server `load` return value is _not_ passed directly to the page, but to the universal `load` function (as the `data` property):\n\n```js\n/// file: src/routes/+page.server.js\n/** @type {import('./$types').PageServerLoad} */\nexport async function load() {\n\treturn {\n\t\tserverMessage: 'hello from server load function'\n\t};\n}\n```\n\n```js\n/// file: src/routes/+page.js\n// @errors: 18047\n/** @type {import('./$types').PageLoad} */\nexport async function load({ data }) {\n\treturn {\n\t\tserverMessage: data.serverMessage,\n\t\tuniversalMessage: 'hello from universal load function'\n\t};\n}\n```\n\n## Using URL data\n\nOften the `load` function depends on the URL in one way or another. For this, the `load` function provides you with `url`, `route` and `params`.\n\n### url\n\nAn instance of [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL), containing properties like the `origin`, `hostname`, `pathname` and `searchParams` (which contains the parsed query string as a [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object). `url.hash` cannot be accessed during `load`, since it is unavailable on the server.\n\n\n### route\n\nContains the name of the current route directory, relative to `src/routes`:\n\n```js\n/// file: src/routes/a/[b]/[...c]/+page.js\n/** @type {import('./$types').PageLoad} */\nexport function load({ route }) {\n\tconsole.log(route.id); // '/a/[b]/[...c]'\n}\n```\n\n### params\n\n`params` is derived from `url.pathname` and `route.id`.\n\nGiven a `route.id` of `/a/[b]/[...c]` and a `url.pathname` of `/a/x/y/z`, the `params` object would look like this:\n\n```json\n{\n\t\"b\": \"x\",\n\t\"c\": \"y/z\"\n}\n```\n\n## Making fetch requests\n\nTo get data from an external API or a `+server.js` handler, you can use the provided `fetch` function, which behaves identically to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch) with a few additional features:\n\n- It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request.\n- It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context).\n- Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.\n- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text`, `json` and `arrayBuffer` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](hooks#Server-hooks-handle).\n- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request - if you received a warning in your browser console when using the browser `fetch` instead of the `load` `fetch`, this is why.\n\n```js\n/// file: src/routes/items/[id]/+page.js\n/** @type {import('./$types').PageLoad} */\nexport async function load({ fetch, params }) {\n\tconst res = await fetch(`/api/items/${params.id}`);\n\tconst item = await res.json();\n\n\treturn { item };\n}\n```\n\n## Cookies\n\nA server `load` function can get and set [`cookies`](@sveltejs-kit#Cookies).\n\n```js\n/// file: src/routes/+layout.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function getUser(sessionid: string | undefined): Promise<{ name: string, avatar: string }>\n}\n\n// @filename: index.js\n//cut\nimport * as db from '$lib/server/database';\n\n/** @type {import('./$types').LayoutServerLoad} */\nexport async function load({ cookies }) {\n\tconst sessionid = cookies.get('sessionid');\n\n\treturn {\n\t\tuser: await db.getUser(sessionid)\n\t};\n}\n```\n\nCookies 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.\n\nFor example, if SvelteKit is serving my.domain.com:\n- domain.com WILL NOT receive cookies\n- my.domain.com WILL receive cookies\n- api.domain.com WILL NOT receive cookies\n- sub.my.domain.com WILL receive cookies\n\nOther cookies will not be passed when `credentials: 'include'` is set, because SvelteKit does not know which domain which cookie belongs to (the browser does not pass this information along), so it's not safe to forward any of them. Use the [handleFetch hook](hooks#Server-hooks-handleFetch) to work around it.\n\n## Headers\n\nBoth server and universal `load` functions have access to a `setHeaders` function that, when running on the server, can set headers for the response. (When running in the browser, `setHeaders` has no effect.) This is useful if you want the page to be cached, for example:\n\n```js\n// @errors: 2322 1360\n/// file: src/routes/products/+page.js\n/** @type {import('./$types').PageLoad} */\nexport async function load({ fetch, setHeaders }) {\n\tconst url = `https://cms.example.com/products.json`;\n\tconst response = await fetch(url);\n\n\t// Headers are only set during SSR, caching the page's HTML\n\t// for the same length of time as the underlying data.\n\tsetHeaders({\n\t\tage: response.headers.get('age'),\n\t\t'cache-control': response.headers.get('cache-control')\n\t});\n\n\treturn response.json();\n}\n```\n\nSetting the same header multiple times (even in separate `load` functions) is an error. You can only set a given header once using the `setHeaders` function. You cannot add a `set-cookie` header with `setHeaders` — use `cookies.set(name, value, options)` instead.\n\n## Using parent data\n\nOccasionally it's useful for a `load` function to access data from a parent `load` function, which can be done with `await parent()`:\n\n```js\n/// file: src/routes/+layout.js\n/** @type {import('./$types').LayoutLoad} */\nexport function load() {\n\treturn { a: 1 };\n}\n```\n\n```js\n/// file: src/routes/abc/+layout.js\n/** @type {import('./$types').LayoutLoad} */\nexport async function load({ parent }) {\n\tconst { a } = await parent();\n\treturn { b: a + 1 };\n}\n```\n\n```js\n/// file: src/routes/abc/+page.js\n/** @type {import('./$types').PageLoad} */\nexport async function load({ parent }) {\n\tconst { a, b } = await parent();\n\treturn { c: a + b };\n}\n```\n\n```svelte\n<!file: src/routes/abc/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n</script>\n\n<!-- renders `1 + 2 = 3` -->\n<p>{data.a} + {data.b} = {data.c}</p>\n```\n\n\nInside `+page.server.js` and `+layout.server.js`, `parent` returns data from parent `+layout.server.js` files.\n\nIn `+page.js` or `+layout.js` it will return data from parent `+layout.js` files. However, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will also return data from parent `+layout.server.js` files that are not 'shadowed' by a `+layout.js` file\n\nTake care not to introduce waterfalls when using `await parent()`. Here, for example, `getData(params)` does not depend on the result of calling `parent()`, so we should call it first to avoid a delayed render.\n\n```js\n/// file: +page.js\n// @filename: ambient.d.ts\ndeclare function getData(params: Record<string, string>): Promise<{ meta: any }>\n\n// @filename: index.js\n//cut\n/** @type {import('./$types').PageLoad} */\nexport async function load({ params, parent }) {\n\tconst parentData = await parent();\n\tconst data = await getData(params);\n\tconst parentData = await parent();\n\n\treturn {\n\t\t...data,\n\t\tmeta: { ...parentData.meta, ...data.meta }\n\t};\n}\n```\n\n## Errors\n\nIf an error is thrown during `load`, the nearest [`+error.svelte`](routing#error) will be rendered. For [_expected_](errors#Expected-errors) errors, use the `error` helper from `@sveltejs/kit` to specify the HTTP status code and an optional message:\n\n```js\n/// file: src/routes/admin/+layout.server.js\n// @filename: ambient.d.ts\ndeclare namespace App {\n\tinterface Locals {\n\t\tuser?: {\n\t\t\tname: string;\n\t\t\tisAdmin: boolean;\n\t\t}\n\t}\n}\n\n// @filename: index.js\n//cut\nimport { error } from '@sveltejs/kit';\n\n/** @type {import('./$types').LayoutServerLoad} */\nexport function load({ locals }) {\n\tif (!locals.user) {\n\t\terror(401, 'not logged in');\n\t}\n\n\tif (!locals.user.isAdmin) {\n\t\terror(403, 'not an admin');\n\t}\n}\n```\n\nCalling `error(...)` will throw an exception, making it easy to stop execution from inside helper functions.\n\nIf an [_unexpected_](errors#Unexpected-errors) error is thrown, SvelteKit will invoke [`handleError`](hooks#Shared-hooks-handleError) and treat it as a 500 Internal Error.\n\n\n## Redirects\n\nTo redirect users, use the `redirect` helper from `@sveltejs/kit` to specify the location to which they should be redirected alongside a `3xx` status code. Like `error(...)`, calling `redirect(...)` will throw an exception, making it easy to stop execution from inside helper functions.\n\n```js\n/// file: src/routes/user/+layout.server.js\n// @filename: ambient.d.ts\ndeclare namespace App {\n\tinterface Locals {\n\t\tuser?: {\n\t\t\tname: string;\n\t\t}\n\t}\n}\n\n// @filename: index.js\n//cut\nimport { redirect } from '@sveltejs/kit';\n\n/** @type {import('./$types').LayoutServerLoad} */\nexport function load({ locals }) {\n\tif (!locals.user) {\n\t\tredirect(307, '/login');\n\t}\n}\n```\n\n\nIn the browser, you can also navigate programmatically outside of a `load` function using [`goto`]($app-navigation#goto) from [`$app.navigation`]($app-navigation).\n\n\n## Streaming with promises\n\nWhen using a server `load`, promises will be streamed to the browser as they resolve. This is useful if you have slow, non-essential data, since you can start rendering the page before all the data is available:\n\n```js\n/// file: src/routes/blog/[slug]/+page.server.js\n// @filename: ambient.d.ts\ndeclare global {\n\tconst loadPost: (slug: string) => Promise<{ title: string, content: string }>;\n\tconst loadComments: (slug: string) => Promise<{ content: string }>;\n}\n\nexport {};\n\n// @filename: index.js\n//cut\n/** @type {import('./$types').PageServerLoad} */\nexport async function load({ params }) {\n\treturn {\n\t\t// make sure the `await` happens at the end, otherwise we\n\t\t// can't start loading comments until we've loaded the post\n\t\tcomments: loadComments(params.slug),\n\t\tpost: await loadPost(params.slug)\n\t};\n}\n```\n\nThis is useful for creating skeleton loading states, for example:\n\n```svelte\n<!file: src/routes/blog/[slug]/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n</script>\n\n<h1>{data.post.title}</h1>\n<div>{@html data.post.content}</div>\n\n{#await data.comments}\n\tLoading comments...\n{:then comments}\n\t{#each comments as comment}\n\t\t<p>{comment.content}</p>\n\t{/each}\n{:catch error}\n\t<p>error loading comments: {error.message}</p>\n{/await}\n```\n\nWhen streaming data, be careful to handle promise rejections correctly. More specifically, the server could crash with an \"unhandled promise rejection\" error if a lazy-loaded promise fails before rendering starts (at which point it's caught) and isn't handling the error in some way. When using SvelteKit's `fetch` directly in the `load` function, SvelteKit will handle this case for you. For other promises, it is enough to attach a noop-`catch` to the promise to mark it as handled.\n\n```js\n/// file: src/routes/+page.server.js\n/** @type {import('./$types').PageServerLoad} */\nexport function load({ fetch }) {\n\tconst ok_manual = Promise.reject();\n\tok_manual.catch(() => {});\n\n\treturn {\n\t\tok_manual,\n\t\tok_fetch: fetch('/fetch/that/could/fail'),\n\t\tdangerous_unhandled: Promise.reject()\n\t};\n}\n```\n\n\n\n\n\n## Parallel loading\n\nWhen rendering (or navigating to) a page, SvelteKit runs all `load` functions concurrently, avoiding a waterfall of requests. During client-side navigation, the result of calling multiple server `load` functions are grouped into a single response. Once all `load` functions have returned, the page is rendered.\n\n## Rerunning load functions\n\nSvelteKit tracks the dependencies of each `load` function to avoid rerunning it unnecessarily during navigation.\n\nFor example, given a pair of `load` functions like these...\n\n```js\n/// file: src/routes/blog/[slug]/+page.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function getPost(slug: string): Promise<{ title: string, content: string }>\n}\n\n// @filename: index.js\n//cut\nimport * as db from '$lib/server/database';\n\n/** @type {import('./$types').PageServerLoad} */\nexport async function load({ params }) {\n\treturn {\n\t\tpost: await db.getPost(params.slug)\n\t};\n}\n```\n\n```js\n/// file: src/routes/blog/[slug]/+layout.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function getPostSummaries(): Promise<Array<{ title: string, slug: string }>>\n}\n\n// @filename: index.js\n//cut\nimport * as db from '$lib/server/database';\n\n/** @type {import('./$types').LayoutServerLoad} */\nexport async function load() {\n\treturn {\n\t\tposts: await db.getPostSummaries()\n\t};\n}\n```\n\n...the one in `+page.server.js` will rerun if we navigate from `/blog/trying-the-raw-meat-diet` to `/blog/i-regret-my-choices` because `params.slug` has changed. The one in `+layout.server.js` will not, because the data is still valid. In other words, we won't call `db.getPostSummaries()` a second time.\n\nA `load` function that calls `await parent()` will also rerun if a parent `load` function is rerun.\n\nDependency tracking does not apply _after_ the `load` function has returned — for example, accessing `params.x` inside a nested [promise](#Streaming-with-promises) will not cause the function to rerun when `params.x` changes. (Don't worry, you'll get a warning in development if you accidentally do this.) Instead, access the parameter in the main body of your `load` function.\n\nSearch parameters are tracked independently from the rest of the url. For example, accessing `event.url.searchParams.get(\"x\")` inside a `load` function will make that `load` function re-run when navigating from `?x=1` to `?x=2`, but not when navigating from `?x=1&y=1` to `?x=1&y=2`.\n\n### Untracking dependencies\n\nIn rare cases, you may wish to exclude something from the dependency tracking mechanism. You can do this with the provided `untrack` function:\n\n```js\n/// file: src/routes/+page.js\n/** @type {import('./$types').PageLoad} */\nexport async function load({ untrack, url }) {\n\t// Untrack url.pathname so that path changes don't trigger a rerun\n\tif (untrack(() => url.pathname === '/')) {\n\t\treturn { message: 'Welcome!' };\n\t}\n}\n```\n\n### Manual invalidation\n\nYou can also rerun `load` functions that apply to the current page using [`invalidate(url)`]($app-navigation#invalidate), which reruns all `load` functions that depend on `url`, and [`invalidateAll()`]($app-navigation#invalidateAll), which reruns every `load` function. Server load functions will never automatically depend on a fetched `url` to avoid leaking secrets to the client.\n\nA `load` function depends on `url` if it calls `fetch(url)` or `depends(url)`. Note that `url` can be a custom identifier that starts with `[a-z]:`:\n\n```js\n/// file: src/routes/random-number/+page.js\n/** @type {import('./$types').PageLoad} */\nexport async function load({ fetch, depends }) {\n\t// load reruns when `invalidate('https://api.example.com/random-number')` is called...\n\tconst response = await fetch('https://api.example.com/random-number');\n\n\t// ...or when `invalidate('app:random')` is called\n\tdepends('app:random');\n\n\treturn {\n\t\tnumber: await response.json()\n\t};\n}\n```\n\n```svelte\n<!file: src/routes/random-number/+page.svelte>\n<script>\n\timport { invalidate, invalidateAll } from '$app/navigation';\n\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n\n\tfunction rerunLoadFunction() {\n\t\t// any of these will cause the `load` function to rerun\n\t\tinvalidate('app:random');\n\t\tinvalidate('https://api.example.com/random-number');\n\t\tinvalidate(url => url.href.includes('random-number'));\n\t\tinvalidateAll();\n\t}\n</script>\n\n<p>random number: {data.number}</p>\n<button onclick={rerunLoadFunction}>Update random number</button>\n```\n\n### When do load functions rerun?\n\nTo summarize, a `load` function will rerun in the following situations:\n\n- It references a property of `params` whose value has changed\n- It references a property of `url` (such as `url.pathname` or `url.search`) whose value has changed. Properties in `request.url` are _not_ tracked\n- It calls `url.searchParams.get(...)`, `url.searchParams.getAll(...)` or `url.searchParams.has(...)` and the parameter in question changes. Accessing other properties of `url.searchParams` will have the same effect as accessing `url.search`.\n- It calls `await parent()` and a parent `load` function reran\n- A child `load` function calls `await parent()` and is rerunning, and the parent is a server load function\n- It declared a dependency on a specific URL via [`fetch`](#Making-fetch-requests) (universal load only) or [`depends`](@sveltejs-kit#LoadEvent), and that URL was marked invalid with [`invalidate(url)`]($app-navigation#invalidate)\n- All active `load` functions were forcibly rerun with [`invalidateAll()`]($app-navigation#invalidateAll)\n\n`params` and `url` can change in response to a `<a href=\"..\">` link click, a [`<form>` interaction](form-actions#GET-vs-POST), a [`goto`]($app-navigation#goto) invocation, or a [`redirect`](@sveltejs-kit#redirect).\n\nNote that rerunning a `load` function will update the `data` prop inside the corresponding `+layout.svelte` or `+page.svelte`; it does _not_ cause the component to be recreated. As a result, internal state is preserved. If this isn't what you want, you can reset whatever you need to reset inside an [`afterNavigate`]($app-navigation#afterNavigate) callback, and/or wrap your component in a [`{#key ...}`](../svelte/key) block.\n\n## Implications for authentication\n\nA couple features of loading data have important implications for auth checks:\n- Layout `load` functions do not run on every request, such as during client side navigation between child routes. [(When do load functions rerun?)](load#Rerunning-load-functions-When-do-load-functions-rerun)\n- Layout and page `load` functions run concurrently unless `await parent()` is called. If a layout `load` throws, the page `load` function runs, but the client will not receive the returned data.\n\nThere are a few possible strategies to ensure an auth check occurs before protected code.\n\nTo prevent data waterfalls and preserve layout `load` caches:\n- Use [hooks](hooks) to protect multiple routes before any `load` functions run\n- Use auth guards directly in `+page.server.js` `load` functions for route specific protection\n\nPutting an auth guard in `+layout.server.js` requires all child pages to call `await parent()` before protected code. Unless every child page depends on returned data from `await parent()`, the other options will be more performant.\n\n## Using `getRequestEvent`\n\nWhen running server `load` functions, the `event` object passed to the function as an argument can also be retrieved with [`getRequestEvent`]($app-server#getRequestEvent). This allows shared logic (such as authentication guards) to access information about the current request without it needing to be passed around.\n\nFor example, you might have a function that requires users to be logged in, and redirects them to `/login` if not:\n\n```js\n/// file: src/lib/server/auth.js\n// @filename: ambient.d.ts\ninterface User {\n\tname: string;\n}\n\ndeclare namespace App {\n\tinterface Locals {\n\t\tuser?: User;\n\t}\n}\n\n// @filename: index.ts\n//cut\nimport { redirect } from '@sveltejs/kit';\nimport { getRequestEvent } from '$app/server';\n\nexport function requireLogin() {\n\tconst { locals, url } = getRequestEvent();\n\n\t// assume `locals.user` is populated in `handle`\n\tif (!locals.user) {\n\t\tconst redirectTo = url.pathname + url.search;\n\t\tconst params = new URLSearchParams({ redirectTo });\n\n\t\tredirect(307, `/login?${params}`);\n\t}\n\n\treturn locals.user;\n}\n```\n\nNow, you can call `requireLogin` in any `load` function (or [form action](form-actions), for example) to guarantee that the user is logged in:\n\n```js\n/// file: +page.server.js\n// @filename: ambient.d.ts\n\ndeclare module '$lib/server/auth' {\n\tinterface User {\n\t\tname: string;\n\t}\n\n\texport function requireLogin(): User;\n}\n\n// @filename: index.ts\n//cut\nimport { requireLogin } from '$lib/server/auth';\n\nexport function load() {\n\tconst user = requireLogin();\n\n\t// `user` is guaranteed to be a user object here, because otherwise\n\t// `requireLogin` would throw a redirect and we wouldn't get here\n\treturn {\n\t\tmessage: `hello ${user.name}!`\n\t};\n}\n```\n\n## Further reading\n\n- [Tutorial: Loading data](/tutorial/kit/page-data)\n- [Tutorial: Errors and redirects](/tutorial/kit/error-basics)\n- [Tutorial: Advanced loading](/tutorial/kit/await-parent)","size_bytes":29294,"metadata":{"title":"Loading data"},"created_at":"2025-07-18T15:47:38.768Z","updated_at":"2025-08-20T14:00:05.502Z"},{"path":"apps/svelte.dev/content/docs/kit/20-core-concepts/30-form-actions.md","title":"Form actions","filename":"30-form-actions.md","content":"A `+page.server.js` file can export _actions_, which allow you to `POST` data to the server using the `<form>` element.\n\nWhen using `<form>`, client-side JavaScript is optional, but you can easily _progressively enhance_ your form interactions with JavaScript to provide the best user experience.\n\n## Default actions\n\nIn the simplest case, a page declares a `default` action:\n\n```js\n/// file: src/routes/login/+page.server.js\n/** @satisfies {import('./$types').Actions} */\nexport const actions = {\n\tdefault: async (event) => {\n\t\t// TODO log the user in\n\t}\n};\n```\n\nTo invoke this action from the `/login` page, just add a `<form>` — no JavaScript needed:\n\n```svelte\n<!file: src/routes/login/+page.svelte>\n<form method=\"POST\">\n\t<label>\n\t\tEmail\n\t\t<input name=\"email\" type=\"email\">\n\t</label>\n\t<label>\n\t\tPassword\n\t\t<input name=\"password\" type=\"password\">\n\t</label>\n\t<button>Log in</button>\n</form>\n```\n\nIf someone were to click the button, the browser would send the form data via `POST` request to the server, running the default action.\n\n\nWe can also invoke the action from other pages (for example if there's a login widget in the nav in the root layout) by adding the `action` attribute, pointing to the page:\n\n```html\n/// file: src/routes/+layout.svelte\n<form method=\"POST\" action=\"/login\">\n\t<!-- content -->\n</form>\n```\n\n## Named actions\n\nInstead of one `default` action, a page can have as many named actions as it needs:\n\n```js\n/// file: src/routes/login/+page.server.js\n/** @satisfies {import('./$types').Actions} */\nexport const actions = {\ndefault: async (event) => {\nlogin: async (event) => {\n\t\t// TODO log the user in\n\t},\nregister: async (event) => {\n\t\t// TODO register the user\n\t}\n};\n```\n\nTo invoke a named action, add a query parameter with the name prefixed by a `/` character:\n\n```svelte\n<!file: src/routes/login/+page.svelte>\n<form method=\"POST\" action=\"?/register\">\n```\n\n```svelte\n<!file: src/routes/+layout.svelte>\n<form method=\"POST\" action=\"/login?/register\">\n```\n\nAs well as the `action` attribute, we can use the `formaction` attribute on a button to `POST` the same form data to a different action than the parent `<form>`:\n\n```svelte\n/// file: src/routes/login/+page.svelte\n<form method=\"POST\"action=\"?/login\">\n\t<label>\n\t\tEmail\n\t\t<input name=\"email\" type=\"email\">\n\t</label>\n\t<label>\n\t\tPassword\n\t\t<input name=\"password\" type=\"password\">\n\t</label>\n\t<button>Log in</button>\n\t<button formaction=\"?/register\">Register</button>\n</form>\n```\n\n\n## Anatomy of an action\n\nEach action receives a `RequestEvent` object, allowing you to read the data with `request.formData()`. After processing the request (for example, logging the user in by setting a cookie), the action can respond with data that will be available through the `form` property on the corresponding page and through `page.form` app-wide until the next update.\n\n```js\n/// file: src/routes/login/+page.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/db';\n\n// @filename: index.js\n//cut\nimport * as db from '$lib/server/db';\n\n/** @type {import('./$types').PageServerLoad} */\nexport async function load({ cookies }) {\n\tconst user = await db.getUserFromSession(cookies.get('sessionid'));\n\treturn { user };\n}\n\n/** @satisfies {import('./$types').Actions} */\nexport const actions = {\n\tlogin: async ({ cookies, request }) => {\n\t\tconst data = await request.formData();\n\t\tconst email = data.get('email');\n\t\tconst password = data.get('password');\n\n\t\tconst user = await db.getUser(email);\n\t\tcookies.set('sessionid', await db.createSession(user), { path: '/' });\n\n\t\treturn { success: true };\n\t},\n\tregister: async (event) => {\n\t\t// TODO register the user\n\t}\n};\n```\n\n```svelte\n<!file: src/routes/login/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data, form } = $props();\n</script>\n\n{#if form?.success}\n\t<!-- this message is ephemeral; it exists because the page was rendered in\n\t       response to a form submission. it will vanish if the user reloads -->\n\t<p>Successfully logged in! Welcome back, {data.user.name}</p>\n{/if}\n```\n\n> [!LEGACY]\n> `PageProps` was added in 2.16.0. In earlier versions, you had to type the `data` and `form` properties individually:\n> ```js\n> /// file: +page.svelte\n> /** @type {{ data: import('./$types').PageData, form: import('./$types').ActionData }} */\n> let { data, form } = $props();\n> ```\n>\n> In Svelte 4, you'd use `export let data` and `export let form` instead to declare properties.\n\n### Validation errors\n\nIf the request couldn't be processed because of invalid data, you can return validation errors — along with the previously submitted form values — back to the user so that they can try again. The `fail` function lets you return an HTTP status code (typically 400 or 422, in the case of validation errors) along with the data. The status code is available through `page.status` and the data through `form`:\n\n```js\n/// file: src/routes/login/+page.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/db';\n\n// @filename: index.js\n//cut\nimport { fail } from '@sveltejs/kit';\nimport * as db from '$lib/server/db';\n\n/** @satisfies {import('./$types').Actions} */\nexport const actions = {\n\tlogin: async ({ cookies, request }) => {\n\t\tconst data = await request.formData();\n\t\tconst email = data.get('email');\n\t\tconst password = data.get('password');\n\nif (!email) {\n\t\t\treturn fail(400, { email, missing: true });\n\t\t}\n\n\t\tconst user = await db.getUser(email);\n\nif (!user || user.password !== db.hash(password)) {\n\t\t\treturn fail(400, { email, incorrect: true });\n\t\t}\n\n\t\tcookies.set('sessionid', await db.createSession(user), { path: '/' });\n\n\t\treturn { success: true };\n\t},\n\tregister: async (event) => {\n\t\t// TODO register the user\n\t}\n};\n```\n\n\n```svelte\n/// file: src/routes/login/+page.svelte\n<form method=\"POST\" action=\"?/login\">\n{#if form?.missing}<p class=\"error\">The email field is required</p>{/if}\n\t{#if form?.incorrect}<p class=\"error\">Invalid credentials!</p>{/if}\n\t<label>\n\t\tEmail\n\t\t<input name=\"email\" type=\"email\"value={form?.email ?? ''}>\n\t</label>\n\t<label>\n\t\tPassword\n\t\t<input name=\"password\" type=\"password\">\n\t</label>\n\t<button>Log in</button>\n\t<button formaction=\"?/register\">Register</button>\n</form>\n```\n\nThe returned data must be serializable as JSON. Beyond that, the structure is entirely up to you. For example, if you had multiple forms on the page, you could distinguish which `<form>` the returned `form` data referred to with an `id` property or similar.\n\n### Redirects\n\nRedirects (and errors) work exactly the same as in [`load`](load#Redirects):\n\n```js\n// @errors: 2345\n/// file: src/routes/login/+page.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/db';\n\n// @filename: index.js\n//cut\nimport { fail,redirect} from '@sveltejs/kit';\nimport * as db from '$lib/server/db';\n\n/** @satisfies {import('./$types').Actions} */\nexport const actions = {\n\tlogin: async ({ cookies, request,url}) => {\n\t\tconst data = await request.formData();\n\t\tconst email = data.get('email');\n\t\tconst password = data.get('password');\n\n\t\tconst user = await db.getUser(email);\n\t\tif (!user) {\n\t\t\treturn fail(400, { email, missing: true });\n\t\t}\n\n\t\tif (user.password !== db.hash(password)) {\n\t\t\treturn fail(400, { email, incorrect: true });\n\t\t}\n\n\t\tcookies.set('sessionid', await db.createSession(user), { path: '/' });\n\nif (url.searchParams.has('redirectTo')) {\n\t\t\tredirect(303, url.searchParams.get('redirectTo'));\n\t\t}\n\n\t\treturn { success: true };\n\t},\n\tregister: async (event) => {\n\t\t// TODO register the user\n\t}\n};\n```\n\n## Loading data\n\nAfter an action runs, the page will be re-rendered (unless a redirect or an unexpected error occurs), with the action's return value available to the page as the `form` prop. This means that your page's `load` functions will run after the action completes.\n\nNote that `handle` runs before the action is invoked, and does not rerun before the `load` functions. This means that if, for example, you use `handle` to populate `event.locals` based on a cookie, you must update `event.locals` when you set or delete the cookie in an action:\n\n```js\n/// file: src/hooks.server.js\n// @filename: ambient.d.ts\ndeclare namespace App {\n\tinterface Locals {\n\t\tuser: {\n\t\t\tname: string;\n\t\t} | null\n\t}\n}\n\n// @filename: global.d.ts\ndeclare global {\n\tfunction getUser(sessionid: string | undefined): {\n\t\tname: string;\n\t};\n}\n\nexport {};\n\n// @filename: index.js\n//cut\n/** @type {import('@sveltejs/kit').Handle} */\nexport async function handle({ event, resolve }) {\n\tevent.locals.user = await getUser(event.cookies.get('sessionid'));\n\treturn resolve(event);\n}\n```\n\n```js\n/// file: src/routes/account/+page.server.js\n// @filename: ambient.d.ts\ndeclare namespace App {\n\tinterface Locals {\n\t\tuser: {\n\t\t\tname: string;\n\t\t} | null\n\t}\n}\n\n// @filename: index.js\n//cut\n/** @type {import('./$types').PageServerLoad} */\nexport function load(event) {\n\treturn {\n\t\tuser: event.locals.user\n\t};\n}\n\n/** @satisfies {import('./$types').Actions} */\nexport const actions = {\n\tlogout: async (event) => {\n\t\tevent.cookies.delete('sessionid', { path: '/' });\n\t\tevent.locals.user = null;\n\t}\n};\n```\n\n## Progressive enhancement\n\nIn the preceding sections we built a `/login` action that [works without client-side JavaScript](https://kryogenix.org/code/browser/everyonehasjs.html) — not a `fetch` in sight. That's great, but when JavaScript _is_ available we can progressively enhance our form interactions to provide a better user experience.\n\n### use:enhance\n\nThe easiest way to progressively enhance a form is to add the `use:enhance` action:\n\n```svelte\n/// file: src/routes/login/+page.svelte\n<script>\n\timport { enhance } from '$app/forms';\n\n\t/** @type {import('./$types').PageProps} */\n\tlet { form } = $props();\n</script>\n\n<form method=\"POST\"use:enhance>\n```\n\n\n\nWithout an argument, `use:enhance` will emulate the browser-native behaviour, just without the full-page reloads. It will:\n\n- update the `form` property, `page.form` and `page.status` on a successful or invalid response, but only if the action is on the same page you're submitting from. For example, if your form looks like `<form action=\"/somewhere/else\" ..>`, the `form` prop and the `page.form` state will _not_ be updated. This is because in the native form submission case you would be redirected to the page the action is on. If you want to have them updated either way, use [`applyAction`](#Progressive-enhancement-Customising-use:enhance)\n- reset the `<form>` element\n- invalidate all data using `invalidateAll` on a successful response\n- call `goto` on a redirect response\n- render the nearest `+error` boundary if an error occurs\n- [reset focus](accessibility#Focus-management) to the appropriate element\n\n### Customising use:enhance\n\nTo customise the behaviour, you can provide a `SubmitFunction` that runs immediately before the form is submitted, and (optionally) returns a callback that runs with the `ActionResult`.\n\n```svelte\n<form\n\tmethod=\"POST\"\n\tuse:enhance={({ formElement, formData, action, cancel, submitter }) => {\n\t\t// `formElement` is this `<form>` element\n\t\t// `formData` is its `FormData` object that's about to be submitted\n\t\t// `action` is the URL to which the form is posted\n\t\t// calling `cancel()` will prevent the submission\n\t\t// `submitter` is the `HTMLElement` that caused the form to be submitted\n\n\t\treturn async ({ result, update }) => {\n\t\t\t// `result` is an `ActionResult` object\n\t\t\t// `update` is a function which triggers the default logic that would be triggered if this callback wasn't set\n\t\t};\n\t}}\n>\n```\n\nYou can use these functions to show and hide loading UI, and so on.\n\nIf you return a callback, you override the default post-submission behavior. To get it back, call `update`, which accepts `invalidateAll` and `reset` parameters, or use `applyAction` on the result:\n\n```svelte\n/// file: src/routes/login/+page.svelte\n<script>\n\timport { enhance,applyAction} from '$app/forms';\n\n\t/** @type {import('./$types').PageProps} */\n\tlet { form } = $props();\n</script>\n\n<form\n\tmethod=\"POST\"\n\tuse:enhance={({ formElement, formData, action, cancel }) => {\n\t\treturn async ({ result }) => {\n\t\t\t// `result` is an `ActionResult` object\nif (result.type === 'redirect') {\n\t\t\t\tgoto(result.location);\n\t\t\t} else {\n\t\t\t\tawait applyAction(result);\n\t\t\t}\n\t\t};\n\t}}\n>\n```\n\nThe behaviour of `applyAction(result)` depends on `result.type`:\n\n- `success`, `failure` — sets `page.status` to `result.status` and updates `form` and `page.form` to `result.data` (regardless of where you are submitting from, in contrast to `update` from `enhance`)\n- `redirect` — calls `goto(result.location, { invalidateAll: true })`\n- `error` — renders the nearest `+error` boundary with `result.error`\n\nIn all cases, [focus will be reset](accessibility#Focus-management).\n\n### Custom event listener\n\nWe can also implement progressive enhancement ourselves, without `use:enhance`, with a normal event listener on the `<form>`:\n\n```svelte\n<!file: src/routes/login/+page.svelte>\n<script>\n\timport { invalidateAll, goto } from '$app/navigation';\n\timport { applyAction, deserialize } from '$app/forms';\n\n\t/** @type {import('./$types').PageProps} */\n\tlet { form } = $props();\n\n\t/** @param {SubmitEvent & { currentTarget: EventTarget & HTMLFormElement}} event */\n\tasync function handleSubmit(event) {\n\t\tevent.preventDefault();\n\t\tconst data = new FormData(event.currentTarget, event.submitter);\n\n\t\tconst response = await fetch(event.currentTarget.action, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: data\n\t\t});\n\n\t\t/** @type {import('@sveltejs/kit').ActionResult} */\n\t\tconst result = deserialize(await response.text());\n\n\t\tif (result.type === 'success') {\n\t\t\t// rerun all `load` functions, following the successful update\n\t\t\tawait invalidateAll();\n\t\t}\n\n\t\tapplyAction(result);\n\t}\n</script>\n\n<form method=\"POST\" onsubmit={handleSubmit}>\n\t<!-- content -->\n</form>\n```\n\nNote that you need to `deserialize` the response before processing it further using the corresponding method from `$app/forms`. `JSON.parse()` isn't enough because form actions - like `load` functions - also support returning `Date` or `BigInt` objects.\n\nIf you have a `+server.js` alongside your `+page.server.js`, `fetch` requests will be routed there by default. To `POST` to an action in `+page.server.js` instead, use the custom `x-sveltekit-action` header:\n\n```js\n// @errors: 2532 2304\nconst response = await fetch(this.action, {\n\tmethod: 'POST',\n\tbody: data,\nheaders: {\n\t\t'x-sveltekit-action': 'true'\n\t}\n});\n```\n\n## Alternatives\n\nForm actions are the preferred way to send data to the server, since they can be progressively enhanced, but you can also use [`+server.js`](routing#server) files to expose (for example) a JSON API. Here's how such an interaction could look like:\n\n```svelte\n<!file: src/routes/send-message/+page.svelte>\n<script>\n\tfunction rerun() {\n\t\tfetch('/api/ci', {\n\t\t\tmethod: 'POST'\n\t\t});\n\t}\n</script>\n\n<button onclick={rerun}>Rerun CI</button>\n```\n\n```js\n// @errors: 2355 1360 2322\n/// file: src/routes/api/ci/+server.js\n/** @type {import('./$types').RequestHandler} */\nexport function POST() {\n\t// do something\n}\n```\n\n## GET vs POST\n\nAs we've seen, to invoke a form action you must use `method=\"POST\"`.\n\nSome forms don't need to `POST` data to the server — search inputs, for example. For these you can use `method=\"GET\"` (or, equivalently, no `method` at all), and SvelteKit will treat them like `<a>` elements, using the client-side router instead of a full page navigation:\n\n```html\n<form action=\"/search\">\n\t<label>\n\t\tSearch\n\t\t<input name=\"q\">\n\t</label>\n</form>\n```\n\nSubmitting this form will navigate to `/search?q=...` and invoke your load function but will not invoke an action. As with `<a>` elements, you can set the [`data-sveltekit-reload`](link-options#data-sveltekit-reload), [`data-sveltekit-replacestate`](link-options#data-sveltekit-replacestate), [`data-sveltekit-keepfocus`](link-options#data-sveltekit-keepfocus) and [`data-sveltekit-noscroll`](link-options#data-sveltekit-noscroll) attributes on the `<form>` to control the router's behaviour.\n\n## Further reading\n\n- [Tutorial: Forms](/tutorial/kit/the-form-element)","size_bytes":16067,"metadata":{"title":"Form actions"},"created_at":"2025-07-18T15:47:38.770Z","updated_at":"2025-09-25T14:00:05.226Z"},{"path":"apps/svelte.dev/content/docs/kit/20-core-concepts/40-page-options.md","title":"Page options","filename":"40-page-options.md","content":"By default, SvelteKit will render (or [prerender](glossary#Prerendering)) any component first on the server and send it to the client as HTML. It will then render the component again in the browser to make it interactive in a process called [_hydration_](glossary#Hydration). For this reason, you need to ensure that components can run in both places. SvelteKit will then initialize a [_router_](routing) that takes over subsequent navigations.\n\nYou can control each of these on a page-by-page basis by exporting options from [`+page.js`](routing#page-page.js) or [`+page.server.js`](routing#page-page.server.js), or for groups of pages using a shared [`+layout.js`](routing#layout-layout.js) or [`+layout.server.js`](routing#layout-layout.server.js). To define an option for the whole app, export it from the root layout. Child layouts and pages override values set in parent layouts, so — for example — you can enable prerendering for your entire app then disable it for pages that need to be dynamically rendered.\n\nYou can mix and match these options in different areas of your app. For example, you could prerender your marketing page for maximum speed, server-render your dynamic pages for SEO and accessibility and turn your admin section into an SPA by rendering it on the client only. This makes SvelteKit very versatile.\n\n## prerender\n\nIt's likely that at least some routes of your app can be represented as a simple HTML file generated at build time. These routes can be [_prerendered_](glossary#Prerendering).\n\n```js\n/// file: +page.js/+page.server.js/+server.js\nexport const prerender = true;\n```\n\nAlternatively, you can set `export const prerender = true` in your root `+layout.js` or `+layout.server.js` and prerender everything except pages that are explicitly marked as _not_ prerenderable:\n\n```js\n/// file: +page.js/+page.server.js/+server.js\nexport const prerender = false;\n```\n\nRoutes with `prerender = true` will be excluded from manifests used for dynamic SSR, making your server (or serverless/edge functions) smaller. In some cases you might want to prerender a route but also include it in the manifest (for example, with a route like `/blog/[slug]` where you want to prerender your most recent/popular content but server-render the long tail) — for these cases, there's a third option, 'auto':\n\n```js\n/// file: +page.js/+page.server.js/+server.js\nexport const prerender = 'auto';\n```\n\n\nThe prerenderer will start at the root of your app and generate files for any prerenderable pages or `+server.js` routes it finds. Each page is scanned for `<a>` elements that point to other pages that are candidates for prerendering — because of this, you generally don't need to specify which pages should be accessed. If you _do_ need to specify which pages should be accessed by the prerenderer, you can do so with [`config.kit.prerender.entries`](configuration#prerender), or by exporting an [`entries`](#entries) function from your dynamic route.\n\nWhile prerendering, the value of `building` imported from [`$app/environment`]($app-environment) will be `true`.\n\n### Prerendering server routes\n\nUnlike the other page options, `prerender` also applies to `+server.js` files. These files are _not_ affected by layouts, but will inherit default values from the pages that fetch data from them, if any. For example if a `+page.js` contains this `load` function...\n\n```js\n/// file: +page.js\nexport const prerender = true;\n\n/** @type {import('./$types').PageLoad} */\nexport async function load({ fetch }) {\n\tconst res = await fetch('/my-server-route.json');\n\treturn await res.json();\n}\n```\n\n...then `src/routes/my-server-route.json/+server.js` will be treated as prerenderable if it doesn't contain its own `export const prerender = false`.\n\n### When not to prerender\n\nThe basic rule is this: for a page to be prerenderable, any two users hitting it directly must get the same content from the server.\n\n\nNote that you can still prerender pages that load data based on the page's parameters, such as a `src/routes/blog/[slug]/+page.svelte` route.\n\nAccessing [`url.searchParams`](load#Using-URL-data-url) during prerendering is forbidden. If you need to use it, ensure you are only doing so in the browser (for example in `onMount`).\n\nPages with [actions](form-actions) cannot be prerendered, because a server must be able to handle the action `POST` requests.\n\n### Route conflicts\n\nBecause prerendering writes to the filesystem, it isn't possible to have two endpoints that would cause a directory and a file to have the same name. For example, `src/routes/foo/+server.js` and `src/routes/foo/bar/+server.js` would try to create `foo` and `foo/bar`, which is impossible.\n\nFor that reason among others, it's recommended that you always include a file extension — `src/routes/foo.json/+server.js` and `src/routes/foo/bar.json/+server.js` would result in `foo.json` and `foo/bar.json` files living harmoniously side-by-side.\n\nFor _pages_, we skirt around this problem by writing `foo/index.html` instead of `foo`.\n\n### Troubleshooting\n\nIf you encounter an error like 'The following routes were marked as prerenderable, but were not prerendered' it's because the route in question (or a parent layout, if it's a page) has `export const prerender = true` but the page wasn't reached by the prerendering crawler and thus wasn't prerendered.\n\nSince these routes cannot be dynamically server-rendered, this will cause errors when people try to access the route in question. There are a few ways to fix it:\n\n* Ensure that SvelteKit can find the route by following links from [`config.kit.prerender.entries`](configuration#prerender) or the [`entries`](#entries) page option. Add links to dynamic routes (i.e. pages with `[parameters]` ) to this option if they are not found through crawling the other entry points, else they are not prerendered because SvelteKit doesn't know what value the parameters should have. Pages not marked as prerenderable will be ignored and their links to other pages will not be crawled, even if some of them would be prerenderable.\n* Ensure that SvelteKit can find the route by discovering a link to it from one of your other prerendered pages that have server-side rendering enabled.\n* Change `export const prerender = true` to `export const prerender = 'auto'`. Routes with `'auto'` can be dynamically server rendered\n\n## entries\n\nSvelteKit will discover pages to prerender automatically, by starting at _entry points_ and crawling them. By default, all your non-dynamic routes are considered entry points — for example, if you have these routes...\n\n```sh\n/             # non-dynamic\n/blog         # non-dynamic\n/blog/[slug]  # dynamic, because of `[slug]`\n```\n\n...SvelteKit will prerender `/` and `/blog`, and in the process discover links like `<a href=\"/blog/hello-world\">` which give it new pages to prerender.\n\nMost of the time, that's enough. In some situations, links to pages like `/blog/hello-world` might not exist (or might not exist on prerendered pages), in which case we need to tell SvelteKit about their existence.\n\nThis can be done with [`config.kit.prerender.entries`](configuration#prerender), or by exporting an `entries` function from a `+page.js`, a `+page.server.js` or a `+server.js` belonging to a dynamic route:\n\n```js\n/// file: src/routes/blog/[slug]/+page.server.js\n/** @type {import('./$types').EntryGenerator} */\nexport function entries() {\n\treturn [\n\t\t{ slug: 'hello-world' },\n\t\t{ slug: 'another-blog-post' }\n\t];\n}\n\nexport const prerender = true;\n```\n\n`entries` can be an `async` function, allowing you to (for example) retrieve a list of posts from a CMS or database, in the example above.\n\n## ssr\n\nNormally, SvelteKit renders your page on the server before sending that HTML to the client where it's [hydrated](glossary#Hydration). This is also required for prerendering to save the full contents of a page.\n\nIf you set `ssr` to `false`, it renders an empty 'shell' page instead. This is useful if your page is unable to be rendered on the server (because you use browser-only globals like `document` for example), but in most situations it's not recommended ([see appendix](glossary#SSR)).\n\n```js\n/// file: +page.js\nexport const ssr = false;\n// If both `ssr` and `csr` are `false`, nothing will be rendered!\n```\n\nIf you add `export const ssr = false` to your root `+layout.js`, your entire app will only be rendered on the client — which essentially means you turn your app into an [SPA](glossary#SPA). You should not do this if your goal is to build a [statically generated site](glossary#SSG).\n\n\n## csr\n\nOrdinarily, SvelteKit [hydrates](glossary#Hydration) your server-rendered HTML into an interactive client-side-rendered (CSR) page. Some pages don't require JavaScript at all — many blog posts and 'about' pages fall into this category. In these cases you can disable CSR:\n\n```js\n/// file: +page.js\nexport const csr = false;\n// If both `csr` and `ssr` are `false`, nothing will be rendered!\n```\n\nDisabling CSR does not ship any JavaScript to the client. This means:\n\n* The webpage should work with HTML and CSS only.\n* `<script>` tags inside all Svelte components are removed.\n* `<form>` elements cannot be [progressively enhanced](form-actions#Progressive-enhancement).\n* Links are handled by the browser with a full-page navigation.\n* Hot Module Replacement (HMR) will be disabled.\n\nYou can enable `csr` during development (for example to take advantage of HMR) like so:\n\n```js\n/// file: +page.js\nimport { dev } from '$app/environment';\n\nexport const csr = dev;\n```\n\n## trailingSlash\n\nBy default, SvelteKit will remove trailing slashes from URLs — if you visit `/about/`, it will respond with a redirect to `/about`. You can change this behaviour with the `trailingSlash` option, which can be one of `'never'` (the default), `'always'`, or `'ignore'`.\n\nAs with other page options, you can export this value from a `+layout.js` or a `+layout.server.js` and it will apply to all child pages. You can also export the configuration from `+server.js` files.\n\n```js\n/// file: src/routes/+layout.js\nexport const trailingSlash = 'always';\n```\n\nThis option also affects [prerendering](#prerender). If `trailingSlash` is `always`, a route like `/about` will result in an `about/index.html` file, otherwise it will create `about.html`, mirroring static webserver conventions.\n\n\n## config\n\nWith the concept of [adapters](adapters), SvelteKit is able to run on a variety of platforms. Each of these might have specific configuration to further tweak the deployment — for example on Vercel you could choose to deploy some parts of your app on the edge and others on serverless environments.\n\n`config` is an object with key-value pairs at the top level. Beyond that, the concrete shape is dependent on the adapter you're using. Every adapter should provide a `Config` interface to import for type safety. Consult the documentation of your adapter for more information.\n\n```js\n// @filename: ambient.d.ts\ndeclare module 'some-adapter' {\n\texport interface Config { runtime: string }\n}\n\n// @filename: index.js\n//cut\n/// file: src/routes/+page.js\n/** @type {import('some-adapter').Config} */\nexport const config = {\n\truntime: 'edge'\n};\n```\n\n`config` objects are merged at the top level (but _not_ deeper levels). This means you don't need to repeat all the values in a `+page.js` if you want to only override some of the values in the upper `+layout.js`. For example this layout configuration...\n\n```js\n/// file: src/routes/+layout.js\nexport const config = {\n\truntime: 'edge',\n\tregions: 'all',\n\tfoo: {\n\t\tbar: true\n\t}\n}\n```\n\n...is overridden by this page configuration...\n\n```js\n/// file: src/routes/+page.js\nexport const config = {\n\tregions: ['us1', 'us2'],\n\tfoo: {\n\t\tbaz: true\n\t}\n}\n```\n\n...which results in the config value `{ runtime: 'edge', regions: ['us1', 'us2'], foo: { baz: true } }` for that page.\n\n## Further reading\n\n- [Tutorial: Page options](/tutorial/kit/page-options)","size_bytes":11985,"metadata":{"title":"Page options"},"created_at":"2025-07-18T15:47:38.772Z","updated_at":"2026-02-14T01:33:24.853Z"},{"path":"apps/svelte.dev/content/docs/kit/20-core-concepts/50-state-management.md","title":"State management","filename":"50-state-management.md","content":"If you're used to building client-only apps, state management in an app that spans server and client might seem intimidating. This section provides tips for avoiding some common gotchas.\n\n## Avoid shared state on the server\n\nBrowsers are _stateful_ — state is stored in memory as the user interacts with the application. Servers, on the other hand, are _stateless_ — the content of the response is determined entirely by the content of the request.\n\nConceptually, that is. In reality, servers are often long-lived and shared by multiple users. For that reason it's important not to store data in shared variables. For example, consider this code:\n\n```js\n// @errors: 7034 7005\n/// file: +page.server.js\nlet user;\n\n/** @type {import('./$types').PageServerLoad} */\nexport function load() {\n\treturn { user };\n}\n\n/** @satisfies {import('./$types').Actions} */\nexport const actions = {\n\tdefault: async ({ request }) => {\n\t\tconst data = await request.formData();\n\n\t\t// NEVER DO THIS!\n\t\tuser = {\n\t\t\tname: data.get('name'),\n\t\t\tembarrassingSecret: data.get('secret')\n\t\t};\n\t}\n}\n```\n\nThe `user` variable is shared by everyone who connects to this server. If Alice submitted an embarrassing secret, and Bob visited the page after her, Bob would know Alice's secret. In addition, when Alice returns to the site later in the day, the server may have restarted, losing her data.\n\nInstead, you should _authenticate_ the user using [`cookies`](load#Cookies) and persist the data to a database.\n\n## No side-effects in load\n\nFor the same reason, your `load` functions should be _pure_ — no side-effects (except maybe the occasional `console.log(...)`). For example, you might be tempted to write to a store or global state inside a `load` function so that you can use the value in your components:\n\n```js\n/// file: +page.js\n// @filename: ambient.d.ts\ndeclare module '$lib/user' {\n\texport const user: { set: (value: any) => void };\n}\n\n// @filename: index.js\n//cut\nimport { user } from '$lib/user';\n\n/** @type {import('./$types').PageLoad} */\nexport async function load({ fetch }) {\n\tconst response = await fetch('/api/user');\n\n\t// NEVER DO THIS!\n\tuser.set(await response.json());\n}\n```\n\nAs with the previous example, this puts one user's information in a place that is shared by _all_ users. Instead, just return the data...\n\n```js\n/// file: +page.js\n/** @type {import('./$types').PageLoad} */\nexport async function load({ fetch }) {\n\tconst response = await fetch('/api/user');\n\nreturn {\n\t\tuser: await response.json()\n\t};\n}\n```\n\n...and pass it around to the components that need it, or use [`page.data`](load#page.data).\n\nIf you're not using SSR, then there's no risk of accidentally exposing one user's data to another. But you should still avoid side-effects in your `load` functions — your application will be much easier to reason about without them.\n\n## Using state and stores with context\n\nYou might wonder how we're able to use `page.data` and other [app state]($app-state) (or [app stores]($app-stores)) if we can't use global state. The answer is that app state and app stores on the server use Svelte's [context API](/tutorial/svelte/context-api) — the state (or store) is attached to the component tree with `setContext`, and when you subscribe you retrieve it with `getContext`. We can do the same thing with our own state:\n\n```svelte\n<!file: src/routes/+layout.svelte>\n<script>\n\timport { setContext } from 'svelte';\n\n\t/** @type {import('./$types').LayoutProps} */\n\tlet { data } = $props();\n\n\t// Pass a function referencing our state\n\t// to the context for child components to access\n\tsetContext('user', () => data.user);\n</script>\n```\n\n```svelte\n<!file: src/routes/user/+page.svelte>\n<script>\n\timport { getContext } from 'svelte';\n\n\t// Retrieve user store from context\n\tconst user = getContext('user');\n</script>\n\n<p>Welcome {user().name}</p>\n```\n\n\n> [!LEGACY]\n> You also use stores from `svelte/store` for this, but when using Svelte 5 it is recommended to make use of universal reactivity instead.\n\nUpdating the value of context-based state in deeper-level pages or components while the page is being rendered via SSR will not affect the value in the parent component because it has already been rendered by the time the state value is updated. In contrast, on the client (when CSR is enabled, which is the default) the value will be propagated and components, pages, and layouts higher in the hierarchy will react to the new value. Therefore, to avoid values 'flashing' during state updates during hydration, it is generally recommended to pass state down into components rather than up.\n\nIf you're not using SSR (and can guarantee that you won't need to use SSR in future) then you can safely keep state in a shared module, without using the context API.\n\n## Component and page state is preserved\n\nWhen you navigate around your application, SvelteKit reuses existing layout and page components. For example, if you have a route like this...\n\n```svelte\n<!file: src/routes/blog/[slug]/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n\n\t// THIS CODE IS BUGGY!\n\tconst wordCount = data.content.split(' ').length;\n\tconst estimatedReadingTime = wordCount / 250;\n</script>\n\n<header>\n\t<h1>{data.title}</h1>\n\t<p>Reading time: {Math.round(estimatedReadingTime)} minutes</p>\n</header>\n\n<div>{@html data.content}</div>\n```\n\n...then navigating from `/blog/my-short-post` to `/blog/my-long-post` won't cause the layout, page and any other components within to be destroyed and recreated. Instead the `data` prop (and by extension `data.title` and `data.content`) will update (as it would with any other Svelte component) and, because the code isn't rerunning, lifecycle methods like `onMount` and `onDestroy` won't rerun and `estimatedReadingTime` won't be recalculated.\n\nInstead, we need to make the value [_reactive_](/tutorial/svelte/state):\n\n```svelte\n/// file: src/routes/blog/[slug]/+page.svelte\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data } = $props();\n\nlet wordCount = $derived(data.content.split(' ').length);\n\tlet estimatedReadingTime = $derived(wordCount / 250);\n</script>\n```\n\n\nReusing components like this means that things like sidebar scroll state are preserved, and you can easily animate between changing values. In the case that you do need to completely destroy and remount a component on navigation, you can use this pattern:\n\n```svelte\n<script>\n\timport { page } from '$app/state';\n</script>\n\n{#key page.url.pathname}\n\t<BlogPost title={data.title} content={data.title} />\n{/key}\n```\n\n## Storing state in the URL\n\nIf you have state that should survive a reload and/or affect SSR, such as filters or sorting rules on a table, URL search parameters (like `?sort=price&order=ascending`) are a good place to put them. You can put them in `<a href=\"...\">` or `<form action=\"...\">` attributes, or set them programmatically via `goto('?key=value')`. They can be accessed inside `load` functions via the `url` parameter, and inside components via `page.url.searchParams`.\n\n## Storing ephemeral state in snapshots\n\nSome UI state, such as 'is the accordion open?', is disposable — if the user navigates away or refreshes the page, it doesn't matter if the state is lost. In some cases, you _do_ want the data to persist if the user navigates to a different page and comes back, but storing the state in the URL or in a database would be overkill. For this, SvelteKit provides [snapshots](snapshots), which let you associate component state with a history entry.","size_bytes":7564,"metadata":{"title":"State management"},"created_at":"2025-07-18T15:47:38.773Z","updated_at":"2026-02-20T02:00:04.578Z"},{"path":"apps/svelte.dev/content/docs/kit/20-core-concepts/60-remote-functions.md","title":"Remote functions","filename":"60-remote-functions.md","content":"<blockquote class=\"since note\">\n\t<p>Available since 2.27</p>\n</blockquote>\n\nRemote functions are a tool for type-safe communication between client and server. They can be _called_ anywhere in your app, but always _run_ on the server, meaning they can safely access [server-only modules](server-only-modules) containing things like environment variables and database clients.\n\nCombined with Svelte's experimental support for [`await`](/docs/svelte/await-expressions), it allows you to load and manipulate data directly inside your components.\n\nThis feature is currently experimental, meaning it is likely to contain bugs and is subject to change without notice. You must opt in by adding the `kit.experimental.remoteFunctions` option in your `svelte.config.js` and optionally, the `compilerOptions.experimental.async` option to use `await` in components:\n\n```js\n/// file: svelte.config.js\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\texperimental: {\n\t\t\tremoteFunctions: true\n\t\t}\n\t},\n\tcompilerOptions: {\n\t\texperimental: {\n\t\t\tasync: true\n\t\t}\n\t}\n};\n\nexport default config;\n```\n\n## Overview\n\nRemote functions are exported from a `.remote.js` or `.remote.ts` file, and come in four flavours: `query`, `form`, `command` and `prerender`. On the client, the exported functions are transformed to `fetch` wrappers that invoke their counterparts on the server via a generated HTTP endpoint. Remote files can be placed anywhere in your `src` directory (except inside the `src/lib/server` directory), and third party libraries can provide them, too.\n\n## query\n\nThe `query` function allows you to read dynamic data from the server (for _static_ data, consider using [`prerender`](#prerender) instead):\n\n```js\n/// file: src/routes/blog/data.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n// @filename: index.js\n//cut\nimport { query } from '$app/server';\nimport * as db from '$lib/server/database';\n\nexport const getPosts = query(async () => {\n\tconst posts = await db.sql`\n\t\tSELECT title, slug\n\t\tFROM post\n\t\tORDER BY published_at\n\t\tDESC\n\t`;\n\n\treturn posts;\n});\n```\n\n>\n> The `db.sql` function above is a [tagged template function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) that escapes any interpolated values.\n\nThe query returned from `getPosts` works as a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to `posts`:\n\n```svelte\n<!file: src/routes/blog/+page.svelte>\n<script>\n\timport { getPosts } from './data.remote';\n</script>\n\n<h1>Recent posts</h1>\n\n<ul>\n\t{#each await getPosts() as { title, slug }}\n\t\t<li><a href=\"/blog/{slug}\">{title}</a></li>\n\t{/each}\n</ul>\n```\n\nUntil the promise resolves — and if it errors — the nearest [`<svelte:boundary>`](../svelte/svelte-boundary) will be invoked.\n\nWhile using `await` is recommended, as an alternative the query also has `loading`, `error` and `current` properties:\n\n```svelte\n<!file: src/routes/blog/+page.svelte>\n<script>\n\timport { getPosts } from './data.remote';\n\n\tconst query = getPosts();\n</script>\n\n<h1>Recent posts</h1>\n\n{#if query.error}\n\t<p>oops!</p>\n{:else if query.loading}\n\t<p>loading...</p>\n{:else}\n\t<ul>\n\t\t{#each query.current as { title, slug }}\n\t\t\t<li><a href=\"/blog/{slug}\">{title}</a></li>\n\t\t{/each}\n\t</ul>\n{/if}\n```\n\n\n### Query arguments\n\nQuery functions can accept an argument, such as the `slug` of an individual post:\n\n```svelte\n<!file: src/routes/blog/[slug]/+page.svelte>\n<script>\n\timport { getPost } from '../data.remote';\n\n\tlet { params } = $props();\n\n\tconst post = $derived(await getPost(params.slug));\n</script>\n\n<h1>{post.title}</h1>\n<div>{@html post.content}</div>\n```\n\nSince `getPost` exposes an HTTP endpoint, it's important to validate this argument to be sure that it's the correct type. For this, we can use any [Standard Schema](https://standardschema.dev/) validation library such as [Zod](https://zod.dev/) or [Valibot](https://valibot.dev/):\n\n```js\n/// file: src/routes/blog/data.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n// @filename: index.js\n//cut\nimport * as v from 'valibot';\nimport { error } from '@sveltejs/kit';\nimport { query } from '$app/server';\nimport * as db from '$lib/server/database';\n\nexport const getPosts = query(async () => { /* ... */ });\n\nexport const getPost = query(v.string(), async (slug) => {\n\tconst [post] = await db.sql`\n\t\tSELECT * FROM post\n\t\tWHERE slug = ${slug}\n\t`;\n\n\tif (!post) error(404, 'Not found');\n\treturn post;\n});\n```\n\nBoth the argument and the return value are serialized with [devalue](https://github.com/sveltejs/devalue), which handles types like `Date` and `Map` (and custom types defined in your [transport hook](hooks#Universal-hooks-transport)) in addition to JSON.\n\n### Refreshing queries\n\nAny query can be re-fetched via its `refresh` method, which retrieves the latest value from the server:\n\n```svelte\n<button onclick={() => getPosts().refresh()}>\n\tCheck for new posts\n</button>\n```\n\n\n## query.batch\n\n`query.batch` works like `query` except that it batches requests that happen within the same macrotask. This solves the so-called n+1 problem: rather than each query resulting in a separate database call (for example), simultaneous queries are grouped together.\n\nOn the server, the callback receives an array of the arguments the function was called with. It must return a function of the form `(input: Input, index: number) => Output`. SvelteKit will then call this with each of the input arguments to resolve the individual calls with their results.\n\n```js\n/// file: weather.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n// @filename: index.js\n//cut\nimport * as v from 'valibot';\nimport { query } from '$app/server';\nimport * as db from '$lib/server/database';\n\nexport const getWeather = query.batch(v.string(), async (cityIds) => {\n\tconst weather = await db.sql`\n\t\tSELECT * FROM weather\n\t\tWHERE city_id = ANY(${cityIds})\n\t`;\n\tconst lookup = new Map(weather.map(w => [w.city_id, w]));\n\n\treturn (cityId) => lookup.get(cityId);\n});\n```\n\n```svelte\n<!file: Weather.svelte>\n<script>\n\timport CityWeather from './CityWeather.svelte';\n\timport { getWeather } from './weather.remote';\n\n\tlet { cities } = $props();\n\tlet limit = $state(5);\n</script>\n\n<h2>Weather</h2>\n\n{#each cities.slice(0, limit) as city}\n\t<h3>{city.name}</h3>\n\t<CityWeather weather={await getWeather(city.id)} />\n{/each}\n\n{#if cities.length > limit}\n\t<button onclick={() => limit += 5}>\n\t\tLoad more\n\t</button>\n{/if}\n```\n\n## form\n\nThe `form` function makes it easy to write data to the server. It takes a callback that receives `data` constructed from the submitted [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)...\n\n```ts\n/// file: src/routes/blog/data.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n\ndeclare module '$lib/server/auth' {\n\tinterface User {\n\t\tname: string;\n\t}\n\n\t/**\n\t * Gets a user's info from their cookies, using `getRequestEvent`\n\t */\n\texport function getUser(): Promise<User | null>;\n}\n// @filename: index.js\n//cut\nimport * as v from 'valibot';\nimport { error, redirect } from '@sveltejs/kit';\nimport { query, form } from '$app/server';\nimport * as db from '$lib/server/database';\nimport * as auth from '$lib/server/auth';\n\nexport const getPosts = query(async () => { /* ... */ });\n\nexport const getPost = query(v.string(), async (slug) => { /* ... */ });\n\nexport const createPost = form(\n\tv.object({\n\t\ttitle: v.pipe(v.string(), v.nonEmpty()),\n\t\tcontent:v.pipe(v.string(), v.nonEmpty())\n\t}),\n\tasync ({ title, content }) => {\n\t\t// Check the user is logged in\n\t\tconst user = await auth.getUser();\n\t\tif (!user) error(401, 'Unauthorized');\n\n\t\tconst slug = title.toLowerCase().replace(/ /g, '-');\n\n\t\t// Insert into the database\n\t\tawait db.sql`\n\t\t\tINSERT INTO post (slug, title, content)\n\t\t\tVALUES (${slug}, ${title}, ${content})\n\t\t`;\n\n\t\t// Redirect to the newly created page\n\t\tredirect(303, `/blog/${slug}`);\n\t}\n);\n```\n\n...and returns an object that can be spread onto a `<form>` element. The callback is called whenever the form is submitted.\n\n```svelte\n<!file: src/routes/blog/new/+page.svelte>\n<script>\n\timport { createPost } from '../data.remote';\n</script>\n\n<h1>Create a new post</h1>\n\n<form {...createPost}>\n\t<!-- form content goes here -->\n\n\t<button>Publish!</button>\n</form>\n```\n\nThe form object contains `method` and `action` properties that allow it to work without JavaScript (i.e. it submits data and reloads the page). It also has an [attachment](/docs/svelte/@attach) that progressively enhances the form when JavaScript is available, submitting data *without* reloading the entire page.\n\nAs with `query`, if the callback uses the submitted `data`, it should be [validated](#query-Query-arguments) by passing a [Standard Schema](https://standardschema.dev) as the first argument to `form`.\n\n### Fields\n\nA form is composed of a set of _fields_, which are defined by the schema. In the case of `createPost`, we have two fields, `title` and `content`, which are both strings. To get the attributes for a field, call its `.as(...)` method, specifying which [input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#input_types) to use:\n\n```svelte\n<form {...createPost}>\n\t<label>\n\t\t<h2>Title</h2>\n\t\t<input {...createPost.fields.title.as('text')} />\n\t</label>\n\n\t<label>\n\t\t<h2>Write your post</h2>\n\t\t<textarea {...createPost.fields.content.as('text')}></textarea>\n\t</label>\n\n\t<button>Publish!</button>\n</form>\n```\n\nThese attributes allow SvelteKit to set the correct input type, set a `name` that is used to construct the `data` passed to the handler, populate the `value` of the form (for example following a failed submission, to save the user having to re-enter everything), and set the [`aria-invalid`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-invalid) state.\n\n\nFields can be nested in objects and arrays, and their values can be strings, numbers, booleans or `File` objects. For example, if your schema looked like this...\n\n```js\n/// file: data.remote.js\nimport * as v from 'valibot';\nimport { form } from '$app/server';\n//cut\nconst datingProfile = v.object({\n\tname: v.string(),\n\tphoto: v.file(),\n\tinfo: v.object({\n\t\theight: v.number(),\n\t\tlikesDogs: v.optional(v.boolean(), false)\n\t}),\n\tattributes: v.array(v.string())\n});\n\nexport const createProfile = form(datingProfile, (data) => { /* ... */ });\n```\n\n...your form could look like this:\n\n```svelte\n<script>\n\timport { createProfile } from './data.remote';\n\n\tconst { name, photo, info, attributes } = createProfile.fields;\n</script>\n\n<form {...createProfile} enctype=\"multipart/form-data\">\n\t<label>\n\t\t<input {...name.as('text')} /> Name\n\t</label>\n\n\t<label>\n\t\t<input {...photo.as('file')} /> Photo\n\t</label>\n\n\t<label>\n\t\t<input {...info.height.as('number')} /> Height (cm)\n\t</label>\n\n\t<label>\n\t\t<input {...info.likesDogs.as('checkbox')} /> I like dogs\n\t</label>\n\n\t<h2>My best attributes</h2>\n\t<input {...attributes[0].as('text')} />\n\t<input {...attributes[1].as('text')} />\n\t<input {...attributes[2].as('text')} />\n\n\t<button>submit</button>\n</form>\n```\n\nBecause our form contains a `file` input, we've added an `enctype=\"multipart/form-data\"` attribute. The values for `info.height` and `info.likesDogs` are coerced to a number and a boolean respectively.\n\n\nIn the case of `radio` and `checkbox` inputs that all belong to the same field, the `value` must be specified as a second argument to `.as(...)`:\n\n```js\n/// file: data.remote.js\nimport * as v from 'valibot';\nimport { form } from '$app/server';\n//cut\nexport const operatingSystems = /** @type {const} */ (['windows', 'mac', 'linux']);\nexport const languages = /** @type {const} */ (['html', 'css', 'js']);\n\nexport const survey = form(\n\tv.object({\n\t\toperatingSystem: v.picklist(operatingSystems),\n\t\tlanguages: v.optional(v.array(v.picklist(languages)), []),\n\t}),\n\t(data) => { /* ... */ },\n);\n```\n\n```svelte\n<form {...survey}>\n\t<h2>Which operating system do you use?</h2>\n\n\t{#each operatingSystems as os}\n\t\t<label>\n\t\t\t<input {...survey.fields.operatingSystem.as('radio', os)}>\n\t\t\t{os}\n\t\t</label>\n\t{/each}\n\n\t<h2>Which languages do you write code in?</h2>\n\n\t{#each languages as language}\n\t\t<label>\n\t\t\t<input {...survey.fields.languages.as('checkbox', language)}>\n\t\t\t{language}\n\t\t</label>\n\t{/each}\n\n\t<button>submit</button>\n</form>\n```\n\nAlternatively, you could use `select` and `select multiple`:\n\n```svelte\n<form {...survey}>\n\t<h2>Which operating system do you use?</h2>\n\n\t<select {...survey.fields.operatingSystem.as('select')}>\n\t\t{#each operatingSystems as os}\n\t\t\t<option>{os}</option>\n\t\t{/each}\n\t</select>\n\n\t<h2>Which languages do you write code in?</h2>\n\n\t<select {...survey.fields.languages.as('select multiple')}>\n\t\t{#each languages as language}\n\t\t\t<option>{language}</option>\n\t\t{/each}\n\t</select>\n\n\t<button>submit</button>\n</form>\n```\n\n\n### Programmatic validation\n\nIn addition to declarative schema validation, you can programmatically mark fields as invalid inside the form handler using the `invalid` helper from `@sveltejs/kit`. This is useful for cases where you can't know if something is valid until you try to perform some action.\n\n- It throws just like `redirect` or `error`\n- It accepts multiple arguments that can be strings (for issues relating to the form as a whole — these will only show up in `fields.allIssues()`) or standard-schema-compliant issues (for those relating to a specific field). Use the `issue` parameter for type-safe creation of such issues:\n\n```js\n/// file: src/routes/shop/data.remote.js\nimport * as v from 'valibot';\nimport { invalid } from '@sveltejs/kit';\nimport { form } from '$app/server';\nimport * as db from '$lib/server/database';\n\nexport const buyHotcakes = form(\n\tv.object({\n\t\tqty: v.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(1, 'you must buy at least one hotcake')\n\t\t)\n\t}),\n\tasync (data, issue) => {\n\t\ttry {\n\t\t\tawait db.buy(data.qty);\n\t\t} catch (e) {\n\t\t\tif (e.code === 'OUT_OF_STOCK') {\n\t\t\t\tinvalid(\n\t\t\t\t\tissue.qty(`we don't have enough hotcakes`)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n);\n```\n\n### Validation\n\nIf the submitted data doesn't pass the schema, the callback will not run. Instead, each invalid field's `issues()` method will return an array of `{ message: string }` objects, and the `aria-invalid` attribute (returned from `as(...)`) will be set to `true`:\n\n```svelte\n<form {...createPost}>\n\t<label>\n\t\t<h2>Title</h2>\n\n{#each createPost.fields.title.issues() as issue}\n\t\t\t<p class=\"issue\">{issue.message}</p>\n\t\t{/each}\n\n\t\t<input {...createPost.fields.title.as('text')} />\n\t</label>\n\n\t<label>\n\t\t<h2>Write your post</h2>\n\n{#each createPost.fields.content.issues() as issue}\n\t\t\t<p class=\"issue\">{issue.message}</p>\n\t\t{/each}\n\n\t\t<textarea {...createPost.fields.content.as('text')}></textarea>\n\t</label>\n\n\t<button>Publish!</button>\n</form>\n```\n\nYou don't need to wait until the form is submitted to validate the data — you can call `validate()` programmatically, for example in an `oninput` callback (which will validate the data on every keystroke) or an `onchange` callback:\n\n```svelte\n<form {...createPost} oninput={() => createPost.validate()}>\n\t<!-- -->\n</form>\n```\n\nBy default, issues will be ignored if they belong to form controls that haven't yet been interacted with. To validate _all_ inputs, call `validate({ includeUntouched: true })`.\n\nFor client-side validation, you can specify a _preflight_ schema which will populate `issues()` and prevent data being sent to the server if the data doesn't validate:\n\n```svelte\n<script>\n\timport * as v from 'valibot';\n\timport { createPost } from '../data.remote';\n\n\tconst schema = v.object({\n\t\ttitle: v.pipe(v.string(), v.nonEmpty()),\n\t\tcontent: v.pipe(v.string(), v.nonEmpty())\n\t});\n</script>\n\n<h1>Create a new post</h1>\n\n<form {...createPost.preflight(schema)}>\n\t<!-- -->\n</form>\n```\n\n\nTo get a list of _all_ issues, rather than just those belonging to a single field, you can use the `fields.allIssues()` method:\n\n```svelte\n{#each createPost.fields.allIssues() as issue}\n\t<p>{issue.message}</p>\n{/each}\n```\n\n### Getting/setting inputs\n\nEach field has a `value()` method that reflects its current value. As the user interacts with the form, it is automatically updated:\n\n```svelte\n<form {...createPost}>\n\t<!-- -->\n</form>\n\n<div class=\"preview\">\n\t<h2>{createPost.fields.title.value()}</h2>\n\t<div>{@html render(createPost.fields.content.value())}</div>\n</div>\n```\n\nAlternatively, `createPost.fields.value()` would return a `{ title, content }` object.\n\nYou can update a field (or a collection of fields) via the `set(...)` method:\n\n```svelte\n<script>\n\timport { createPost } from '../data.remote';\n\n\t// this...\n\tcreatePost.fields.set({\n\t\ttitle: 'My new blog post',\n\t\tcontent: 'Lorem ipsum dolor sit amet...'\n\t});\n\n\t// ...is equivalent to this:\n\tcreatePost.fields.title.set('My new blog post');\n\tcreatePost.fields.content.set('Lorem ipsum dolor sit amet');\n</script>\n```\n\n### Handling sensitive data\n\nIn the case of a non-progressively-enhanced form submission (i.e. where JavaScript is unavailable, for whatever reason) `value()` is also populated if the submitted data is invalid, so that the user does not need to fill the entire form out from scratch.\n\nYou can prevent sensitive data (such as passwords and credit card numbers) from being sent back to the user by using a name with a leading underscore:\n\n```svelte\n<form {...register}>\n\t<label>\n\t\tUsername\n\t\t<input {...register.fields.username.as('text')} />\n\t</label>\n\n\t<label>\n\t\tPassword\n\t\t<input{...register.fields._password.as('password')}/>\n\t</label>\n\n\t<button>Sign up!</button>\n</form>\n```\n\nIn this example, if the data does not validate, only the first `<input>` will be populated when the page reloads.\n\n### Single-flight mutations\n\nBy default, all queries used on the page (along with any `load` functions) are automatically refreshed following a successful form submission. This ensures that everything is up-to-date, but it's also inefficient: many queries will be unchanged, and it requires a second trip to the server to get the updated data.\n\nInstead, we can specify which queries should be refreshed in response to a particular form submission. This is called a _single-flight mutation_, and there are two ways to achieve it. The first is to refresh the query on the server, inside the form handler:\n\n```js\nimport * as v from 'valibot';\nimport { error, redirect } from '@sveltejs/kit';\nimport { query, form } from '$app/server';\nconst slug = '';\nconst post = { id: '' };\n/** @type {any} */\nconst externalApi = '';\n//cut\nexport const getPosts = query(async () => { /* ... */ });\n\nexport const getPost = query(v.string(), async (slug) => { /* ... */ });\n\nexport const createPost = form(\n\tv.object({/* ... */}),\n\tasync (data) => {\n\t\t// form logic goes here...\n\n\t\t// Refresh `getPosts()` on the server, and send\n\t\t// the data back with the result of `createPost`\n\t\tawait getPosts().refresh();\n\n\t\t// Redirect to the newly created page\n\t\tredirect(303, `/blog/${slug}`);\n\t}\n);\n\nexport const updatePost = form(\n\tv.object({/* ... */}),\n\tasync (data) => {\n\t\t// form logic goes here...\n\t\tconst result = externalApi.update(post);\n\n\t\t// The API already gives us the updated post,\n\t\t// no need to refresh it, we can set it directly\n\t\tawait getPost(post.id).set(result);\n\t}\n);\n```\n\nThe second is to drive the single-flight mutation from the client, which we'll see in the section on [`enhance`](#form-enhance).\n\n### Returns and redirects\n\nThe example above uses [`redirect(...)`](@sveltejs-kit#redirect), which sends the user to the newly created page. Alternatively, the callback could return data, in which case it would be available as `createPost.result`:\n\n```ts\n/// file: src/routes/blog/data.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n\ndeclare module '$lib/server/auth' {\n\tinterface User {\n\t\tname: string;\n\t}\n\n\t/**\n\t * Gets a user's info from their cookies, using `getRequestEvent`\n\t */\n\texport function getUser(): Promise<User | null>;\n}\n// @filename: index.js\nimport * as v from 'valibot';\nimport { error, redirect } from '@sveltejs/kit';\nimport { query, form } from '$app/server';\nimport * as db from '$lib/server/database';\nimport * as auth from '$lib/server/auth';\n\nexport const getPosts = query(async () => { /* ... */ });\n\nexport const getPost = query(v.string(), async (slug) => { /* ... */ });\n\n//cut\nexport const createPost = form(\n\tv.object({/* ... */}),\n\tasync (data) => {\n\t\t// ...\n\n\t\treturn { success: true };\n\t}\n);\n```\n\n```svelte\n<!file: src/routes/blog/new/+page.svelte>\n<script>\n\timport { createPost } from '../data.remote';\n</script>\n\n<h1>Create a new post</h1>\n\n<form {...createPost}>\n\t<!-- -->\n</form>\n\n{#if createPost.result?.success}\n\t<p>Successfully published!</p>\n{/if}\n```\n\nThis value is _ephemeral_ — it will vanish if you resubmit, navigate away, or reload the page.\n\n\nIf an error occurs during submission, the nearest `+error.svelte` page will be rendered.\n\n### enhance\n\nWe can customize what happens when the form is submitted with the `enhance` method:\n\n```svelte\n<!file: src/routes/blog/new/+page.svelte>\n<script>\n\timport { createPost } from '../data.remote';\n\timport { showToast } from '$lib/toast';\n</script>\n\n<h1>Create a new post</h1>\n\n<form {...createPost.enhance(async ({ form, data, submit }) => {\n\ttry {\n\t\tawait submit();\n\t\tform.reset();\n\n\t\tshowToast('Successfully published!');\n\t} catch (error) {\n\t\tshowToast('Oh no! Something went wrong');\n\t}\n})}>\n\t<!-- -->\n</form>\n```\n\n> When using `enhance`, the `<form>` is not automatically reset — you must call `form.reset()` if you want to clear the inputs.\n\nThe callback receives the `form` element, the `data` it contains, and a `submit` function.\n\nTo enable client-driven [single-flight mutations](#form-Single-flight-mutations), use `submit().updates(...)`. For example, if the `getPosts()` query was used on this page, we could refresh it like so:\n\n```ts\nimport type { RemoteQuery, RemoteQueryOverride } from '@sveltejs/kit';\ninterface Post {}\ndeclare function submit(): Promise<any> & {\n\tupdates(...queries: Array<RemoteQuery<any> | RemoteQueryOverride>): Promise<any>;\n}\n\ndeclare function getPosts(): RemoteQuery<Post[]>;\n//cut\nawait submit().updates(getPosts());\n```\n\nWe can also _override_ the current data while the submission is ongoing:\n\n```ts\nimport type { RemoteQuery, RemoteQueryOverride } from '@sveltejs/kit';\ninterface Post {}\ndeclare function submit(): Promise<any> & {\n\tupdates(...queries: Array<RemoteQuery<any> | RemoteQueryOverride>): Promise<any>;\n}\n\ndeclare function getPosts(): RemoteQuery<Post[]>;\ndeclare const newPost: Post;\n//cut\nawait submit().updates(\n\tgetPosts().withOverride((posts) => [newPost, ...posts])\n);\n```\n\nThe override will be applied immediately, and released when the submission completes (or fails).\n\n### Multiple instances of a form\n\nSome forms may be repeated as part of a list. In this case you can create separate instances of a form function via `for(id)` to achieve isolation.\n\n```svelte\n<!file: src/routes/todos/+page.svelte>\n<script>\n\timport { getTodos, modifyTodo } from '../data.remote';\n</script>\n\n<h1>Todos</h1>\n\n{#each await getTodos() as todo}\n\t{@const modify = modifyTodo.for(todo.id)}\n\t<form {...modify}>\n\t\t<!-- -->\n\t\t<button disabled={!!modify.pending}>save changes</button>\n\t</form>\n{/each}\n```\n\n### Multiple submit buttons\n\nIt's possible for a `<form>` to have multiple submit buttons. For example, you might have a single form that allows you to log in or register depending on which button was clicked.\n\nTo accomplish this, add a field to your schema for the button value, and use `as('submit', value)` to bind it:\n\n```svelte\n<!file: src/routes/login/+page.svelte>\n<script>\n\timport { loginOrRegister } from '$lib/auth';\n</script>\n\n<form {...loginOrRegister}>\n\t<label>\n\t\tYour username\n\t\t<input {...loginOrRegister.fields.username.as('text')} />\n\t</label>\n\n\t<label>\n\t\tYour password\n\t\t<input {...loginOrRegister.fields._password.as('password')} />\n\t</label>\n\n\t<button {...loginOrRegister.fields.action.as('submit', 'login')}>login</button>\n\t<button {...loginOrRegister.fields.action.as('submit', 'register')}>register</button>\n</form>\n```\n\nIn your form handler, you can check which button was clicked:\n\n```js\n/// file: $lib/auth.js\nimport * as v from 'valibot';\nimport { form } from '$app/server';\n\nexport const loginOrRegister = form(\n\tv.object({\n\t\tusername: v.string(),\n\t\t_password: v.string(),\n\t\taction: v.picklist(['login', 'register'])\n\t}),\n\tasync ({ username, _password, action }) => {\n\t\tif (action === 'login') {\n\t\t\t// handle login\n\t\t} else {\n\t\t\t// handle registration\n\t\t}\n\t}\n);\n```\n\n## command\n\nThe `command` function, like `form`, allows you to write data to the server. Unlike `form`, it's not specific to an element and can be called from anywhere.\n\n\nAs with `query` and `form`, if the function accepts an argument, it should be [validated](#query-Query-arguments) by passing a [Standard Schema](https://standardschema.dev) as the first argument to `command`.\n\n```ts\n/// file: likes.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n// @filename: index.js\n//cut\nimport * as v from 'valibot';\nimport { query, command } from '$app/server';\nimport * as db from '$lib/server/database';\n\nexport const getLikes = query(v.string(), async (id) => {\n\tconst [row] = await db.sql`\n\t\tSELECT likes\n\t\tFROM item\n\t\tWHERE id = ${id}\n\t`;\n\n\treturn row.likes;\n});\n\nexport const addLike = command(v.string(), async (id) => {\n\tawait db.sql`\n\t\tUPDATE item\n\t\tSET likes = likes + 1\n\t\tWHERE id = ${id}\n\t`;\n});\n```\n\nNow simply call `addLike`, from (for example) an event handler:\n\n```svelte\n<!file: +page.svelte>\n<script>\n\timport { getLikes, addLike } from './likes.remote';\n\timport { showToast } from '$lib/toast';\n\n\tlet { item } = $props();\n</script>\n\n<button\n\tonclick={async () => {\n\t\ttry {\n\t\t\tawait addLike(item.id);\n\t\t} catch (error) {\n\t\t\tshowToast('Something went wrong!');\n\t\t}\n\t}}\n>\n\tadd like\n</button>\n\n<p>likes: {await getLikes(item.id)}</p>\n```\n\n\n### Updating queries\n\nTo update `getLikes(item.id)`, or any other query, we need to tell SvelteKit _which_ queries need to be refreshed (unlike `form`, which by default invalidates everything, to approximate the behaviour of a native form submission).\n\nWe either do that inside the command itself...\n\n```js\n/// file: likes.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n// @filename: index.js\n//cut\nimport * as v from 'valibot';\nimport { query, command } from '$app/server';\nimport * as db from '$lib/server/database';\n//cut\nexport const getLikes = query(v.string(), async (id) => { /* ... */ });\n\nexport const addLike = command(v.string(), async (id) => {\n\tawait db.sql`\n\t\tUPDATE item\n\t\tSET likes = likes + 1\n\t\tWHERE id = ${id}\n\t`;\n\n\tgetLikes(id).refresh();\n\t// Just like within form functions you can also do\n\t// getLikes(id).set(...)\n\t// in case you have the result already\n});\n```\n\n...or when we call it:\n\n```ts\nimport { RemoteCommand, RemoteQueryFunction } from '@sveltejs/kit';\n\ninterface Item { id: string }\n\ndeclare const addLike: RemoteCommand<string, void>;\ndeclare const getLikes: RemoteQueryFunction<string, number>;\ndeclare function showToast(message: string): void;\ndeclare const item: Item;\n//cut\ntry {\n\tawait addLike(item.id).updates(getLikes(item.id));\n} catch (error) {\n\tshowToast('Something went wrong!');\n}\n```\n\nAs before, we can use `withOverride` for optimistic updates:\n\n```ts\nimport { RemoteCommand, RemoteQueryFunction } from '@sveltejs/kit';\n\ninterface Item { id: string }\n\ndeclare const addLike: RemoteCommand<string, void>;\ndeclare const getLikes: RemoteQueryFunction<string, number>;\ndeclare function showToast(message: string): void;\ndeclare const item: Item;\n//cut\ntry {\n\tawait addLike(item.id).updates(\n\t\tgetLikes(item.id).withOverride((n) => n + 1)\n\t);\n} catch (error) {\n\tshowToast('Something went wrong!');\n}\n```\n\n## prerender\n\nThe `prerender` function is similar to `query`, except that it will be invoked at build time to prerender the result. Use this for data that changes at most once per redeployment.\n\n```js\n/// file: src/routes/blog/data.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n// @filename: index.js\n//cut\nimport { prerender } from '$app/server';\nimport * as db from '$lib/server/database';\n\nexport const getPosts = prerender(async () => {\n\tconst posts = await db.sql`\n\t\tSELECT title, slug\n\t\tFROM post\n\t\tORDER BY published_at\n\t\tDESC\n\t`;\n\n\treturn posts;\n});\n```\n\nYou can use `prerender` functions on pages that are otherwise dynamic, allowing for partial prerendering of your data. This results in very fast navigation, since prerendered data can live on a CDN along with your other static assets.\n\nIn the browser, prerendered data is saved using the [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache) API. This cache survives page reloads, and will be cleared when the user first visits a new deployment of your app.\n\n\n### Prerender arguments\n\nAs with queries, prerender functions can accept an argument, which should be [validated](#query-Query-arguments) with a [Standard Schema](https://standardschema.dev/):\n\n```js\n/// file: src/routes/blog/data.remote.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function sql(strings: TemplateStringsArray, ...values: any[]): Promise<any[]>;\n}\n// @filename: index.js\n//cut\nimport * as v from 'valibot';\nimport { error } from '@sveltejs/kit';\nimport { prerender } from '$app/server';\nimport * as db from '$lib/server/database';\n\nexport const getPosts = prerender(async () => { /* ... */ });\n\nexport const getPost = prerender(v.string(), async (slug) => {\n\tconst [post] = await db.sql`\n\t\tSELECT * FROM post\n\t\tWHERE slug = ${slug}\n\t`;\n\n\tif (!post) error(404, 'Not found');\n\treturn post;\n});\n```\n\nAny calls to `getPost(...)` found by SvelteKit's crawler while [prerendering pages](page-options#prerender) will be saved automatically, but you can also specify which values it should be called with using the `inputs` option:\n\n```js\n/// file: src/routes/blog/data.remote.js\nimport * as v from 'valibot';\nimport { prerender } from '$app/server';\n//cut\n\nexport const getPost = prerender(\n\tv.string(),\n\tasync (slug) => { /* ... */ },\n\t{\n\t\tinputs: () => [\n\t\t\t'first-post',\n\t\t\t'second-post',\n\t\t\t'third-post'\n\t\t]\n\t}\n);\n```\n\nBy default, prerender functions are excluded from your server bundle, which means that you cannot call them with any arguments that were _not_ prerendered. You can set `dynamic: true` to change this behaviour:\n\n```js\n/// file: src/routes/blog/data.remote.js\nimport * as v from 'valibot';\nimport { prerender } from '$app/server';\n//cut\n\nexport const getPost = prerender(\n\tv.string(),\n\tasync (slug) => { /* ... */ },\n\t{\n\t\tdynamic: true,\n\t\tinputs: () => [\n\t\t\t'first-post',\n\t\t\t'second-post',\n\t\t\t'third-post'\n\t\t]\n\t}\n);\n```\n\n## Handling validation errors\n\nAs long as _you're_ not passing invalid data to your remote functions, there are only two reasons why the argument passed to a `command`, `query` or `prerender` function would fail validation:\n\n- the function signature changed between deployments, and some users are currently on an older version of your app\n- someone is trying to attack your site by poking your exposed endpoints with bad data\n\nIn the second case, we don't want to give the attacker any help, so SvelteKit will generate a generic [400 Bad Request](https://http.dog/400) response. You can control the message by implementing the [`handleValidationError`](hooks#Server-hooks-handleValidationError) server hook, which, like [`handleError`](hooks#Shared-hooks-handleError), must return an [`App.Error`](errors#Type-safety) (which defaults to `{ message: string }`):\n\n```js\n/// file: src/hooks.server.ts\n/** @type {import('@sveltejs/kit').HandleValidationError} */\nexport function handleValidationError({ event, issues }) {\n\treturn {\n\t\tmessage: 'Nice try, hacker!'\n\t};\n}\n```\n\nIf you know what you're doing and want to opt out of validation, you can pass the string `'unchecked'` in place of a schema:\n\n```ts\n/// file: data.remote.ts\nimport { query } from '$app/server';\n\nexport const getStuff = query('unchecked', async ({ id }: { id: string }) => {\n\t// the shape might not actually be what TypeScript thinks\n\t// since bad actors might call this function with other arguments\n});\n```\n\n## Using `getRequestEvent`\n\nInside `query`, `form` and `command` you can use [`getRequestEvent`]($app-server#getRequestEvent) to get the current [`RequestEvent`](@sveltejs-kit#RequestEvent) object. This makes it easy to build abstractions for interacting with cookies, for example:\n\n```ts\n/// file: user.remote.ts\nimport { getRequestEvent, query } from '$app/server';\nimport { findUser } from '$lib/server/database';\n\nexport const getProfile = query(async () => {\n\tconst user = await getUser();\n\n\treturn {\n\t\tname: user.name,\n\t\tavatar: user.avatar\n\t};\n});\n\n// this query could be called from multiple places, but\n// the function will only run once per request\nconst getUser = query(async () => {\n\tconst { cookies } = getRequestEvent();\n\n\treturn await findUser(cookies.get('session_id'));\n});\n```\n\nNote that some properties of `RequestEvent` are different inside remote functions:\n\n- you cannot set headers (other than writing cookies, and then only inside `form` and `command` functions)\n- `route`, `params` and `url` relate to the page the remote function was called from, _not_ the URL of the endpoint SvelteKit creates for the remote function. Queries are not re-run when the user navigates (unless the argument to the query changes as a result of navigation), and so you should be mindful of how you use these values. In particular, never use them to determine whether or not a user is authorized to access certain data.\n\n## Redirects\n\nInside `query`, `form` and `prerender` functions it is possible to use the [`redirect(...)`](@sveltejs-kit#redirect) function. It is *not* possible inside `command` functions, as you should avoid redirecting here. (If you absolutely have to, you can return a `{ redirect: location }` object and deal with it in the client.)","size_bytes":34814,"metadata":{"title":"Remote functions"},"created_at":"2025-07-31T23:52:36.156Z","updated_at":"2026-02-14T01:33:24.852Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/10-building-your-app.md","title":"Building your app","filename":"10-building-your-app.md","content":"Building a SvelteKit app happens in two stages, which both happen when you run `vite build` (usually via `npm run build`).\n\nFirstly, Vite creates an optimized production build of your server code, your browser code, and your service worker (if you have one). [Prerendering](page-options#prerender) is executed at this stage, if appropriate.\n\nSecondly, an _adapter_ takes this production build and tunes it for your target environment — more on this on the following pages.\n\n## During the build\n\nSvelteKit will load your `+page/layout(.server).js` files (and all files they import) for analysis during the build. Any code that should _not_ be executed at this stage must check that `building` from [`$app/environment`]($app-environment) is `false`:\n\n```js\nimport { building } from '$app/environment';\nimport { initialiseDatabase } from '$lib/server/database';\n\nif (!building) {\n\tinitialiseDatabase();\n}\n\nexport function load() {\n\t// ...\n}\n```\n\n## Preview your app\n\nAfter building, you can view your production build locally with `vite preview` (via `npm run preview`). Note that this will run the app in Node, and so is not a perfect reproduction of your deployed app — adapter-specific adjustments like the [`platform` object](adapters#Platform-specific-context) do not apply to previews.","size_bytes":1327,"metadata":{"title":"Building your app"},"created_at":"2025-07-18T15:47:38.776Z","updated_at":"2026-02-14T01:33:24.848Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/20-adapters.md","title":"Adapters","filename":"20-adapters.md","content":"Before you can deploy your SvelteKit app, you need to _adapt_ it for your deployment target. Adapters are small plugins that take the built app as input and generate output for deployment.\n\nOfficial adapters exist for a variety of platforms — these are documented on the following pages:\n\n- [`@sveltejs/adapter-cloudflare`](adapter-cloudflare) for Cloudflare Workers and Cloudflare Pages\n- [`@sveltejs/adapter-netlify`](adapter-netlify) for Netlify\n- [`@sveltejs/adapter-node`](adapter-node) for Node servers\n- [`@sveltejs/adapter-static`](adapter-static) for static site generation (SSG)\n- [`@sveltejs/adapter-vercel`](adapter-vercel) for Vercel\n\nAdditional [community-provided adapters](/packages#sveltekit-adapters) exist for other platforms.\n\n## Using adapters\n\nYour adapter is specified in `svelte.config.js`:\n\n```js\n/// file: svelte.config.js\n// @filename: ambient.d.ts\ndeclare module 'svelte-adapter-foo' {\n\tconst adapter: (opts: any) => import('@sveltejs/kit').Adapter;\n\texport default adapter;\n}\n\n// @filename: index.js\n//cut\nimport adapter from 'svelte-adapter-foo';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\t// adapter options go here\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\n## Platform-specific context\n\nSome adapters may have access to additional information about the request. For example, Cloudflare Workers can access an `env` object containing KV namespaces etc. This can be passed to the `RequestEvent` used in [hooks](hooks) and [server routes](routing#server) as the `platform` property — consult each adapter's documentation to learn more.","size_bytes":1644,"metadata":{"title":"Adapters"},"created_at":"2025-07-18T15:47:38.778Z","updated_at":"2025-10-04T02:00:04.349Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md","title":"Zero-config deployments","filename":"30-adapter-auto.md","content":"When you create a new SvelteKit project with `npx sv create`, it installs [`adapter-auto`](https://github.com/sveltejs/kit/tree/main/packages/adapter-auto) by default. This adapter automatically installs and uses the correct adapter for supported environments when you deploy:\n\n- [`@sveltejs/adapter-cloudflare`](adapter-cloudflare) for [Cloudflare Pages](https://developers.cloudflare.com/pages/)\n- [`@sveltejs/adapter-netlify`](adapter-netlify) for [Netlify](https://netlify.com/)\n- [`@sveltejs/adapter-vercel`](adapter-vercel) for [Vercel](https://vercel.com/)\n- [`svelte-adapter-azure-swa`](https://github.com/geoffrich/svelte-adapter-azure-swa) for [Azure Static Web Apps](https://docs.microsoft.com/en-us/azure/static-web-apps/)\n- [`svelte-kit-sst`](https://github.com/sst/v2/tree/master/packages/svelte-kit-sst) for [AWS via SST](https://sst.dev/docs/start/aws/svelte)\n- [`@sveltejs/adapter-node`](adapter-node) for [Google Cloud Run](https://cloud.google.com/run)\n\nIt's recommended to install the appropriate adapter to your `devDependencies` once you've settled on a target environment, since this will add the adapter to your lockfile and slightly improve install times on CI.\n\n## Environment-specific configuration\n\nTo add configuration options, such as `{ edge: true }` in [`adapter-vercel`](adapter-vercel) and [`adapter-netlify`](adapter-netlify), you must install the underlying adapter — `adapter-auto` does not take any options.\n\n## Adding community adapters\n\nYou can add zero-config support for additional adapters by editing [adapters.js](https://github.com/sveltejs/kit/blob/main/packages/adapter-auto/adapters.js) and opening a pull request.","size_bytes":1705,"metadata":{"title":"Zero-config deployments"},"created_at":"2025-07-18T15:47:38.779Z","updated_at":"2025-07-18T15:47:40.041Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/40-adapter-node.md","title":"Node servers","filename":"40-adapter-node.md","content":"To generate a standalone Node server, use [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node).\n\n## Usage\n\nInstall with `npm i -D @sveltejs/adapter-node`, then add the adapter to your `svelte.config.js`:\n\n```js\n// @errors: 2307\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-node';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter()\n\t}\n};\n\nexport default config;\n```\n\n## Deploying\n\nFirst, build your app with `npm run build`. This will create the production server in the output directory specified in the adapter options, defaulting to `build`.\n\nYou will need the output directory, the project's `package.json`, and the production dependencies in `node_modules` to run the application. Production dependencies can be generated by copying the `package.json` and `package-lock.json` and then running `npm ci --omit dev` (you can skip this step if your app doesn't have any dependencies). You can then start your app with this command:\n\n```sh\nnode build\n```\n\nDevelopment dependencies will be bundled into your app using [Rollup](https://rollupjs.org). To control whether a given package is bundled or externalised, place it in `devDependencies` or `dependencies` respectively in your `package.json`.\n\n### Compressing responses\n\nYou will typically want to compress responses coming from the server. If you're already deploying your server behind a reverse proxy for SSL or load balancing, it typically results in better performance to also handle compression at that layer since Node.js is single-threaded.\n\nHowever, if you're building a [custom server](#Custom-server) and do want to add a compression middleware there, note that we would recommend using [`@polka/compression`](https://www.npmjs.com/package/@polka/compression) since SvelteKit streams responses and the more popular `compression` package does not support streaming and may cause errors when used.\n\n## Environment variables\n\nIn `dev` and `preview`, SvelteKit will read environment variables from your `.env` file (or `.env.local`, or `.env.[mode]`, [as determined by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files).)\n\nIn production, `.env` files are _not_ automatically loaded. To do so, install `dotenv` in your project...\n\n```sh\nnpm install dotenv\n```\n\n...and invoke it before running the built app:\n\n```sh\nnode-r dotenv/configbuild\n```\n\nIf you use Node.js v20.6+, you can use the [`--env-file`](https://nodejs.org/en/learn/command-line/how-to-read-environment-variables-from-nodejs) flag instead:\n\n```sh\nnode--env-file=.envbuild\n```\n\n### `PORT`, `HOST` and `SOCKET_PATH`\n\nBy default, the server will accept connections on `0.0.0.0` using port 3000. These can be customised with the `PORT` and `HOST` environment variables:\n\n```sh\nHOST=127.0.0.1 PORT=4000 node build\n```\n\nAlternatively, the server can be configured to accept connections on a specified socket path. When this is done using the `SOCKET_PATH` environment variable, the `HOST` and `PORT` environment variables will be disregarded.\n\n```sh\nSOCKET_PATH=/tmp/socket node build\n```\n\n### `ORIGIN`, `PROTOCOL_HEADER`, `HOST_HEADER`, and `PORT_HEADER`\n\nHTTP doesn't give SvelteKit a reliable way to know the URL that is currently being requested. The simplest way to tell SvelteKit where the app is being served is to set the `ORIGIN` environment variable:\n\n```sh\nORIGIN=https://my.site node build\n\n# or e.g. for local previewing and testing\nORIGIN=http://localhost:3000 node build\n```\n\nWith this, a request for the `/stuff` pathname will correctly resolve to `https://my.site/stuff`. Alternatively, you can specify headers that tell SvelteKit about the request protocol and host, from which it can construct the origin URL:\n\n```sh\nPROTOCOL_HEADER=x-forwarded-proto HOST_HEADER=x-forwarded-host node build\n```\n\n>\n> If you're hosting your proxy on a non-standard port and your reverse proxy supports `x-forwarded-port`, you can also set `PORT_HEADER=x-forwarded-port`.\n\nIf `adapter-node` can't correctly determine the URL of your deployment, you may experience this error when using [form actions](form-actions):\n\n\n### `ADDRESS_HEADER` and `XFF_DEPTH`\n\nThe [`RequestEvent`](@sveltejs-kit#RequestEvent) object passed to hooks and endpoints includes an `event.getClientAddress()` function that returns the client's IP address. By default this is the connecting `remoteAddress`. If your server is behind one or more proxies (such as a load balancer), this value will contain the innermost proxy's IP address rather than the client's, so we need to specify an `ADDRESS_HEADER` to read the address from:\n\n```sh\nADDRESS_HEADER=True-Client-IP node build\n```\n\n\nIf the `ADDRESS_HEADER` is `X-Forwarded-For`, the header value will contain a comma-separated list of IP addresses. The `XFF_DEPTH` environment variable should specify how many trusted proxies sit in front of your server. E.g. if there are three trusted proxies, proxy 3 will forward the addresses of the original connection and the first two proxies:\n\n```\n<client address>, <proxy 1 address>, <proxy 2 address>\n```\n\nSome guides will tell you to read the left-most address, but this leaves you [vulnerable to spoofing](https://adam-p.ca/blog/2022/03/x-forwarded-for/):\n\n```\n<spoofed address>, <client address>, <proxy 1 address>, <proxy 2 address>\n```\n\nWe instead read from the _right_, accounting for the number of trusted proxies. In this case, we would use `XFF_DEPTH=3`.\n\n\n### `BODY_SIZE_LIMIT`\n\nThe maximum request body size to accept in bytes including while streaming. The body size can also be specified with a unit suffix for kilobytes (`K`), megabytes (`M`), or gigabytes (`G`). For example, `512K` or `1M`. Defaults to 512kb. You can disable this option with a value of `Infinity` (0 in older versions of the adapter) and implement a custom check in [`handle`](hooks#Server-hooks-handle) if you need something more advanced.\n\n### `SHUTDOWN_TIMEOUT`\n\nThe number of seconds to wait before forcefully closing any remaining connections after receiving a `SIGTERM` or `SIGINT` signal. Defaults to `30`. Internally the adapter calls [`closeAllConnections`](https://nodejs.org/api/http.html#servercloseallconnections). See [Graceful shutdown](#Graceful-shutdown) for more details.\n\n### `IDLE_TIMEOUT`\n\nWhen using systemd socket activation, `IDLE_TIMEOUT` specifies the number of seconds after which the app is automatically put to sleep when receiving no requests. If not set, the app runs continuously. See [Socket activation](#Socket-activation) for more details.\n\n### `KEEP_ALIVE_TIMEOUT` and `HEADERS_TIMEOUT`\n\nThe number of seconds for [`keepAliveTimeout`](https://nodejs.org/api/http.html#serverkeepalivetimeout) and [`headersTimeout`](https://nodejs.org/api/http.html#serverheaderstimeout).\n\n## Options\n\nThe adapter can be configured with various options:\n\n```js\n// @errors: 2307\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-node';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\t// default options are shown\n\t\t\tout: 'build',\n\t\t\tprecompress: true,\n\t\t\tenvPrefix: ''\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\n### out\n\nThe directory to build the server to. It defaults to `build` — i.e. `node build` would start the server locally after it has been created.\n\n### precompress\n\nEnables precompressing using gzip and brotli for assets and prerendered pages. It defaults to `true`.\n\n### envPrefix\n\nIf you need to change the name of the environment variables used to configure the deployment (for example, to deconflict with environment variables you don't control), you can specify a prefix:\n\n```js\nenvPrefix: 'MY_CUSTOM_';\n```\n\n```sh\nMY_CUSTOM_HOST=127.0.0.1 \\\nMY_CUSTOM_PORT=4000 \\\nMY_CUSTOM_ORIGIN=https://my.site \\\nnode build\n```\n\n## Graceful shutdown\n\nBy default `adapter-node` gracefully shuts down the HTTP server when a `SIGTERM` or `SIGINT` signal is received. It will:\n\n1. reject new requests ([`server.close`](https://nodejs.org/api/http.html#serverclosecallback))\n2. wait for requests that have already been made but not received a response yet to finish and close connections once they become idle ([`server.closeIdleConnections`](https://nodejs.org/api/http.html#servercloseidleconnections))\n3. and finally, close any remaining connections that are still active after [`SHUTDOWN_TIMEOUT`](#Environment-variables-SHUTDOWN_TIMEOUT) seconds. ([`server.closeAllConnections`](https://nodejs.org/api/http.html#servercloseallconnections))\n\n\nYou can listen to the `sveltekit:shutdown` event which is emitted after the HTTP server has closed all connections. Unlike Node's `exit` event, the `sveltekit:shutdown` event supports asynchronous operations and is always emitted when all connections are closed even if the server has dangling work such as open database connections.\n\n```js\n// @errors: 2304\nprocess.on('sveltekit:shutdown', async (reason) => {\n  await jobs.stop();\n  await db.close();\n});\n```\n\nThe parameter `reason` has one of the following values:\n\n- `SIGINT` - shutdown was triggered by a `SIGINT` signal\n- `SIGTERM` - shutdown was triggered by a `SIGTERM` signal\n- `IDLE` - shutdown was triggered by [`IDLE_TIMEOUT`](#Environment-variables-IDLE_TIMEOUT)\n\n## Socket activation\n\nMost Linux operating systems today use a modern process manager called systemd to start the server and run and manage services. You can configure your server to allocate a socket and start and scale your app on demand. This is called [socket activation](https://0pointer.de/blog/projects/socket-activated-containers.html). In this case, the OS will pass two environment variables to your app — `LISTEN_PID` and `LISTEN_FDS`. The adapter will then listen on file descriptor 3 which refers to a systemd socket unit that you will have to create.\n\n\nTo take advantage of socket activation follow these steps.\n\n1. Run your app as a [systemd service](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html). It can either run directly on the host system or inside a container (using Docker or a systemd portable service for example). If you additionally pass an [`IDLE_TIMEOUT`](#Environment-variables-IDLE_TIMEOUT) environment variable to your app it will gracefully shutdown if there are no requests for `IDLE_TIMEOUT` seconds. systemd will automatically start your app again when new requests are coming in.\n\n```ini\n/// file: /etc/systemd/system/myapp.service\n[Service]\nEnvironment=NODE_ENV=production IDLE_TIMEOUT=60\nExecStart=/usr/bin/node /usr/bin/myapp/build\n```\n\n2. Create an accompanying [socket unit](https://www.freedesktop.org/software/systemd/man/latest/systemd.socket.html). The adapter only accepts a single socket.\n\n```ini\n/// file: /etc/systemd/system/myapp.socket\n[Socket]\nListenStream=3000\n\n[Install]\nWantedBy=sockets.target\n```\n\n3. Make sure systemd has recognised both units by running `sudo systemctl daemon-reload`. Then enable the socket on boot and start it immediately using `sudo systemctl enable --now myapp.socket`. The app will then automatically start once the first request is made to `localhost:3000`.\n\n## Custom server\n\nThe adapter creates two files in your build directory — `index.js` and `handler.js`. Running `index.js` — e.g. `node build`, if you use the default build directory — will start a server on the configured port.\n\nAlternatively, you can import the `handler.js` file, which exports a handler suitable for use with [Express](https://github.com/expressjs/express), [Connect](https://github.com/senchalabs/connect) or [Polka](https://github.com/lukeed/polka) (or even just the built-in [`http.createServer`](https://nodejs.org/dist/latest/docs/api/http.html#httpcreateserveroptions-requestlistener)) and set up your own server:\n\n```js\n// @errors: 2307 7006\n/// file: my-server.js\nimport { handler } from './build/handler.js';\nimport express from 'express';\n\nconst app = express();\n\n// add a route that lives separately from the SvelteKit app\napp.get('/healthcheck', (req, res) => {\n\tres.end('ok');\n});\n\n// let SvelteKit handle everything else, including serving prerendered pages and static assets\napp.use(handler);\n\napp.listen(3000, () => {\n\tconsole.log('listening on port 3000');\n});\n```","size_bytes":12234,"metadata":{"title":"Node servers"},"created_at":"2025-07-18T15:47:38.785Z","updated_at":"2026-01-10T14:00:07.321Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/50-adapter-static.md","title":"Static site generation","filename":"50-adapter-static.md","content":"To use SvelteKit as a static site generator (SSG), use [`adapter-static`](https://github.com/sveltejs/kit/tree/main/packages/adapter-static).\n\nThis will prerender your entire site as a collection of static files. If you'd like to prerender only some pages and dynamically server-render others, you will need to use a different adapter together with [the `prerender` option](page-options#prerender).\n\n## Usage\n\nInstall with `npm i -D @sveltejs/adapter-static`, then add the adapter to your `svelte.config.js`:\n\n```js\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-static';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\t// default options are shown. On some platforms\n\t\t\t// these options are set automatically — see below\n\t\t\tpages: 'build',\n\t\t\tassets: 'build',\n\t\t\tfallback: undefined,\n\t\t\tprecompress: false,\n\t\t\tstrict: true\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\n...and add the [`prerender`](page-options#prerender) option to your root layout:\n\n```js\n/// file: src/routes/+layout.js\n// If you're using a fallback (i.e. SPA mode) you don't need to prerender all\n// pages by setting this here, but should prerender as many as possible to\n// avoid large performance and SEO impacts\nexport const prerender = true;\n```\n\n\n\n## Zero-config support\n\nSome platforms have zero-config support (more to come in future):\n\n- [Vercel](https://vercel.com)\n\nOn these platforms, you should omit the adapter options so that `adapter-static` can provide the optimal configuration:\n\n```js\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-static';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({...})\n\t}\n};\n\nexport default config;\n```\n\n## Options\n\n### pages\n\nThe directory to write prerendered pages to. It defaults to `build`.\n\n### assets\n\nThe directory to write static assets (the contents of `static`, plus client-side JS and CSS generated by SvelteKit) to. Ordinarily this should be the same as `pages`, and it will default to whatever the value of `pages` is, but in rare circumstances you might need to output pages and assets to separate locations.\n\n### fallback\n\nTo create a [single page app (SPA)](single-page-apps) you must specify the name of the fallback page to be generated by SvelteKit, which is used as the entry point for URLs that have not been prerendered. This is commonly `200.html`, but can vary depending on your deployment platform. You should avoid `index.html` where possible to avoid conflicting with a prerendered homepage. \n\n> This option has large negative performance and SEO impacts. It is only recommended in certain circumstances such as wrapping the site in a mobile app. See the [single page apps](single-page-apps) documentation for more details and alternatives.\n\n### precompress\n\nIf `true`, precompresses files with brotli and gzip. This will generate `.br` and `.gz` files.\n\n### strict\n\nBy default, `adapter-static` checks that either all pages and endpoints (if any) of your app were prerendered, or you have the `fallback` option set. This check exists to prevent you from accidentally publishing an app where some parts of it are not accessible, because they are not contained in the final output. If you know this is ok (for example when a certain page only exists conditionally), you can set `strict` to `false` to turn off this check.\n\n## GitHub Pages\n\nWhen building for [GitHub Pages](https://docs.github.com/en/pages/getting-started-with-github-pages/about-github-pages), if your repo name is not equivalent to `your-username.github.io`, make sure to update [`config.kit.paths.base`](configuration#paths) to match your repo name. This is because the site will be served from `https://your-username.github.io/your-repo-name` rather than from the root.\n\nYou'll also want to generate a fallback `404.html` page to replace the default 404 page shown by GitHub Pages.\n\nA config for GitHub Pages might look like the following:\n\n```js\n// @errors: 2322\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-static';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\tfallback: '404.html'\n\t\t}),\n\t\tpaths: {\n\t\t\tbase: process.argv.includes('dev') ? '' : process.env.BASE_PATH\n\t\t}\n\t}\n};\n\nexport default config;\n```\n\nYou can use GitHub actions to automatically deploy your site to GitHub Pages when you make a change. Here's an example workflow:\n\n```yaml\n### file: .github/workflows/deploy.yml\nname: Deploy to GitHub Pages\n\non:\n  push:\n    branches: 'main'\n\njobs:\n  build_site:\n    runs-on: ubuntu-latest\n    steps:\n      name: Checkout\n        uses: actions/checkout@v4\n\n      # If you're using pnpm, add this step then change the commands and cache key below to use `pnpm`\n      # - name: Install pnpm\n      #   uses: pnpm/action-setup@v3\n      #   with:\n      #     version: 8\n\n      name: Install Node.js\n        uses: actions/setup-node@v4\n        with:\n          node-version: 20\n          cache: npm\n\n      name: Install dependencies\n        run: npm i\n\n      name: build\n        env:\n          BASE_PATH: '/${{ github.event.repository.name }}'\n        run: |\n          npm run build\n\n      name: Upload Artifacts\n        uses: actions/upload-pages-artifact@v3\n        with:\n          # this should match the `pages` option in your adapter-static options\n          path: 'build/'\n\n  deploy:\n    needs: build_site\n    runs-on: ubuntu-latest\n\n    permissions:\n      pages: write\n      id-token: write\n\n    environment:\n      name: github-pages\n      url: ${{ steps.deployment.outputs.page_url }}\n\n    steps:\n      name: Deploy\n        id: deployment\n        uses: actions/deploy-pages@v4\n```\n\nIf you're not using GitHub actions to deploy your site (for example, you're pushing the built site to its own repo), add an empty `.nojekyll` file in your `static` directory to prevent Jekyll from interfering.","size_bytes":5947,"metadata":{"title":"Static site generation"},"created_at":"2025-07-18T15:47:38.787Z","updated_at":"2026-02-14T01:33:24.849Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/55-single-page-apps.md","title":"Single-page apps","filename":"55-single-page-apps.md","content":"You can turn a SvelteKit app into a fully client-rendered single-page app (SPA) by specifying a _fallback page_. This page will be served for any URLs that can't be served by other means such as returning a prerendered page.\n\n>\n> You can avoid these drawbacks by [prerendering](#Prerendering-individual-pages) as many pages as possible when using SPA mode (especially your homepage). If you can prerender all pages, you can simply use [static site generation](adapter-static) rather than a SPA. Otherwise, you should strongly consider using an adapter which supports server side rendering. SvelteKit has officially supported adapters for various providers with generous free tiers.\n\n## Usage\n\nFirst, disable SSR for the pages you don't want to prerender. These pages will be served via the fallback page; for example, to serve all pages via the fallback by default, you can update the root layout as shown below. You should [opt back into prerendering individual pages and directories](#Prerendering-individual-pages) where possible.\n```js\n/// file: src/routes/+layout.js\nexport const ssr = false;\n```\n\nIf you don't have any server-side logic (i.e. `+page.server.js`, `+layout.server.js` or `+server.js` files) you can use [`adapter-static`](adapter-static) to create your SPA. Install `adapter-static` with `npm i -D @sveltejs/adapter-static` and add it to your `svelte.config.js` with the `fallback` option:\n\n```js\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-static';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\tfallback: '200.html' // may differ from host to host\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\nThe `fallback` page is an HTML page created by SvelteKit from your page template (e.g. `app.html`) that loads your app and navigates to the correct route. For example [Surge](https://surge.sh/help/adding-a-200-page-for-client-side-routing), a static web host, lets you add a `200.html` file that will handle any requests that don't correspond to static assets or prerendered pages.\n\nOn some hosts it may be something else entirely — consult your platform's documentation. We recommend avoiding `index.html` if possible as it may conflict with prerendering.\n\n\n## Prerendering individual pages\n\nIf you want certain pages to be prerendered, you can re-enable `ssr` alongside `prerender` for just those parts of your app:\n\n```js\n/// file: src/routes/my-prerendered-page/+page.js\nexport const prerender = true;\nexport const ssr = true;\n```\n\nYou won't need a Node server or server capable of running JavaScript to deploy this page. It will only server render your page while building your project for the purposes of outputting an `.html` page that can be served from any static web host.\n\n## Apache\n\nTo run an SPA on [Apache](https://httpd.apache.org/), you should add a `static/.htaccess` file to route requests to the fallback page:\n\n```\n<IfModule mod_rewrite.c>\n\tRewriteEngine On\n\tRewriteBase /\n\tRewriteRule ^200\\.html$ - [L]\n\tRewriteCond %{REQUEST_FILENAME} !-f\n\tRewriteCond %{REQUEST_FILENAME} !-d\n\tRewriteRule . /200.html [L]\n</IfModule>\n```","size_bytes":3159,"metadata":{"title":"Single-page apps"},"created_at":"2025-07-18T15:47:38.793Z","updated_at":"2025-11-03T02:00:03.527Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md","title":"Cloudflare","filename":"60-adapter-cloudflare.md","content":"To deploy to [Cloudflare Workers](https://workers.cloudflare.com/) or [Cloudflare Pages](https://pages.cloudflare.com/), use [`adapter-cloudflare`](https://github.com/sveltejs/kit/tree/main/packages/adapter-cloudflare).\n\nThis adapter will be installed by default when you use [`adapter-auto`](adapter-auto). If you plan on staying with Cloudflare, you can switch from [`adapter-auto`](adapter-auto) to using this adapter directly so that `event.platform` is emulated during local development, type declarations are automatically applied, and the ability to set Cloudflare-specific options is provided.\n\n## Comparisons\n\n- `adapter-cloudflare` – supports all SvelteKit features; builds for Cloudflare Workers Static Assets and Cloudflare Pages\n- `adapter-cloudflare-workers` – deprecated. Supports all SvelteKit features; builds for Cloudflare Workers Sites\n- `adapter-static` – only produces client-side static assets; compatible with Cloudflare Workers Static Assets and Cloudflare Pages\n\n## Usage\n\nInstall with `npm i -D @sveltejs/adapter-cloudflare`, then add the adapter to your `svelte.config.js`:\n\n```js\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-cloudflare';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\t// See below for an explanation of these options\n\t\t\tconfig: undefined,\n\t\t\tplatformProxy: {\n\t\t\t\tconfigPath: undefined,\n\t\t\t\tenvironment: undefined,\n\t\t\t\tpersist: undefined\n\t\t\t},\n\t\t\tfallback: 'plaintext',\n\t\t\troutes: {\n\t\t\t\tinclude: ['/*'],\n\t\t\t\texclude: ['<all>']\n\t\t\t}\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\n## Options\n\n### config\n\nPath to your [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/). If you would like to use a Wrangler configuration filename other than `wrangler.jsonc`, `wrangler.json`, or `wrangler.toml` you can specify it using this option.\n\n### platformProxy\n\nPreferences for the emulated `platform.env` local bindings. See the [getPlatformProxy](https://developers.cloudflare.com/workers/wrangler/api/#parameters-1) Wrangler API documentation for a full list of options.\n\n### fallback\n\nWhether to render a plaintext 404.html page or a rendered SPA fallback page for non-matching asset requests.\n\nFor Cloudflare Workers, the default behaviour is to return a null-body 404-status response for non-matching assets requests. However, if the [`assets.not_found_handling`](https://developers.cloudflare.com/workers/static-assets/routing/#2-not_found_handling) Wrangler configuration setting is set to `\"404-page\"`, this page will be served if a request fails to match an asset. If `assets.not_found_handling` is set to `\"single-page-application\"`, the adapter will render a SPA fallback `index.html` page regardless of the `fallback` option specified.\n\nFor Cloudflare Pages, this page will only be served when a request that matches an entry in `routes.exclude` fails to match an asset.\n\nMost of the time `plaintext` is sufficient, but if you are using `routes.exclude` to manually exclude a set of prerendered pages without exceeding the 100 route limit, you may wish to use `spa` instead to avoid showing an unstyled 404 page to users.\n\nSee Cloudflare Pages' [Not Found behaviour](https://developers.cloudflare.com/pages/configuration/serving-pages/#not-found-behavior) for more info.\n\n### routes\n\nOnly for Cloudflare Pages. Allows you to customise the [`_routes.json`](https://developers.cloudflare.com/pages/functions/routing/#create-a-_routesjson-file) file generated by `adapter-cloudflare`.\n\n- `include` defines routes that will invoke a function, and defaults to `['/*']`\n- `exclude` defines routes that will _not_ invoke a function — this is a faster and cheaper way to serve your app's static assets. This array can include the following special values:\n\t- `<build>` contains your app's build artifacts (the files generated by Vite)\n\t- `<files>` contains the contents of your `static` directory\n\t- `<redirects>` contains a list of pathnames from your [`_redirects` file](https://developers.cloudflare.com/pages/configuration/redirects/) at the root\n\t- `<prerendered>` contains a list of prerendered pages\n\t- `<all>` (the default) contains all of the above\n\nYou can have up to 100 `include` and `exclude` rules combined. Generally you can omit the `routes` options, but if (for example) your `<prerendered>` paths exceed that limit, you may find it helpful to manually create an `exclude` list that includes `'/articles/*'` instead of the auto-generated `['/articles/foo', '/articles/bar', '/articles/baz', ...]`.\n\n## Cloudflare Workers\n\n### Basic configuration\n\nWhen building for Cloudflare Workers, this adapter expects to find a [Wrangler configuration file](https://developers.cloudflare.com/workers/configuration/sites/configuration/) in the project root. It should look something like this:\n\n```jsonc\n/// file: wrangler.jsonc\n{\n\t\"name\": \"<any-name-you-want>\",\n\t\"main\": \".svelte-kit/cloudflare/_worker.js\",\n\t\"compatibility_flags\": [\"nodejs_als\"],\n\t\"compatibility_date\": \"<YYYY-MM-DD>\",\n\t\"assets\": {\n\t\t\"binding\": \"ASSETS\",\n\t\t\"directory\": \".svelte-kit/cloudflare\",\n\t}\n}\n```\n\n### Deployment\n\nYou can use the Wrangler CLI to deploy your application by running `npx wrangler deploy` or use the [Cloudflare Git integration](https://developers.cloudflare.com/workers/ci-cd/builds/) to enable automatic builds and deployments on push.\n\n## Cloudflare Pages\n\n### Deployment\n\nPlease follow the [Get Started Guide](https://developers.cloudflare.com/pages/get-started/) for Cloudflare Pages to begin.\n\nIf you're using the [Git integration](https://developers.cloudflare.com/pages/get-started/git-integration/), your build settings should look like this:\n\n- Framework preset – SvelteKit\n- Build command – `npm run build` or `vite build`\n- Build output directory – `.svelte-kit/cloudflare`\n\n\nOnce configured, go to the **Runtime** section of your project settings, and add the `nodejs_als` compability flag to enable the [Node.js AsyncLocalStorage](https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-asynclocalstorage). Alternatively, do this in your wrangler config using the `compatibility_flags` array.\n\n### Further reading\n\nYou may wish to refer to [Cloudflare's documentation for deploying a SvelteKit site on Cloudflare Pages](https://developers.cloudflare.com/pages/framework-guides/deploy-a-svelte-kit-site/).\n\n### Notes\n\nFunctions contained in the [`/functions` directory](https://developers.cloudflare.com/pages/functions/routing/) at the project's root will _not_ be included in the deployment. Instead, functions should be implemented as [server endpoints](routing#server) in your SvelteKit app, which is compiled to a [single `_worker.js` file](https://developers.cloudflare.com/pages/functions/advanced-mode/).\n\n## Runtime APIs\n\nThe [`env`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#parameters) object contains your project's [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/), which consist of KV/DO namespaces, etc. It is passed to SvelteKit via the `platform` property, along with [`ctx`](https://developers.cloudflare.com/workers/runtime-apis/context/), [`caches`](https://developers.cloudflare.com/workers/runtime-apis/cache/), and [`cf`](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties), meaning that you can access it in hooks and endpoints:\n\n```js\n// @filename: ambient.d.ts\nimport { DurableObjectNamespace } from '@cloudflare/workers-types';\n\ndeclare global {\n\tnamespace App {\n\t\tinterface Platform {\n\t\t\tenv: {\n\t\t\t\tYOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;\n\t\t\t};\n\t\t}\n\t}\n}\n// @filename: +server.js\n//cut\n// @errors: 2355 2322\n/// file: +server.js\n/** @type {import('./$types').RequestHandler} */\nexport async function POST({ request, platform }) {\n\tconst x = platform?.env.YOUR_DURABLE_OBJECT_NAMESPACE.idFromName('x');\n}\n```\n\n\nTo make these types available to your app, install [`@cloudflare/workers-types`](https://www.npmjs.com/package/@cloudflare/workers-types) and reference them in your `src/app.d.ts`:\n\n```ts\n/// file: src/app.d.ts\nimport { KVNamespace, DurableObjectNamespace } from '@cloudflare/workers-types';\n\ndeclare global {\n\tnamespace App {\n\t\tinterface Platform {\nenv: {\n\t\t\t\tYOUR_KV_NAMESPACE: KVNamespace;\n\t\t\t\tYOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;\n\t\t\t};\n\t\t}\n\t}\n}\n\nexport {};\n```\n\n### Testing locally\n\nCloudflare specific values in the `platform` property are emulated during dev and preview modes. Local [bindings](https://developers.cloudflare.com/workers/wrangler/configuration/#bindings) are created based on your [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/) and are used to populate `platform.env` during development and preview. Use the adapter config [`platformProxy` option](#Options-platformProxy) to change your preferences for the bindings.\n\nFor testing the build, you should use [Wrangler](https://developers.cloudflare.com/workers/wrangler/) version 4. Once you have built your site, run `wrangler dev .svelte-kit/cloudflare/_worker.js` if you're testing for Cloudflare Workers or `wrangler pages dev .svelte-kit/cloudflare` for Cloudflare Pages.\n\n## Headers and redirects\n\nThe [`_headers`](https://developers.cloudflare.com/pages/configuration/headers/) and [`_redirects`](https://developers.cloudflare.com/pages/configuration/redirects/) files, specific to Cloudflare, can be used for static asset responses (like images) by putting them into the project root folder.\n\nHowever, they will have no effect on responses dynamically rendered by SvelteKit, which should return custom headers or redirect responses from [server endpoints](routing#server) or with the [`handle`](hooks#Server-hooks-handle) hook.\n\n## Troubleshooting\n\n### Node.js compatibility\n\nIf you would like to enable [Node.js compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs/), you can add the `nodejs_compat` compatibility flag to your Wrangler configuration file:\n\n```jsonc\n/// file: wrangler.jsonc\n{\n\t\"compatibility_flags\": [\"nodejs_compat\"]\n}\n```\n\n### Worker size limits\n\nWhen deploying your application, the server generated by SvelteKit is bundled into a single file. Wrangler will fail to publish your worker if it exceeds [the size limits](https://developers.cloudflare.com/workers/platform/limits/#worker-size) after minification. You're unlikely to hit this limit usually, but some large libraries can cause this to happen. In that case, you can try to reduce the size of your worker by only importing such libraries on the client side. See [the FAQ](./faq#How-do-I-use-a-client-side-library-accessing-document-or-window) for more information.\n\n### Accessing the file system\n\nYou can't use `fs` in Cloudflare Workers.\n\nInstead, use the [`read`]($app-server#read) function from `$app/server` to access your files. It works by fetching the file from the deployed public assets location.\n\nAlternatively, you can [prerender](page-options#prerender) the routes in question.\n\n## Migrating from Workers Sites\n\nCloudflare no longer recommends using [Workers Sites](https://developers.cloudflare.com/workers/configuration/sites/configuration/) and instead recommends using [Workers Static Assets](https://developers.cloudflare.com/workers/static-assets/). To migrate, replace `@sveltejs/adapter-cloudflare-workers` with `@sveltejs/adapter-cloudflare` and remove all `site` configuration settings from your Wrangler configuration file, then add the `assets.directory` and `assets.binding` configuration settings:\n\n### svelte.config.js\n\n```js\n// @errors: 2307\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-cloudflare-workers';\nimport adapter from '@sveltejs/adapter-cloudflare';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter()\n\t}\n};\n\nexport default config;\n```\n\n### wrangler.toml\n\n```toml\n/// file: wrangler.toml\nsite.bucket = \".cloudflare/public\"\nassets.directory = \".cloudflare/public\"\nassets.binding = \"ASSETS\" # Exclude this if you don't have a `main` key configured.\n```\n\n### wrangler.jsonc\n\n```jsonc\n/// file: wrangler.jsonc\n{\n\"site\": {\n\t\t\"bucket\": \".cloudflare/public\"\n\t},\n\"assets\": {\n\t\t\"directory\": \".cloudflare/public\",\n\t\t\"binding\": \"ASSETS\" // Exclude this if you don't have a `main` key configured.\n\t}\n}\n```","size_bytes":12399,"metadata":{"title":"Cloudflare"},"created_at":"2025-07-18T15:47:38.796Z","updated_at":"2026-02-14T01:33:24.851Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/70-adapter-cloudflare-workers.md","title":"Cloudflare Workers","filename":"70-adapter-cloudflare-workers.md","content":"To deploy to [Cloudflare Workers](https://workers.cloudflare.com/) with [Workers Sites](https://developers.cloudflare.com/workers/configuration/sites/), use `adapter-cloudflare-workers`.\n\n## Usage\n\nInstall with `npm i -D @sveltejs/adapter-cloudflare-workers`, then add the adapter to your `svelte.config.js`:\n\n```js\n// @errors: 2307\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-cloudflare-workers';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\t// see below for options that can be set here\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\n## Options\n\n### config\n\nPath to your [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/). If you would like to use a Wrangler configuration filename other than `wrangler.jsonc`, `wrangler.json`, or `wrangler.toml` you can specify it using this option.\n\n### platformProxy\n\nPreferences for the emulated `platform.env` local bindings. See the [getPlatformProxy](https://developers.cloudflare.com/workers/wrangler/api/#parameters-1) Wrangler API documentation for a full list of options.\n\n## Basic Configuration\n\nThis adapter expects to find a [Wrangler configuration file](https://developers.cloudflare.com/workers/configuration/sites/configuration/) in the project root. It should look something like this:\n\n```jsonc\n/// file: wrangler.jsonc\n{\n\t\"name\": \"<your-service-name>\",\n\t\"account_id\": \"<your-account-id>\",\n\t\"main\": \"./.cloudflare/worker.js\",\n\t\"site\": {\n\t\t\"bucket\": \"./.cloudflare/public\"\n\t},\n\t\"build\": {\n\t\t\"command\": \"npm run build\"\n\t},\n\t\"compatibility_date\": \"2021-11-12\"\n}\n```\n\n`<your-service-name>` can be anything. `<your-account-id>` can be found by running `wrangler whoami` using the Wrangler CLI tool or by logging into your [Cloudflare dashboard](https://dash.cloudflare.com) and grabbing it from the end of the URL:\n\n```\nhttps://dash.cloudflare.com/<your-account-id>/home\n```\n\n\nYou will need to install [Wrangler](https://developers.cloudflare.com/workers/wrangler/install-and-update/) and log in, if you haven't already:\n\n```sh\nnpm i -D wrangler\nwrangler login\n```\n\nThen, you can build your app and deploy it:\n\n```sh\nwrangler deploy\n```\n\n## Runtime APIs\n\nThe [`env`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#parameters) object contains your project's [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/), which consist of KV/DO namespaces, etc. It is passed to SvelteKit via the `platform` property, along with [`ctx`](https://developers.cloudflare.com/workers/runtime-apis/context/), [`caches`](https://developers.cloudflare.com/workers/runtime-apis/cache/), and [`cf`](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties), meaning that you can access it in hooks and endpoints:\n\n```js\n// @filename: ambient.d.ts\nimport { DurableObjectNamespace } from '@cloudflare/workers-types';\n\ndeclare global {\n\tnamespace App {\n\t\tinterface Platform {\n\t\t\tenv: {\n\t\t\t\tYOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;\n\t\t\t};\n\t\t}\n\t}\n}\n// @filename: +server.js\n//cut\n// @errors: 2355 2322\n/// file: +server.js\n/** @type {import('./$types').RequestHandler} */\nexport async function POST({ request, platform }) {\n\tconst x = platform?.env.YOUR_DURABLE_OBJECT_NAMESPACE.idFromName('x');\n}\n```\n\n\nTo make these types available to your app, install [`@cloudflare/workers-types`](https://www.npmjs.com/package/@cloudflare/workers-types) and reference them in your `src/app.d.ts`:\n\n```ts\n/// file: src/app.d.ts\nimport { KVNamespace, DurableObjectNamespace } from '@cloudflare/workers-types';\n\ndeclare global {\n\tnamespace App {\n\t\tinterface Platform {\nenv?: {\n\t\t\t\tYOUR_KV_NAMESPACE: KVNamespace;\n\t\t\t\tYOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;\n\t\t\t};\n\t\t}\n\t}\n}\n\nexport {};\n```\n\n### Testing Locally\n\nCloudflare Workers specific values in the `platform` property are emulated during dev and preview modes. Local [bindings](https://developers.cloudflare.com/workers/wrangler/configuration/#bindings) are created based on your [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/) and are used to populate `platform.env` during development and preview. Use the adapter config [`platformProxy` option](#Options-platformProxy) to change your preferences for the bindings.\n\nFor testing the build, you should use [Wrangler](https://developers.cloudflare.com/workers/wrangler/) version 4. Once you have built your site, run `wrangler dev`.\n\n## Troubleshooting\n\n### Node.js compatibility\n\nIf you would like to enable [Node.js compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs/), you can add the `nodejs_compat` compatibility flag to your Wrangler configuration file:\n\n```jsonc\n/// file: wrangler.jsonc\n{\n\t\"compatibility_flags\": [\"nodejs_compat\"]\n}\n```\n\n### Worker size limits\n\nWhen deploying your application, the server generated by SvelteKit is bundled into a single file. Wrangler will fail to publish your worker if it exceeds [the size limits](https://developers.cloudflare.com/workers/platform/limits/#worker-size) after minification. You're unlikely to hit this limit usually, but some large libraries can cause this to happen. In that case, you can try to reduce the size of your worker by only importing such libraries on the client side. See [the FAQ](./faq#How-do-I-use-a-client-side-library-accessing-document-or-window) for more information.\n\n### Accessing the file system\n\nYou can't use `fs` in Cloudflare Workers — you must [prerender](page-options#prerender) the routes in question.","size_bytes":5621,"metadata":{"title":"Cloudflare Workers"},"created_at":"2025-07-18T15:47:38.797Z","updated_at":"2025-08-14T14:00:06.334Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md","title":"Netlify","filename":"80-adapter-netlify.md","content":"To deploy to Netlify, use [`adapter-netlify`](https://github.com/sveltejs/kit/tree/main/packages/adapter-netlify).\n\nThis adapter will be installed by default when you use [`adapter-auto`](adapter-auto), but adding it to your project allows you to specify Netlify-specific options.\n\n## Usage\n\nInstall with `npm i -D @sveltejs/adapter-netlify`, then add the adapter to your `svelte.config.js`:\n\n```js\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-netlify';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\t// default options are shown\n\t\tadapter: adapter({\n\t\t\t// if true, will create a Netlify Edge Function rather\n\t\t\t// than using standard Node-based functions\n\t\t\tedge: false,\n\n\t\t\t// if true, will split your app into multiple functions\n\t\t\t// instead of creating a single one for the entire app.\n\t\t\t// if `edge` is true, this option cannot be used\n\t\t\tsplit: false\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\nThen, make sure you have a [netlify.toml](https://docs.netlify.com/configure-builds/file-based-configuration) file in the project root. This will determine where to write static assets based on the `build.publish` settings, as per this sample configuration:\n\n```toml\n[build]\n\tcommand = \"npm run build\"\n\tpublish = \"build\"\n```\n\nIf the `netlify.toml` file or the `build.publish` value is missing, a default value of `\"build\"` will be used. Note that if you have set the publish directory in the Netlify UI to something else then you will need to set it in `netlify.toml` too, or use the default value of `\"build\"`.\n\n### Node version\n\nNew projects will use the current Node LTS version by default. However, if you're upgrading a project you created a while ago it may be stuck on an older version. See [the Netlify docs](https://docs.netlify.com/configure-builds/manage-dependencies/#node-js-and-javascript) for details on manually specifying a current Node version.\n\n## Netlify Edge Functions\n\nSvelteKit supports [Netlify Edge Functions](https://docs.netlify.com/build/edge-functions/overview/). If you pass the option `edge: true` to the `adapter` function, server-side rendering will happen in a Deno-based edge function that's deployed close to the site visitor. If set to `false` (the default), the site will deploy to Node-based Netlify Functions.\n\n```js\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-netlify';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\t// will create a Netlify Edge Function using Deno-based\n\t\t\t// rather than using standard Node-based functions\n\t\t\tedge: true\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\n## Netlify alternatives to SvelteKit functionality\n\nYou may build your app using functionality provided directly by SvelteKit without relying on any Netlify functionality. Using the SvelteKit versions of these features will allow them to be used in dev mode, tested with integration tests, and to work with other adapters should you ever decide to switch away from Netlify. However, in some scenarios you may find it beneficial to use the Netlify versions of these features. One example would be if you're migrating an app that's already hosted on Netlify to SvelteKit.\n\n### `_headers` and `_redirects`\n\nThe [`_headers`](https://docs.netlify.com/routing/headers/#syntax-for-the-headers-file) and [`_redirects`](https://docs.netlify.com/routing/redirects/redirect-options/) files specific to Netlify can be used for static asset responses (like images) by putting them into the project root folder. You can also use [`[[redirects]]`](https://docs.netlify.com/routing/redirects/#syntax-for-the-netlify-configuration-file) in your `netlify.toml`.\n\n### Netlify Forms\n\n1. Create your Netlify HTML form as described [here](https://docs.netlify.com/forms/setup/#html-forms), e.g. as `/routes/contact/+page.svelte`. (Don't forget to add the hidden `form-name` input element!)\n2. Netlify's build bot parses your HTML files at deploy time, which means your form must be [prerendered](page-options#prerender) as HTML. You can either add `export const prerender = true` to your `contact.svelte` to prerender just that page or set the `kit.prerender.force: true` option to prerender all pages.\n3. If your Netlify form has a [custom success message](https://docs.netlify.com/forms/setup/#success-messages) like `<form netlify ... action=\"/success\">` then ensure the corresponding `/routes/success/+page.svelte` exists and is prerendered.\n\n### Netlify Functions\n\nWith this adapter, SvelteKit endpoints are hosted as [Netlify Functions](https://docs.netlify.com/functions/overview/). Netlify function handlers have additional context, including [Netlify Identity](https://docs.netlify.com/visitor-access/identity/) information. You can access this context via the `event.platform.context` field inside your hooks and `+page.server` or `+layout.server` endpoints. These are [serverless functions](https://docs.netlify.com/functions/overview/) when the `edge` property is `false` in the adapter config or [edge functions](https://docs.netlify.com/edge-functions/overview/#app) when it is `true`.\n\n```js\n// @errors: 2339\n// @filename: ambient.d.ts\n/// <reference types=\"@sveltejs/adapter-netlify\" />\n// @filename: +page.server.js\n//cut\n/// file: +page.server.js\n/** @type {import('./$types').PageServerLoad} */\nexport const load = async (event) => {\n\tconst context = event.platform?.context;\n\tconsole.log(context); // shows up in your functions log in the Netlify app\n};\n```\n\nAdditionally, you can add your own Netlify functions by creating a directory for them and adding the configuration to your `netlify.toml` file. For example:\n\n```toml\n[build]\n\tcommand = \"npm run build\"\n\tpublish = \"build\"\n\n[functions]\n\tdirectory = \"functions\"\n```\n\n## Troubleshooting\n\n### Accessing the file system\n\nYou can't use `fs` in edge deployments.\n\nYou _can_ use it in serverless deployments, but it won't work as expected, since files are not copied from your project into your deployment. Instead, use the [`read`]($app-server#read) function from `$app/server` to access your files. It also works inside edge deployments by fetching the file from the deployed public assets location.\n\nAlternatively, you can [prerender](page-options#prerender) the routes in question.","size_bytes":6297,"metadata":{"title":"Netlify"},"created_at":"2025-07-18T15:47:38.799Z","updated_at":"2026-02-14T01:33:24.849Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md","title":"Vercel","filename":"90-adapter-vercel.md","content":"To deploy to Vercel, use [`adapter-vercel`](https://github.com/sveltejs/kit/tree/main/packages/adapter-vercel).\n\nThis adapter will be installed by default when you use [`adapter-auto`](adapter-auto), but adding it to your project allows you to specify Vercel-specific options.\n\n## Usage\n\nInstall with `npm i -D @sveltejs/adapter-vercel`, then add the adapter to your `svelte.config.js`:\n\n```js\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-vercel';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\t// see below for options that can be set here\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\n## Deployment configuration\n\nTo control how your routes are deployed to Vercel as functions, you can specify deployment configuration, either through the option shown above or with [`export const config`](page-options#config) inside `+server.js`, `+page(.server).js` and `+layout(.server).js` files.\n\nFor example you could deploy one specific route as an individual serverless function, separate from the rest of your app:\n\n```js\n/// file: about/+page.js\n/** @type {import('@sveltejs/adapter-vercel').Config} */\nexport const config = {\n\tsplit: true\n};\n```\n\nThe following options apply to all functions:\n\n- `runtime`: `'edge'`, `'nodejs20.x'` or `'nodejs22.x'`. By default, the adapter will select the `'nodejs<version>.x'` corresponding to the Node version your project is configured to use on the Vercel dashboard\n- `regions`: an array of [edge network regions](https://vercel.com/docs/concepts/edge-network/regions) (defaulting to `[\"iad1\"]` for serverless functions) or `'all'` if `runtime` is `edge` (its default). Note that multiple regions for serverless functions are only supported on Enterprise plans\n- `split`: if `true`, causes a route to be deployed as an individual function. If `split` is set to `true` at the adapter level, all routes will be deployed as individual functions\n\nAdditionally, the following option applies to edge functions:\n- `external`: an array of dependencies that esbuild should treat as external when bundling functions. This should only be used to exclude optional dependencies that will not run outside Node\n\nAnd the following option apply to serverless functions:\n- `memory`: the amount of memory available to the function. Defaults to `1024` Mb, and can be decreased to `128` Mb or [increased](https://vercel.com/docs/concepts/limits/overview#serverless-function-memory) in 64Mb increments up to `3008` Mb on Pro or Enterprise accounts\n- `maxDuration`: [maximum execution duration](https://vercel.com/docs/functions/runtimes#max-duration) of the function. Defaults to `10` seconds for Hobby accounts, `15` for Pro and `900` for Enterprise\n- `isr`: configuration Incremental Static Regeneration, described below\n\nConfiguration set in a layout applies to all the routes beneath that layout, unless overridden at a more granular level.\n\nIf your functions need to access data in a specific region, it's recommended that they be deployed in the same region (or close to it) for optimal performance.\n\n## Image Optimization\n\nYou may set the `images` config to control how Vercel builds your images. See the [image configuration reference](https://vercel.com/docs/build-output-api/v3/configuration#images) for full details. As an example, you may set:\n\n```js\n/// file: svelte.config.js\nimport adapter from '@sveltejs/adapter-vercel';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter({\n\t\t\timages: {\n\t\t\t\tsizes: [640, 828, 1200, 1920, 3840],\n\t\t\t\tformats: ['image/avif', 'image/webp'],\n\t\t\t\tminimumCacheTTL: 300,\n\t\t\t\tdomains: ['example-app.vercel.app'],\n\t\t\t}\n\t\t})\n\t}\n};\n\nexport default config;\n```\n\n## Incremental Static Regeneration\n\nVercel supports [Incremental Static Regeneration](https://vercel.com/docs/incremental-static-regeneration) (ISR), which provides the performance and cost advantages of prerendered content with the flexibility of dynamically rendered content.\n\n\nTo add ISR to a route, include the `isr` property in your `config` object:\n\n```js\nimport { BYPASS_TOKEN } from '$env/static/private';\n\n/** @type {import('@sveltejs/adapter-vercel').Config} */\nexport const config = {\n\tisr: {\n\t\texpiration: 60,\n\t\tbypassToken: BYPASS_TOKEN,\n\t\tallowQuery: ['search']\n\t}\n};\n```\n\n\nThe `expiration` property is required; all others are optional. The properties are discussed in more detail below.\n\n### expiration\n\nThe expiration time (in seconds) before the cached asset will be re-generated by invoking the Serverless Function. Setting the value to `false` means it will never expire. In that case, you likely want to define a bypass token to re-generate on demand.\n\n### bypassToken\n\nA random token that can be provided in the URL to bypass the cached version of the asset, by requesting the asset with a `__prerender_bypass=<token>` cookie.\n\nMaking a `GET` or `HEAD` request with `x-prerender-revalidate: <token>` will force the asset to be re-validated.\n\nNote that the `BYPASS_TOKEN` string must be at least 32 characters long. You could generate one using the JavaScript console like so:\n\n```js\ncrypto.randomUUID();\n```\n\nSet this string as an environment variable on Vercel by logging in and going to your project then Settings > Environment Variables. For \"Key\" put `BYPASS_TOKEN` and for \"value\" use the string generated above, then hit \"Save\".\n\nTo get this key known about for local development, you can use the [Vercel CLI](https://vercel.com/docs/cli/env) by running the `vercel env pull` command locally like so:\n\n```sh\nvercel env pull .env.development.local\n```\n\n### allowQuery\n\nA list of valid query parameters that contribute to the cache key. Other parameters (such as utm tracking codes) will be ignored, ensuring that they do not result in content being re-generated unnecessarily. By default, query parameters are ignored.\n\n\n## Environment variables\n\nVercel makes a set of [deployment-specific environment variables](https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables) available. Like other environment variables, these are accessible from `$env/static/private` and `$env/dynamic/private` (sometimes — more on that later), and inaccessible from their public counterparts. To access one of these variables from the client:\n\n```js\n/// file: +layout.server.js\nimport { VERCEL_COMMIT_REF } from '$env/static/private';\n\n/** @type {import('./$types').LayoutServerLoad} */\nexport function load() {\n\treturn {\n\t\tdeploymentGitBranch: VERCEL_COMMIT_REF\n\t};\n}\n```\n\n```svelte\n<!file: +layout.svelte>\n<script>\n\t/** @type {import('./$types').LayoutProps} */\n\tlet { data } = $props();\n</script>\n\n<p>This staging environment was deployed from {data.deploymentGitBranch}.</p>\n```\n\nSince all of these variables are unchanged between build time and run time when building on Vercel, we recommend using `$env/static/private` — which will statically replace the variables, enabling optimisations like dead code elimination — rather than `$env/dynamic/private`.\n\n## Skew protection\n\nWhen a new version of your app is deployed, assets belonging to the previous version may no longer be accessible. If a user is actively using your app when this happens, it can cause errors when they navigate — this is known as _version skew_. SvelteKit mitigates this by detecting errors resulting from version skew and causing a hard reload to get the latest version of the app, but this will cause any client-side state to be lost. (You can also proactively mitigate it by observing [`updated.current`]($app-state#updated) from `$app/state`, which tells clients when a new version has been deployed.)\n\n[Skew protection](https://vercel.com/docs/deployments/skew-protection) is a Vercel feature that routes client requests to their original deployment. When a user visits your app, a cookie is set with the deployment ID, and any subsequent requests will be routed to that deployment for as long as skew protection is active. When they reload the page, they will get the newest deployment. (`updated.current` is exempted from this behaviour, and so will continue to report new deployments.) To enable it, visit the Advanced section of your project settings on Vercel.\n\nCookie-based skew protection comes with one caveat: if a user has multiple versions of your app open in multiple tabs, requests from older versions will be routed to the newer one, meaning they will fall back to SvelteKit's built-in skew protection.\n\n## Notes\n\n### Vercel utilities\n\nIf you need Vercel-specific utilities like `waitUntil`, use the package [`@vercel/functions`](https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package).\n\n### Vercel functions\n\nIf you have Vercel functions contained in the `api` directory at the project's root, any requests for `/api/*` will _not_ be handled by SvelteKit. You should implement these as [API routes](routing#server) in your SvelteKit app instead, unless you need to use a non-JavaScript language in which case you will need to ensure that you don't have any `/api/*` routes in your SvelteKit app.\n\n### Node version\n\nProjects created before a certain date may default to using an older Node version than what SvelteKit currently requires. You can [change the Node version in your project settings](https://vercel.com/docs/concepts/functions/serverless-functions/runtimes/node-js#node.js-version).\n\n## Troubleshooting\n\n### Accessing the file system\n\nYou can't use `fs` in edge functions.\n\nYou _can_ use it in serverless functions, but it won't work as expected, since files are not copied from your project into your deployment. Instead, use the [`read`]($app-server#read) function from `$app/server` to access your files. It also works inside routes deployed as edge functions by fetching the file from the deployed public assets location.\n\nAlternatively, you can [prerender](page-options#prerender) the routes in question.\n\n### Deployment protection\n\nIf using [`read`]($app-server#read) in an edge function, SvelteKit will `fetch` the file in question from your deployment. If you are using [Deployment Protection](https://vercel.com/docs/deployment-protection), you must also enable [Protection Bypass for Automation](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/protection-bypass-automation) so that the request does not result in a [401 Unauthorized](https://http.dog/401) response.","size_bytes":10446,"metadata":{"title":"Vercel"},"created_at":"2025-07-18T15:47:38.800Z","updated_at":"2026-01-02T02:00:04.293Z"},{"path":"apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md","title":"Writing adapters","filename":"99-writing-adapters.md","content":"If an adapter for your preferred environment doesn't yet exist, you can build your own. We recommend [looking at the source for an adapter](https://github.com/sveltejs/kit/tree/main/packages) to a platform similar to yours and copying it as a starting point.\n\nAdapter packages implement the following API, which creates an `Adapter`:\n\n```js\n// @errors: 2322\n// @filename: ambient.d.ts\ntype AdapterSpecificOptions = any;\n\n// @filename: index.js\n//cut\n/** @param {AdapterSpecificOptions} options */\nexport default function (options) {\n\t/** @type {import('@sveltejs/kit').Adapter} */\n\tconst adapter = {\n\t\tname: 'adapter-package-name',\n\t\tasync adapt(builder) {\n\t\t\t// adapter implementation\n\t\t},\n\t\tasync emulate() {\n\t\t\treturn {\n\t\t\t\tasync platform({ config, prerender }) {\n\t\t\t\t\t// the returned object becomes `event.platform` during dev, build and\n\t\t\t\t\t// preview. Its shape is that of `App.Platform`\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tsupports: {\n\t\t\tread: ({ config, route }) => {\n\t\t\t\t// Return `true` if the route with the given `config` can use `read`\n\t\t\t\t// from `$app/server` in production, return `false` if it can't.\n\t\t\t\t// Or throw a descriptive error describing how to configure the deployment\n\t\t\t},\n\t\t\tinstrumentation: () => {\n\t\t\t\t// Return `true` if this adapter supports loading `instrumentation.server.js`.\n\t\t\t\t// Return `false if it can't, or throw a descriptive error.\n\t\t\t}\n\t\t}\n\t};\n\n\treturn adapter;\n}\n```\n\nOf these, `name` and `adapt` are required. `emulate` and `supports` are optional.\n\nWithin the `adapt` method, there are a number of things that an adapter should do:\n\n- Clear out the build directory\n- Write SvelteKit output with `builder.writeClient`, `builder.writeServer`, and `builder.writePrerendered`\n- Output code that:\n\t- Imports `Server` from `${builder.getServerDirectory()}/index.js`\n\t- Instantiates the app with a manifest generated with `builder.generateManifest({ relativePath })`\n\t- Listens for requests from the platform, converts them to a standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) if necessary, calls the `server.respond(request, { getClientAddress })` function to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) and responds with it\n\t- expose any platform-specific information to SvelteKit via the `platform` option passed to `server.respond`\n\t- Globally shims `fetch` to work on the target platform, if necessary. SvelteKit provides a `@sveltejs/kit/node/polyfills` helper for platforms that can use `undici`\n- Bundle the output to avoid needing to install dependencies on the target platform, if necessary\n- Put the user's static files and the generated JS/CSS in the correct location for the target platform\n\nWhere possible, we recommend putting the adapter output under the `build/` directory with any intermediate output placed under `.svelte-kit/[adapter-name]`.","size_bytes":2891,"metadata":{"title":"Writing adapters"},"created_at":"2025-07-18T15:47:38.802Z","updated_at":"2026-02-26T02:00:03.890Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/10-advanced-routing.md","title":"Advanced routing","filename":"10-advanced-routing.md","content":"## Rest parameters\n\nIf the number of route segments is unknown, you can use rest syntax — for example you might implement GitHub's file viewer like so...\n\n```sh\n/[org]/[repo]/tree/[branch]/[...file]\n```\n\n...in which case a request for `/sveltejs/kit/tree/main/documentation/docs/04-advanced-routing.md` would result in the following parameters being available to the page:\n\n```js\n// @noErrors\n{\n\torg: 'sveltejs',\n\trepo: 'kit',\n\tbranch: 'main',\n\tfile: 'documentation/docs/04-advanced-routing.md'\n}\n```\n\n\n### 404 pages\n\nRest parameters also allow you to render custom 404s. Given these routes...\n\n```tree\nsrc/routes/\n├ marx-brothers/\n│ ├ chico/\n│ ├ harpo/\n│ ├ groucho/\n│ └ +error.svelte\n└ +error.svelte\n```\n\n...the `marx-brothers/+error.svelte` file will _not_ be rendered if you visit `/marx-brothers/karl`, because no route was matched. If you want to render the nested error page, you should create a route that matches any `/marx-brothers/*` request, and return a 404 from it:\n\n```tree\nsrc/routes/\n├ marx-brothers/\n| ├ [...path]/\n│ ├ chico/\n│ ├ harpo/\n│ ├ groucho/\n│ └ +error.svelte\n└ +error.svelte\n```\n\n```js\n/// file: src/routes/marx-brothers/[...path]/+page.js\nimport { error } from '@sveltejs/kit';\n\n/** @type {import('./$types').PageLoad} */\nexport function load(event) {\n\terror(404, 'Not Found');\n}\n```\n\n\n## Optional parameters\n\nA route like `[lang]/home` contains a parameter named `lang` which is required. Sometimes it's beneficial to make these parameters optional, so that in this example both `home` and `en/home` point to the same page. You can do that by wrapping the parameter in another bracket pair: `[[lang]]/home`\n\nNote that an optional route parameter cannot follow a rest parameter (`[...rest]/[[optional]]`), since parameters are matched 'greedily' and the optional parameter would always be unused.\n\n## Matching\n\nA route like `src/routes/fruits/[page]` would match `/fruits/apple`, but it would also match `/fruits/rocketship`. We don't want that. You can ensure that route parameters are well-formed by adding a _matcher_ — which takes the parameter string (`\"apple\"` or `\"rocketship\"`) and returns `true` if it is valid — to your `src/params` directory...\n\n```js\n/// file: src/params/fruit.js\n/**\n * @param {string} param\n * @return {param is ('apple' | 'orange')}\n * @satisfies {import('@sveltejs/kit').ParamMatcher}\n */\nexport function match(param) {\n\treturn param === 'apple' || param === 'orange';\n}\n```\n\n...and augmenting your routes:\n\n```\nsrc/routes/fruits/[page=fruit]\n```\n\nIf the pathname doesn't match, SvelteKit will try to match other routes (using the sort order specified below), before eventually returning a 404.\n\nEach module in the `params` directory corresponds to a matcher, with the exception of `*.test.js` and `*.spec.js` files which may be used to unit test your matchers.\n\n\n## Sorting\n\nIt's possible for multiple routes to match a given path. For example each of these routes would match `/foo-abc`:\n\n```sh\nsrc/routes/[...catchall]/+page.svelte\nsrc/routes/[[a=x]]/+page.svelte\nsrc/routes/[b]/+page.svelte\nsrc/routes/foo-[c]/+page.svelte\nsrc/routes/foo-abc/+page.svelte\n```\n\nSvelteKit needs to know which route is being requested. To do so, it sorts them according to the following rules...\n\n- More specific routes are higher priority (e.g. a route with no parameters is more specific than a route with one dynamic parameter, and so on)\n- Parameters with [matchers](#Matching) (`[name=type]`) are higher priority than those without (`[name]`)\n- `[[optional]]` and `[...rest]` parameters are ignored unless they are the final part of the route, in which case they are treated with lowest priority. In other words `x/[[y]]/z` is treated equivalently to `x/z` for the purposes of sorting\n- Ties are resolved alphabetically\n\n...resulting in this ordering, meaning that `/foo-abc` will invoke `src/routes/foo-abc/+page.svelte`, and `/foo-def` will invoke `src/routes/foo-[c]/+page.svelte` rather than less specific routes:\n\n```sh\nsrc/routes/foo-abc/+page.svelte\nsrc/routes/foo-[c]/+page.svelte\nsrc/routes/[[a=x]]/+page.svelte\nsrc/routes/[b]/+page.svelte\nsrc/routes/[...catchall]/+page.svelte\n```\n\n## Encoding\n\nSome characters can't be used on the filesystem — `/` on Linux and Mac, `\\ / : * ? \" < > |` on Windows. The `#` and `%` characters have special meaning in URLs, and the `[ ] ( )` characters have special meaning to SvelteKit, so these also can't be used directly as part of your route.\n\nTo use these characters in your routes, you can use hexadecimal escape sequences, which have the format `[x+nn]` where `nn` is a hexadecimal character code:\n\n- `\\` — `[x+5c]`\n- `/` — `[x+2f]`\n- `:` — `[x+3a]`\n- `*` — `[x+2a]`\n- `?` — `[x+3f]`\n- `\"` — `[x+22]`\n- `<` — `[x+3c]`\n- `>` — `[x+3e]`\n- `|` — `[x+7c]`\n- `#` — `[x+23]`\n- `%` — `[x+25]`\n- `[` — `[x+5b]`\n- `]` — `[x+5d]`\n- `(` — `[x+28]`\n- `)` — `[x+29]`\n\nFor example, to create a `/smileys/:-)` route, you would create a `src/routes/smileys/[x+3a]-[x+29]/+page.svelte` file.\n\nYou can determine the hexadecimal code for a character with JavaScript:\n\n```js\n':'.charCodeAt(0).toString(16); // '3a', hence '[x+3a]'\n```\n\nYou can also use Unicode escape sequences. Generally you won't need to as you can use the unencoded character directly, but if — for some reason — you can't have a filename with an emoji in it, for example, then you can use the escaped characters. In other words, these are equivalent:\n\n```\nsrc/routes/[u+d83e][u+dd2a]/+page.svelte\nsrc/routes/🤪/+page.svelte\n```\n\nThe format for a Unicode escape sequence is `[u+nnnn]` where `nnnn` is a valid value between `0000` and `10ffff`. (Unlike JavaScript string escaping, there's no need to use surrogate pairs to represent code points above `ffff`.) To learn more about Unicode encodings, consult [Programming with Unicode](https://unicodebook.readthedocs.io/unicode_encodings.html).\n\n\n## Advanced layouts\n\nBy default, the _layout hierarchy_ mirrors the _route hierarchy_. In some cases, that might not be what you want.\n\n### (group)\n\nPerhaps you have some routes that are 'app' routes that should have one layout (e.g. `/dashboard` or `/item`), and others that are 'marketing' routes that should have a different layout (`/about` or `/testimonials`). We can group these routes with a directory whose name is wrapped in parentheses — unlike normal directories, `(app)` and `(marketing)` do not affect the URL pathname of the routes inside them:\n\n```tree\nsrc/routes/\n│ (app)/\n│ ├ dashboard/\n│ ├ item/\n│ └ +layout.svelte\n│ (marketing)/\n│ ├ about/\n│ ├ testimonials/\n│ └ +layout.svelte\n├ admin/\n└ +layout.svelte\n```\n\nYou can also put a `+page` directly inside a `(group)`, for example if `/` should be an `(app)` or a `(marketing)` page.\n\n### Breaking out of layouts\n\nThe root layout applies to every page of your app — if omitted, it defaults to `{@render children()}`. If you want some pages to have a different layout hierarchy than the rest, then you can put your entire app inside one or more groups _except_ the routes that should not inherit the common layouts.\n\nIn the example above, the `/admin` route does not inherit either the `(app)` or `(marketing)` layouts.\n\n### +page@\n\nPages can break out of the current layout hierarchy on a route-by-route basis. Suppose we have an `/item/[id]/embed` route inside the `(app)` group from the previous example:\n\n```tree\nsrc/routes/\n├ (app)/\n│ ├ item/\n│ │ ├ [id]/\n│ │ │ ├ embed/\n│ │ │ │ └ +page.svelte\n│ │ │ └ +layout.svelte\n│ │ └ +layout.svelte\n│ └ +layout.svelte\n└ +layout.svelte\n```\n\nOrdinarily, this would inherit the root layout, the `(app)` layout, the `item` layout and the `[id]` layout. We can reset to one of those layouts by appending `@` followed by the segment name — or, for the root layout, the empty string. In this example, we can choose from the following options:\n\n- `+page@[id].svelte` - inherits from `src/routes/(app)/item/[id]/+layout.svelte`\n- `+page@item.svelte` - inherits from `src/routes/(app)/item/+layout.svelte`\n- `+page@(app).svelte` - inherits from `src/routes/(app)/+layout.svelte`\n- `+page@.svelte` - inherits from `src/routes/+layout.svelte`\n\n```tree\nsrc/routes/\n├ (app)/\n│ ├ item/\n│ │ ├ [id]/\n│ │ │ ├ embed/\n│ │ │ │ └ +page@(app).svelte\n│ │ │ └ +layout.svelte\n│ │ └ +layout.svelte\n│ └ +layout.svelte\n└ +layout.svelte\n```\n\n### +layout@\n\nLike pages, layouts can _themselves_ break out of their parent layout hierarchy, using the same technique. For example, a `+layout@.svelte` component would reset the hierarchy for all its child routes.\n\n```\nsrc/routes/\n├ (app)/\n│ ├ item/\n│ │ ├ [id]/\n│ │ │ ├ embed/\n│ │ │ │ └ +page.svelte  // uses (app)/item/[id]/+layout.svelte\n│ │ │ ├ +layout.svelte  // inherits from (app)/item/+layout@.svelte\n│ │ │ └ +page.svelte    // uses (app)/item/+layout@.svelte\n│ │ └ +layout@.svelte   // inherits from root layout, skipping (app)/+layout.svelte\n│ └ +layout.svelte\n└ +layout.svelte\n```\n\n### When to use layout groups\n\nNot all use cases are suited for layout grouping, nor should you feel compelled to use them. It might be that your use case would result in complex `(group)` nesting, or that you don't want to introduce a `(group)` for a single outlier. It's perfectly fine to use other means such as composition (reusable `load` functions or Svelte components) or if-statements to achieve what you want. The following example shows a layout that rewinds to the root layout and reuses components and functions that other layouts can also use:\n\n```svelte\n<!file: src/routes/nested/route/+layout@.svelte>\n<script>\n\timport ReusableLayout from '$lib/ReusableLayout.svelte';\n\tlet { data, children } = $props();\n</script>\n\n<ReusableLayout {data}>\n\t{@render children()}\n</ReusableLayout>\n```\n\n```js\n/// file: src/routes/nested/route/+layout.js\n// @filename: ambient.d.ts\ndeclare module \"$lib/reusable-load-function\" {\n\texport function reusableLoad(event: import('@sveltejs/kit').LoadEvent): Promise<Record<string, any>>;\n}\n// @filename: index.js\n//cut\nimport { reusableLoad } from '$lib/reusable-load-function';\n\n/** @type {import('./$types').PageLoad} */\nexport function load(event) {\n\t// Add additional logic here, if needed\n\treturn reusableLoad(event);\n}\n```\n\n## Further reading\n\n- [Tutorial: Advanced Routing](/tutorial/kit/optional-params)","size_bytes":10523,"metadata":{"title":"Advanced routing"},"created_at":"2025-07-18T15:47:38.805Z","updated_at":"2026-02-21T14:00:04.063Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md","title":"Hooks","filename":"20-hooks.md","content":"'Hooks' are app-wide functions you declare that SvelteKit will call in response to specific events, giving you fine-grained control over the framework's behaviour.\n\nThere are three hooks files, all optional:\n\n- `src/hooks.server.js` — your app's server hooks\n- `src/hooks.client.js` — your app's client hooks\n- `src/hooks.js` — your app's hooks that run on both the client and server\n\nCode in these modules will run when the application starts up, making them useful for initializing database clients and so on.\n\n## Server hooks\n\nThe following hooks can be added to `src/hooks.server.js`:\n\n### handle\n\nThis function runs every time the SvelteKit server receives a [request](web-standards#Fetch-APIs-Request) — whether that happens while the app is running, or during [prerendering](page-options#prerender) — and determines the [response](web-standards#Fetch-APIs-Response). It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).\n\n```js\n/// file: src/hooks.server.js\n/** @type {import('@sveltejs/kit').Handle} */\nexport async function handle({ event, resolve }) {\n\tif (event.url.pathname.startsWith('/custom')) {\n\t\treturn new Response('custom response');\n\t}\n\n\tconst response = await resolve(event);\n\treturn response;\n}\n```\n\n\nIf unimplemented, defaults to `({ event, resolve }) => resolve(event)`.\n\nDuring prerendering, SvelteKit crawls your pages for links and renders each route it finds. Rendering the route invokes the `handle` function (and all other route dependencies, like `load`). If you need to exclude some code from running during this phase, check that the app is not [`building`]($app-environment#building) beforehand.\n\n### locals\n\nTo add custom data to the request, which is passed to handlers in `+server.js` and server `load` functions, populate the `event.locals` object, as shown below.\n\n```js\n/// file: src/hooks.server.js\n// @filename: ambient.d.ts\ntype User = {\n\tname: string;\n}\n\ndeclare namespace App {\n\tinterface Locals {\n\t\tuser: User;\n\t}\n}\n\nconst getUserInformation: (cookie: string | void) => Promise<User>;\n\n// @filename: index.js\n//cut\n/** @type {import('@sveltejs/kit').Handle} */\nexport async function handle({ event, resolve }) {\n\tevent.locals.user = await getUserInformation(event.cookies.get('sessionid'));\n\n\tconst response = await resolve(event);\n\n\t// Note that modifying response headers isn't always safe.\n\t// Response objects can have immutable headers\n\t// (e.g. Response.redirect() returned from an endpoint).\n\t// Modifying immutable headers throws a TypeError.\n\t// In that case, clone the response or avoid creating a\n\t// response object with immutable headers.\n\tresponse.headers.set('x-custom-header', 'potato');\n\n\treturn response;\n}\n```\n\nYou can define multiple `handle` functions and execute them with [the `sequence` helper function](@sveltejs-kit-hooks).\n\n`resolve` also supports a second, optional parameter that gives you more control over how the response will be rendered. That parameter is an object that can have the following fields:\n\n- `transformPageChunk(opts: { html: string, done: boolean }): MaybePromise<string | undefined>` — applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML (they could include an element's opening tag but not its closing tag, for example) but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components.\n- `filterSerializedResponseHeaders(name: string, value: string): boolean` — determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. By default, none will be included.\n- `preload(input: { type: 'js' | 'css' | 'font' | 'asset', path: string }): boolean` — determines what files should be added to the `<head>` tag to preload it. The method is called with each file that was found at build time while constructing the code chunks — so if you for example have `import './styles.css` in your `+page.svelte`, `preload` will be called with the resolved path to that CSS file when visiting that page. Note that in dev mode `preload` is _not_ called, since it depends on analysis that happens at build time. Preloading can improve performance by downloading assets sooner, but it can also hurt if too much is downloaded unnecessarily. By default, `js` and `css` files will be preloaded. `asset` files are not preloaded at all currently, but we may add this later after evaluating feedback.\n\n```js\n/// file: src/hooks.server.js\n/** @type {import('@sveltejs/kit').Handle} */\nexport async function handle({ event, resolve }) {\n\tconst response = await resolve(event, {\n\t\ttransformPageChunk: ({ html }) => html.replace('old', 'new'),\n\t\tfilterSerializedResponseHeaders: (name) => name.startsWith('x-'),\n\t\tpreload: ({ type, path }) => type === 'js' || path.includes('/important/')\n\t});\n\n\treturn response;\n}\n```\n\nNote that `resolve(...)` will never throw an error, it will always return a `Promise<Response>` with the appropriate status code. If an error is thrown elsewhere during `handle`, it is treated as fatal, and SvelteKit will respond with a JSON representation of the error or a fallback error page — which can be customised via `src/error.html` — depending on the `Accept` header. You can read more about error handling [here](errors).\n\n### handleFetch\n\nThis function allows you to modify (or replace) the result of an [`event.fetch`](load#Making-fetch-requests) call that runs on the server (or during prerendering) inside an endpoint, `load`, `action`, `handle`, `handleError` or `reroute`.\n\nFor example, your `load` function might make a request to a public URL like `https://api.yourapp.com` when the user performs a client-side navigation to the respective page, but during SSR it might make sense to hit the API directly (bypassing whatever proxies and load balancers sit between it and the public internet).\n\n```js\n/// file: src/hooks.server.js\n/** @type {import('@sveltejs/kit').HandleFetch} */\nexport async function handleFetch({ request, fetch }) {\n\tif (request.url.startsWith('https://api.yourapp.com/')) {\n\t\t// clone the original request, but change the URL\n\t\trequest = new Request(\n\t\t\trequest.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),\n\t\t\trequest\n\t\t);\n\t}\n\n\treturn fetch(request);\n}\n```\n\nRequests made with `event.fetch` follow the browser's credentials model — for same-origin requests, `cookie` and `authorization` headers are forwarded unless the `credentials` option is set to `\"omit\"`. For cross-origin requests, `cookie` will be included if the request URL belongs to a subdomain of the app — for example if your app is on `my-domain.com`, and your API is on `api.my-domain.com`, cookies will be included in the request.\n\nThere is one caveat: if your app and your API are on sibling subdomains — `www.my-domain.com` and `api.my-domain.com` for example — then a cookie belonging to a common parent domain like `my-domain.com` will _not_ be included, because SvelteKit has no way to know which domain the cookie belongs to. In these cases you will need to manually include the cookie using `handleFetch`:\n\n```js\n/// file: src/hooks.server.js\n// @errors: 2345\n/** @type {import('@sveltejs/kit').HandleFetch} */\nexport async function handleFetch({ event, request, fetch }) {\n\tif (request.url.startsWith('https://api.my-domain.com/')) {\n\t\trequest.headers.set('cookie', event.request.headers.get('cookie'));\n\t}\n\n\treturn fetch(request);\n}\n```\n\n### handleValidationError\n\nThis hook is called when a remote function is called with an argument that does not match the provided [Standard Schema](https://standardschema.dev/). It must return an object matching the shape of [`App.Error`](types#Error).\n\nSay you have a remote function that expects a string as its argument ...\n\n```js\n/// file: todos.remote.js\nimport * as v from 'valibot';\nimport { query } from '$app/server';\n\nexport const getTodo = query(v.string(), (id) => {\n\t// implementation...\n});\n```\n\n...but it is called with something that doesn't match the schema — such as a number (e.g. `await getTodos(1)`) — then validation will fail, the server will respond with a [400 status code](https://http.dog/400), and the function will throw with the message 'Bad Request'.\n\nTo customise this message and add additional properties to the error object, implement `handleValidationError`:\n\n```js\n/// file: src/hooks.server.js\n/** @type {import('@sveltejs/kit').HandleValidationError} */\nexport function handleValidationError({ issues }) {\n\treturn {\n\t\tmessage: 'No thank you'\n\t};\n}\n```\n\nBe thoughtful about what information you expose here, as the most likely reason for validation to fail is that someone is sending malicious requests to your server.\n\n## Shared hooks\n\nThe following can be added to `src/hooks.server.js` _and_ `src/hooks.client.js`:\n\n### handleError\n\nIf an [unexpected error](errors#Unexpected-errors) is thrown during loading, rendering, or from an endpoint, this function will be called with the `error`, `event`, `status` code and `message`. This allows for two things:\n\n- you can log the error\n- you can generate a custom representation of the error that is safe to show to users, omitting sensitive details like messages and stack traces. The returned value, which defaults to `{ message }`, becomes the value of `page.error`.\n\nFor errors thrown from your code (or library code called by your code) the status will be 500 and the message will be \"Internal Error\". While `error.message` may contain sensitive information that should not be exposed to users, `message` is safe (albeit meaningless to the average user).\n\nTo add more information to the `page.error` object in a type-safe way, you can customize the expected shape by declaring an `App.Error` interface (which must include `message: string`, to guarantee sensible fallback behavior). This allows you to — for example — append a tracking ID for users to quote in correspondence with your technical support staff:\n\n```ts\n/// file: src/app.d.ts\ndeclare global {\n\tnamespace App {\n\t\tinterface Error {\n\t\t\tmessage: string;\n\t\t\terrorId: string;\n\t\t}\n\t}\n}\n\nexport {};\n```\n\n```js\n/// file: src/hooks.server.js\n// @errors: 2322 2353\n// @filename: ambient.d.ts\ndeclare module '@sentry/sveltekit' {\n\texport const init: (opts: any) => void;\n\texport const captureException: (error: any, opts: any) => void;\n}\n\n// @filename: index.js\n//cut\nimport * as Sentry from '@sentry/sveltekit';\n\nSentry.init({/*...*/})\n\n/** @type {import('@sveltejs/kit').HandleServerError} */\nexport async function handleError({ error, event, status, message }) {\n\tconst errorId = crypto.randomUUID();\n\n\t// example integration with https://sentry.io/\n\tSentry.captureException(error, {\n\t\textra: { event, errorId, status }\n\t});\n\n\treturn {\n\t\tmessage: 'Whoops!',\n\t\terrorId\n\t};\n}\n```\n\n```js\n/// file: src/hooks.client.js\n// @errors: 2322 2353\n// @filename: ambient.d.ts\ndeclare module '@sentry/sveltekit' {\n\texport const init: (opts: any) => void;\n\texport const captureException: (error: any, opts: any) => void;\n}\n\n// @filename: index.js\n//cut\nimport * as Sentry from '@sentry/sveltekit';\n\nSentry.init({/*...*/})\n\n/** @type {import('@sveltejs/kit').HandleClientError} */\nexport async function handleError({ error, event, status, message }) {\n\tconst errorId = crypto.randomUUID();\n\n\t// example integration with https://sentry.io/\n\tSentry.captureException(error, {\n\t\textra: { event, errorId, status }\n\t});\n\n\treturn {\n\t\tmessage: 'Whoops!',\n\t\terrorId\n\t};\n}\n```\n\n\nThis function is not called for _expected_ errors (those thrown with the [`error`](@sveltejs-kit#error) function imported from `@sveltejs/kit`).\n\nDuring development, if an error occurs because of a syntax error in your Svelte code, the passed in error has a `frame` property appended highlighting the location of the error.\n\n\n### init\n\nThis function runs once, when the server is created or the app starts in the browser, and is a useful place to do asynchronous work such as initializing a database connection.\n\n\n```js\n// @errors: 2307\n/// file: src/hooks.server.js\nimport * as db from '$lib/server/database';\n\n/** @type {import('@sveltejs/kit').ServerInit} */\nexport async function init() {\n\tawait db.connect();\n}\n```\n\n> In the browser, asynchronous work in `init` will delay hydration, so be mindful of what you put in there.\n\n## Universal hooks\n\nThe following can be added to `src/hooks.js`. Universal hooks run on both server and client (not to be confused with shared hooks, which are environment-specific).\n\n### reroute\n\nThis function runs before `handle` and allows you to change how URLs are translated into routes. The returned pathname (which defaults to `url.pathname`) is used to select the route and its parameters.\n\nFor example, you might have a `src/routes/[[lang]]/about/+page.svelte` page, which should be accessible as `/en/about` or `/de/ueber-uns` or `/fr/a-propos`. You could implement this with `reroute`:\n\n```js\n// @errors: 2345 2304\n/// file: src/hooks.js\n\n/** @type {Record<string, string>} */\nconst translated = {\n\t'/en/about': '/en/about',\n\t'/de/ueber-uns': '/de/about',\n\t'/fr/a-propos': '/fr/about',\n};\n\n/** @type {import('@sveltejs/kit').Reroute} */\nexport function reroute({ url }) {\n\tif (url.pathname in translated) {\n\t\treturn translated[url.pathname];\n\t}\n}\n```\n\nThe `lang` parameter will be correctly derived from the returned pathname.\n\nUsing `reroute` will _not_ change the contents of the browser's address bar, or the value of `event.url`.\n\nSince version 2.18, the `reroute` hook can be asynchronous, allowing it to (for example) fetch data from your backend to decide where to reroute to. Use this carefully and make sure it's fast, as it will delay navigation otherwise. If you need to fetch data, use the `fetch` provided as an argument. It has the [same benefits](load#Making-fetch-requests) as the `fetch` provided to `load` functions, with the caveat that `params` and `id` are unavailable to [`handleFetch`](#Server-hooks-handleFetch) because the route is not yet known.\n\n```js\n// @errors: 2345 2304\n/// file: src/hooks.js\n\n/** @type {import('@sveltejs/kit').Reroute} */\nexport async function reroute({ url, fetch }) {\n\t// Ask a special endpoint within your app about the destination\n\tif (url.pathname === '/api/reroute') return;\n\n\tconst api = new URL('/api/reroute', url);\n\tapi.searchParams.set('pathname', url.pathname);\n\n\tconst result = await fetch(api).then(r => r.json());\n\treturn result.pathname;\n}\n```\n\n\n\n### transport\n\nThis is a collection of _transporters_, which allow you to pass custom types — returned from `load` and form actions — across the server/client boundary. Each transporter contains an `encode` function, which encodes values on the server (or returns a falsy value for anything that isn't an instance of the type) and a corresponding `decode` function:\n\n```js\n// @errors: 2307\n/// file: src/hooks.js\nimport { Vector } from '$lib/math';\n\n/** @type {import('@sveltejs/kit').Transport} */\nexport const transport = {\n\tVector: {\n\t\tencode: (value) => value instanceof Vector && [value.x, value.y],\n\t\tdecode: ([x, y]) => new Vector(x, y)\n\t}\n};\n```\n\n\n## Further reading\n\n- [Tutorial: Hooks](/tutorial/kit/handle)","size_bytes":15398,"metadata":{"title":"Hooks"},"created_at":"2025-07-18T15:47:38.805Z","updated_at":"2026-02-24T14:00:04.883Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/25-errors.md","title":"Errors","filename":"25-errors.md","content":"Errors are an inevitable fact of software development. SvelteKit handles errors differently depending on where they occur, what kind of errors they are, and the nature of the incoming request.\n\n## Error objects\n\nSvelteKit distinguishes between expected and unexpected errors, both of which are represented as simple `{ message: string }` objects by default.\n\nYou can add additional properties, like a `code` or a tracking `id`, as shown in the examples below. (When using TypeScript this requires you to redefine the `Error` type as described in  [type safety](errors#Type-safety)).\n\n## Expected errors\n\nAn _expected_ error is one created with the [`error`](@sveltejs-kit#error) helper imported from `@sveltejs/kit`:\n\n```js\n/// file: src/routes/blog/[slug]/+page.server.js\n// @filename: ambient.d.ts\ndeclare module '$lib/server/database' {\n\texport function getPost(slug: string): Promise<{ title: string, content: string } | undefined>\n}\n\n// @filename: index.js\n//cut\nimport { error } from '@sveltejs/kit';\nimport * as db from '$lib/server/database';\n\n/** @type {import('./$types').PageServerLoad} */\nexport async function load({ params }) {\n\tconst post = await db.getPost(params.slug);\n\n\tif (!post) {\n\t\terror(404, {\n\t\t\tmessage: 'Not found'\n\t\t});\n\t}\n\n\treturn { post };\n}\n```\n\nThis throws an exception that SvelteKit catches, causing it to set the response status code to 404 and render an [`+error.svelte`](routing#error) component, where `page.error` is the object provided as the second argument to `error(...)`.\n\n```svelte\n<!file: src/routes/+error.svelte>\n<script>\n\timport { page } from '$app/state';\n</script>\n\n<h1>{page.error.message}</h1>\n```\n\n> [!LEGACY]\n> `$app/state` was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use `$app/stores` instead.\n\nYou can add extra properties to the error object if needed...\n\n```js\n// @filename: ambient.d.ts\ndeclare global {\n\tnamespace App {\n\t\tinterface Error {\n\t\t\tmessage: string;\n\t\t\tcode: string;\n\t\t}\n\t}\n}\nexport {}\n\n// @filename: index.js\nimport { error } from '@sveltejs/kit';\n//cut\nerror(404, {\n\tmessage: 'Not found',\n\tcode: 'NOT_FOUND'\n});\n```\n\n...otherwise, for convenience, you can pass a string as the second argument:\n\n```js\nimport { error } from '@sveltejs/kit';\n//cut\nerror(404, { message: 'Not found' });\nerror(404, 'Not found');\n```\n\n\n## Unexpected errors\n\nAn _unexpected_ error is any other exception that occurs while handling a request. Since these can contain sensitive information, unexpected error messages and stack traces are not exposed to users.\n\nBy default, unexpected errors are printed to the console (or, in production, your server logs), while the error that is exposed to the user has a generic shape:\n\n```json\n{ \"message\": \"Internal Error\" }\n```\n\nUnexpected errors will go through the [`handleError`](hooks#Shared-hooks-handleError) hook, where you can add your own error handling — for example, sending errors to a reporting service, or returning a custom error object which becomes `page.error`.\n\n## Responses\n\nIf an error occurs inside `handle` or inside a [`+server.js`](routing#server) request handler, SvelteKit will respond with either a fallback error page or a JSON representation of the error object, depending on the request's `Accept` headers.\n\nYou can customise the fallback error page by adding a `src/error.html` file:\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n\t<head>\n\t\t<meta charset=\"utf-8\" />\n\t\t<title>%sveltekit.error.message%</title>\n\t</head>\n\t<body>\n\t\t<h1>My custom error page</h1>\n\t\t<p>Status: %sveltekit.status%</p>\n\t\t<p>Message: %sveltekit.error.message%</p>\n\t</body>\n</html>\n```\n\nSvelteKit will replace `%sveltekit.status%` and `%sveltekit.error.message%` with their corresponding values.\n\nIf the error instead occurs inside a `load` function while rendering a page, SvelteKit will render the [`+error.svelte`](routing#error) component nearest to where the error occurred. If the error occurs inside a `load` function in `+layout(.server).js`, the closest error boundary in the tree is an `+error.svelte` file _above_ that layout (not next to it).\n\nThe exception is when the error occurs inside the root `+layout.js` or `+layout.server.js`, since the root layout would ordinarily _contain_ the `+error.svelte` component. In this case, SvelteKit uses the fallback error page.\n\n## Type safety\n\nIf you're using TypeScript and need to customize the shape of errors, you can do so by declaring an `App.Error` interface in your app (by convention, in `src/app.d.ts`, though it can live anywhere that TypeScript can 'see'):\n\n```ts\n/// file: src/app.d.ts\ndeclare global {\n\tnamespace App {\n\t\tinterface Error {\ncode: string;\n\t\t\tid: string;\n\t\t}\n\t}\n}\n\nexport {};\n```\n\nThis interface always includes a `message: string` property.\n\n## Further reading\n\n- [Tutorial: Errors and redirects](/tutorial/kit/error-basics)\n- [Tutorial: Hooks](/tutorial/kit/handle)","size_bytes":4905,"metadata":{"title":"Errors"},"created_at":"2025-07-18T15:47:38.808Z","updated_at":"2026-02-24T14:00:04.883Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/30-link-options.md","title":"Link options","filename":"30-link-options.md","content":"In SvelteKit, `<a>` elements (rather than framework-specific `<Link>` components) are used to navigate between the routes of your app. If the user clicks on a link whose `href` is 'owned' by the app (as opposed to, say, a link to an external site) then SvelteKit will navigate to the new page by importing its code and then calling any `load` functions it needs to fetch data.\n\nYou can customise the behaviour of links with `data-sveltekit-*` attributes. These can be applied to the `<a>` itself, or to a parent element.\n\nThese options also apply to `<form>` elements with [`method=\"GET\"`](form-actions#GET-vs-POST).\n\n## data-sveltekit-preload-data\n\nBefore the browser registers that the user has clicked on a link, we can detect that they've hovered the mouse over it (on desktop) or that a `touchstart` or `mousedown` event was triggered. In both cases, we can make an educated guess that a `click` event is coming.\n\nSvelteKit can use this information to get a head start on importing the code and fetching the page's data, which can give us an extra couple of hundred milliseconds — the difference between a user interface that feels laggy and one that feels snappy.\n\nWe can control this behaviour with the `data-sveltekit-preload-data` attribute, which can have one of two values:\n\n- `\"hover\"` means that preloading will start if the mouse comes to a rest over a link. On mobile, preloading begins on `touchstart`\n- `\"tap\"` means that preloading will start as soon as a `touchstart` or `mousedown` event is registered\n\nThe default project template has a `data-sveltekit-preload-data=\"hover\"` attribute applied to the `<body>` element in `src/app.html`, meaning that every link is preloaded on hover by default:\n\n```html\n<body data-sveltekit-preload-data=\"hover\">\n\t<div style=\"display: contents\">%sveltekit.body%</div>\n</body>\n```\n\nSometimes, calling `load` when the user hovers over a link might be undesirable, either because it's likely to result in false positives (a click needn't follow a hover) or because data is updating very quickly and a delay could mean staleness.\n\nIn these cases, you can specify the `\"tap\"` value, which causes SvelteKit to call `load` only when the user taps or clicks on a link:\n\n```html\n<a data-sveltekit-preload-data=\"tap\" href=\"/stonks\">\n\tGet current stonk values\n</a>\n```\n\n\nData will never be preloaded if the user has chosen reduced data usage, meaning [`navigator.connection.saveData`](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData) is `true`.\n\n## data-sveltekit-preload-code\n\nEven in cases where you don't want to preload _data_ for a link, it can be beneficial to preload the _code_. The `data-sveltekit-preload-code` attribute works similarly to `data-sveltekit-preload-data`, except that it can take one of four values, in decreasing 'eagerness':\n\n- `\"eager\"` means that links will be preloaded straight away\n- `\"viewport\"` means that links will be preloaded once they enter the viewport\n- `\"hover\"` - as above, except that only code is preloaded\n- `\"tap\"` - as above, except that only code is preloaded\n\nNote that `viewport` and `eager` only apply to links that are present in the DOM immediately following navigation — if a link is added later (in an `{#if ...}` block, for example) it will not be preloaded until triggered by `hover` or `tap`. This is to avoid performance pitfalls resulting from aggressively observing the DOM for changes.\n\n\nAs with `data-sveltekit-preload-data`, this attribute will be ignored if the user has chosen reduced data usage.\n\n## data-sveltekit-reload\n\nOccasionally, we need to tell SvelteKit not to handle a link, but allow the browser to handle it. Adding a `data-sveltekit-reload` attribute to a link...\n\n```html\n<a data-sveltekit-reload href=\"/path\">Path</a>\n```\n\n...will cause a full-page navigation when the link is clicked.\n\nLinks with a `rel=\"external\"` attribute will receive the same treatment. In addition, they will be ignored during [prerendering](page-options#prerender).\n\n## data-sveltekit-replacestate\n\nSometimes you don't want navigation to create a new entry in the browser's session history. Adding a `data-sveltekit-replacestate` attribute to a link...\n\n```html\n<a data-sveltekit-replacestate href=\"/path\">Path</a>\n```\n\n...will replace the current `history` entry rather than creating a new one with `pushState` when the link is clicked.\n\n## data-sveltekit-keepfocus\n\nSometimes you don't want [focus to be reset](accessibility#Focus-management) after navigation. For example, maybe you have a search form that submits as the user is typing, and you want to keep focus on the text input.  Adding a `data-sveltekit-keepfocus` attribute to it...\n\n```html\n<form data-sveltekit-keepfocus>\n\t<input type=\"text\" name=\"query\">\n</form>\n```\n\n...will cause the currently focused element to retain focus after navigation. In general, avoid using this attribute on links, since the focused element would be the `<a>` tag (and not a previously focused element) and screen reader and other assistive technology users often expect focus to be moved after a navigation. You should also only use this attribute on elements that still exist after navigation. If the element no longer exists, the user's focus will be lost, making for a confusing experience for assistive technology users.\n\n## data-sveltekit-noscroll\n\nWhen navigating to internal links, SvelteKit mirrors the browser's default navigation behaviour: it will change the scroll position to 0,0 so that the user is at the very top left of the page (unless the link includes a `#hash`, in which case it will scroll to the element with a matching ID).\n\nIn certain cases, you may wish to disable this behaviour. Adding a `data-sveltekit-noscroll` attribute to a link...\n\n```html\n<a href=\"path\" data-sveltekit-noscroll>Path</a>\n```\n\n...will prevent scrolling after the link is clicked.\n\n## Disabling options\n\nTo disable any of these options inside an element where they have been enabled, use the `\"false\"` value:\n\n```html\n<div data-sveltekit-preload-data>\n\t<!-- these links will be preloaded -->\n\t<a href=\"/a\">a</a>\n\t<a href=\"/b\">b</a>\n\t<a href=\"/c\">c</a>\n\n\t<div data-sveltekit-preload-data=\"false\">\n\t\t<!-- these links will NOT be preloaded -->\n\t\t<a href=\"/d\">d</a>\n\t\t<a href=\"/e\">e</a>\n\t\t<a href=\"/f\">f</a>\n\t</div>\n</div>\n```\n\nTo apply an attribute to an element conditionally, do this:\n\n```svelte\n<div data-sveltekit-preload-data={condition ? 'hover' : false}>\n```","size_bytes":6469,"metadata":{"title":"Link options"},"created_at":"2025-07-18T15:47:38.811Z","updated_at":"2025-07-18T15:47:40.078Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/40-service-workers.md","title":"Service workers","filename":"40-service-workers.md","content":"Service workers act as proxy servers that handle network requests inside your app. This makes it possible to make your app work offline, but even if you don't need offline support (or can't realistically implement it because of the type of app you're building), it's often worth using service workers to speed up navigation by precaching your built JS and CSS.\n\nIn SvelteKit, if you have a `src/service-worker.js` file (or `src/service-worker/index.js`) it will be bundled and automatically registered.\n\nYou can [disable automatic registration](configuration#serviceWorker) if you need to register the service worker with your own logic or use another solution. The default registration looks something like this:\n\n```js\nif ('serviceWorker' in navigator) {\n\taddEventListener('load', function () {\n\t\tnavigator.serviceWorker.register('./path/to/service-worker.js');\n\t});\n}\n```\n\n## Inside the service worker\n\nInside the service worker you have access to the [`$service-worker` module]($service-worker), which provides you with the paths to all static assets, build files and prerendered pages. You're also provided with an app version string, which you can use for creating a unique cache name, and the deployment's `base` path. If your Vite config specifies `define` (used for global variable replacements), this will be applied to service workers as well as your server/client builds.\n\nThe following example caches the built app and any files in `static` eagerly, and caches all other requests as they happen. This would make each page work offline once visited.\n\n```js\n/// file: src/service-worker.js\n// Disables access to DOM typings like `HTMLElement` which are not available\n// inside a service worker and instantiates the correct globals\n/// <reference no-default-lib=\"true\"/>\n/// <reference lib=\"esnext\" />\n/// <reference lib=\"webworker\" />\n\n// Ensures that the `$service-worker` import has proper type definitions\n/// <reference types=\"@sveltejs/kit\" />\n\n// Only necessary if you have an import from `$env/static/public`\n/// <reference types=\"../.svelte-kit/ambient.d.ts\" />\n\nimport { build, files, version } from '$service-worker';\n\n// This gives `self` the correct types\nconst self = /** @type {ServiceWorkerGlobalScope} */ (/** @type {unknown} */ (globalThis.self));\n\n// Create a unique cache name for this deployment\nconst CACHE = `cache-${version}`;\n\nconst ASSETS = [\n\t...build, // the app itself\n\t...files  // everything in `static`\n];\n\nself.addEventListener('install', (event) => {\n\t// Create a new cache and add all files to it\n\tasync function addFilesToCache() {\n\t\tconst cache = await caches.open(CACHE);\n\t\tawait cache.addAll(ASSETS);\n\t}\n\n\tevent.waitUntil(addFilesToCache());\n});\n\nself.addEventListener('activate', (event) => {\n\t// Remove previous cached data from disk\n\tasync function deleteOldCaches() {\n\t\tfor (const key of await caches.keys()) {\n\t\t\tif (key !== CACHE) await caches.delete(key);\n\t\t}\n\t}\n\n\tevent.waitUntil(deleteOldCaches());\n});\n\nself.addEventListener('fetch', (event) => {\n\t// ignore POST requests etc\n\tif (event.request.method !== 'GET') return;\n\n\tasync function respond() {\n\t\tconst url = new URL(event.request.url);\n\t\tconst cache = await caches.open(CACHE);\n\n\t\t// `build`/`files` can always be served from the cache\n\t\tif (ASSETS.includes(url.pathname)) {\n\t\t\tconst response = await cache.match(url.pathname);\n\n\t\t\tif (response) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t}\n\n\t\t// for everything else, try the network first, but\n\t\t// fall back to the cache if we're offline\n\t\ttry {\n\t\t\tconst response = await fetch(event.request);\n\n\t\t\t// if we're offline, fetch can return a value that is not a Response\n\t\t\t// instead of throwing - and we can't pass this non-Response to respondWith\n\t\t\tif (!(response instanceof Response)) {\n\t\t\t\tthrow new Error('invalid response from fetch');\n\t\t\t}\n\n\t\t\tif (response.status === 200) {\n\t\t\t\tcache.put(event.request, response.clone());\n\t\t\t}\n\n\t\t\treturn response;\n\t\t} catch (err) {\n\t\t\tconst response = await cache.match(event.request);\n\n\t\t\tif (response) {\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// if there's no cache, then just error out\n\t\t\t// as there is nothing we can do to respond to this request\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tevent.respondWith(respond());\n});\n```\n\n\n## During development\n\nThe service worker is bundled for production, but not during development. For that reason, only browsers that support [modules in service workers](https://web.dev/es-modules-in-sw) will be able to use them at dev time. If you are manually registering your service worker, you will need to pass the `{ type: 'module' }` option in development:\n\n```js\nimport { dev } from '$app/environment';\n\nnavigator.serviceWorker.register('/service-worker.js', {\n\ttype: dev ? 'module' : 'classic'\n});\n```\n\n\n## Other solutions\n\nSvelteKit's service worker implementation is designed to be easy to work with and is probably a good solution for most users. However, outside of SvelteKit, many PWA applications leverage the [Workbox](https://web.dev/learn/pwa/workbox) library. If you're used to using Workbox you may prefer [Vite PWA plugin](https://vite-pwa-org.netlify.app/frameworks/sveltekit.html).\n\n## References\n\nFor more general information on service workers, we recommend [the MDN web docs](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers).","size_bytes":5327,"metadata":{"title":"Service workers"},"created_at":"2025-07-18T15:47:38.812Z","updated_at":"2026-02-21T14:00:04.067Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/50-server-only-modules.md","title":"Server-only modules","filename":"50-server-only-modules.md","content":"Like a good friend, SvelteKit keeps your secrets. When writing your backend and frontend in the same repository, it can be easy to accidentally import sensitive data into your front-end code (environment variables containing API keys, for example). SvelteKit provides a way to prevent this entirely: server-only modules.\n\n## Private environment variables\n\nThe [`$env/static/private`]($env-static-private) and [`$env/dynamic/private`]($env-dynamic-private) modules can only be imported into modules that only run on the server, such as [`hooks.server.js`](hooks#Server-hooks) or [`+page.server.js`](routing#page-page.server.js).\n\n## Server-only utilities\n\nThe [`$app/server`]($app-server) module, which contains a [`read`]($app-server#read) function for reading assets from the filesystem, can likewise only be imported by code that runs on the server.\n\n## Your modules\n\nYou can make your own modules server-only in two ways:\n\n- adding `.server` to the filename, e.g. `secrets.server.js`\n- placing them in `$lib/server`, e.g. `$lib/server/secrets.js`\n\n## How it works\n\nAny time you have public-facing code that imports server-only code (whether directly or indirectly)...\n\n```js\n// @errors: 7005\n/// file: $lib/server/secrets.js\nexport const atlantisCoordinates = [/* redacted */];\n```\n\n```js\n// @errors: 2307 7006 7005\n/// file: src/routes/utils.js\nexport { atlantisCoordinates } from '$lib/server/secrets.js';\n\nexport const add = (a, b) => a + b;\n```\n\n```html\n/// file: src/routes/+page.svelte\n<script>\n\timport { add } from './utils.js';\n</script>\n```\n\n...SvelteKit will error:\n\n```\nCannot import $lib/server/secrets.ts into code that runs in the browser, as this could leak sensitive information.\n\n src/routes/+page.svelte imports\n  src/routes/utils.js imports\n   $lib/server/secrets.ts\n\nIf you're only using the import as a type, change it to `import type`.\n```\n\nEven though the public-facing code — `src/routes/+page.svelte` — only uses the `add` export and not the secret `atlantisCoordinates` export, the secret code could end up in JavaScript that the browser downloads, and so the import chain is considered unsafe.\n\nThis feature also works with dynamic imports, even interpolated ones like ``await import(`./${foo}.js`)``.\n\n\n## Further reading\n\n- [Tutorial: Environment variables](/tutorial/kit/env-static-private)","size_bytes":2364,"metadata":{"title":"Server-only modules"},"created_at":"2025-07-18T15:47:38.814Z","updated_at":"2025-08-19T02:00:04.597Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/65-snapshots.md","title":"Snapshots","filename":"65-snapshots.md","content":"Ephemeral DOM state — like scroll positions on sidebars, the content of `<input>` elements and so on — is discarded when you navigate from one page to another.\n\nFor example, if the user fills out a form but navigates away and then back before submitting, or if the user refreshes the page, the values they filled in will be lost. In cases where it's valuable to preserve that input, you can take a _snapshot_ of DOM state, which can then be restored if the user navigates back.\n\nTo do this, export a `snapshot` object with `capture` and `restore` methods from a `+page.svelte` or `+layout.svelte`:\n\n```svelte\n<!file: +page.svelte>\n<script>\n\tlet comment = $state('');\n\n\t/** @type {import('./$types').Snapshot<string>} */\n\texport const snapshot = {\n\t\tcapture: () => comment,\n\t\trestore: (value) => comment = value\n\t};\n</script>\n\n<form method=\"POST\">\n\t<label for=\"comment\">Comment</label>\n\t<textarea id=\"comment\" bind:value={comment} />\n\t<button>Post comment</button>\n</form>\n```\n\nWhen you navigate away from this page, the `capture` function is called immediately before the page updates, and the returned value is associated with the current entry in the browser's history stack. If you navigate back, the `restore` function is called with the stored value as soon as the page is updated.\n\nThe data must be serializable as JSON so that 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.","size_bytes":1524,"metadata":{"title":"Snapshots"},"created_at":"2025-07-18T15:47:38.814Z","updated_at":"2025-07-18T15:47:40.084Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/67-shallow-routing.md","title":"Shallow routing","filename":"67-shallow-routing.md","content":"As you navigate around a SvelteKit app, you create _history entries_. Clicking the back and forward buttons traverses through this list of entries, re-running any `load` functions and replacing page components as necessary.\n\nSometimes, it's useful to create history entries _without_ navigating. For example, you might want to show a modal dialog that the user can dismiss by navigating back. This is particularly valuable on mobile devices, where swipe gestures are often more natural than interacting directly with the UI. In these cases, a modal that is _not_ associated with a history entry can be a source of frustration, as a user may swipe backwards in an attempt to dismiss it and find themselves on the wrong page.\n\nSvelteKit makes this possible with the [`pushState`]($app-navigation#pushState) and [`replaceState`]($app-navigation#replaceState) functions, which allow you to associate state with a history entry without navigating. For example, to implement a history-driven modal:\n\n```svelte\n<!file: +page.svelte>\n<script>\n\timport { pushState } from '$app/navigation';\n\timport { page } from '$app/state';\n\timport Modal from './Modal.svelte';\n\n\tfunction showModal() {\n\t\tpushState('', {\n\t\t\tshowModal: true\n\t\t});\n\t}\n</script>\n\n{#if page.state.showModal}\n\t<Modal close={() => history.back()} />\n{/if}\n```\n\nThe modal can be dismissed by navigating back (unsetting `page.state.showModal`) or by interacting with it in a way that causes the `close` callback to run, which will navigate back programmatically.\n\n## API\n\nThe first argument to `pushState` is the URL, relative to the current URL. To stay on the current URL, use `''`.\n\nThe second argument is the new page state, which can be accessed via the [page object]($app-state#page) as `page.state`. You can make page state type-safe by declaring an [`App.PageState`](types#PageState) interface (usually in `src/app.d.ts`).\n\nTo set page state without creating a new history entry, use `replaceState` instead of `pushState`.\n\n> [!LEGACY]\n> `page.state` from `$app/state` was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use `$page.state` from `$app/stores` instead.\n\n## Loading data for a route\n\nWhen shallow routing, you may want to render another `+page.svelte` inside the current page. For example, clicking on a photo thumbnail could pop up the detail view without navigating to the photo page.\n\nFor this to work, you need to load the data that the `+page.svelte` expects. A convenient way to do this is to use [`preloadData`]($app-navigation#preloadData) inside the `click` handler of an `<a>` element. If the element (or a parent) uses [`data-sveltekit-preload-data`](link-options#data-sveltekit-preload-data), the data will have already been requested, and `preloadData` will reuse that request.\n\n```svelte\n<!file: src/routes/photos/+page.svelte>\n<script>\n\timport { preloadData, pushState, goto } from '$app/navigation';\n\timport { page } from '$app/state';\n\timport Modal from './Modal.svelte';\n\timport PhotoPage from './[id]/+page.svelte';\n\n\tlet { data } = $props();\n</script>\n\n{#each data.thumbnails as thumbnail}\n\t<a\n\t\thref=\"/photos/{thumbnail.id}\"\n\t\tonclick={async (e) => {\n\t\t\tif (innerWidth < 640        // bail if the screen is too small\n\t\t\t\t|| e.shiftKey             // or the link is opened in a new window\n\t\t\t\t|| e.metaKey || e.ctrlKey // or a new tab (mac: metaKey, win/linux: ctrlKey)\n\t\t\t\t// should also consider clicking with a mouse scroll wheel\n\t\t\t) return;\n\n\t\t\t// prevent navigation\n\t\t\te.preventDefault();\n\n\t\t\tconst { href } = e.currentTarget;\n\n\t\t\t// run `load` functions (or rather, get the result of the `load` functions\n\t\t\t// that are already running because of `data-sveltekit-preload-data`)\n\t\t\tconst result = await preloadData(href);\n\n\t\t\tif (result.type === 'loaded' && result.status === 200) {\n\t\t\t\tpushState(href, { selected: result.data });\n\t\t\t} else {\n\t\t\t\t// something bad happened! try navigating\n\t\t\t\tgoto(href);\n\t\t\t}\n\t\t}}\n\t>\n\t\t<img alt={thumbnail.alt} src={thumbnail.src} />\n\t</a>\n{/each}\n\n{#if page.state.selected}\n\t<Modal onclose={() => history.back()}>\n\t\t<!-- pass page data to the +page.svelte component,\n\t\t     just like SvelteKit would on navigation -->\n\t\t<PhotoPage data={page.state.selected} />\n\t</Modal>\n{/if}\n```\n\n## Caveats\n\nDuring server-side rendering, `page.state` is always an empty object. The same is true for the first page the user lands on — if the user reloads the page (or returns from another document), state will _not_ be applied until they navigate.\n\nShallow routing is a feature that requires JavaScript to work. Be mindful when using it and try to think of sensible fallback behavior in case JavaScript isn't available.","size_bytes":4708,"metadata":{"title":"Shallow routing"},"created_at":"2025-07-18T15:47:38.816Z","updated_at":"2025-07-18T15:47:40.086Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/68-observability.md","title":"Observability","filename":"68-observability.md","content":"<blockquote class=\"since note\">\n\t<p>Available since 2.31</p>\n</blockquote>\n\nSometimes, you may need to observe how your application is behaving in order to improve performance or find the root cause of a pesky bug. To help with this, SvelteKit can emit server-side [OpenTelemetry](https://opentelemetry.io) spans for the following:\n\n- The [`handle`](hooks#Server-hooks-handle) hook and `handle` functions running in a [`sequence`](@sveltejs-kit-hooks#sequence) (these will show up as children of each other and the root `handle` hook)\n- Server [`load`](load) functions and universal `load` functions when they're run on the server\n- [Form actions](form-actions)\n- [Remote functions](remote-functions)\n\nJust telling SvelteKit to emit spans won't get you far, though — you need to actually collect them somewhere to be able to view them. SvelteKit provides `src/instrumentation.server.ts` as a place to write your tracing setup and instrumentation code. It's guaranteed to be run prior to your application code being imported, providing your deployment platform supports it and your adapter is aware of it.\n\nBoth of these features are currently experimental, meaning they are likely to contain bugs and are subject to change without notice. You must opt in by adding the `kit.experimental.tracing.server` and `kit.experimental.instrumentation.server` option in your `svelte.config.js`:\n\n```js\n/// file: svelte.config.js\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\texperimental: {\n\t\t\ttracing: {\n\t\t\t\tserver: true\n\t\t\t},\n\t\t\tinstrumentation: {\n\t\t\t\tserver: true\n\t\t\t}\n\t\t}\n\t}\n};\n\nexport default config;\n```\n\n\n## Augmenting the built-in tracing\n\nSvelteKit provides access to the `root` span and the `current` span on the request event. The root span is the one associated with your root `handle` function, and the current span could be associated with `handle`, `load`, a form action, or a remote function, depending on the context. You can annotate these spans with any attributes you wish to record:\n\n```js\n/// file: $lib/authenticate.ts\n\n// @filename: ambient.d.ts\ndeclare module '$lib/auth-core' {\n\texport function getAuthenticatedUser(): Promise<{ id: string }>\n}\n\n// @filename: index.js\n//cut\nimport { getRequestEvent } from '$app/server';\nimport { getAuthenticatedUser } from '$lib/auth-core';\n\nasync function authenticate() {\n\tconst user = await getAuthenticatedUser();\n\tconst event = getRequestEvent();\n\tevent.tracing.root.setAttribute('userId', user.id);\n}\n```\n\n## Development quickstart\n\nTo view your first trace, you'll need to set up a local collector. We'll use [Jaeger](https://www.jaegertracing.io/docs/getting-started/) in this example, as they provide an easy-to-use quickstart command. Once your collector is running locally:\n\n- Turn on the experimental flags mentioned earlier in your `svelte.config.js` file\n- Use your package manager to install the dependencies you'll need:\n  ```sh\n  npm i @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-proto import-in-the-middle\n  ```\n- Create `src/instrumentation.server.js` with the following:\n\n```js\n/// file: src/instrumentation.server.js\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';\nimport { createAddHookMessageChannel } from 'import-in-the-middle';\nimport { register } from 'node:module';\n\nconst { registerOptions } = createAddHookMessageChannel();\nregister('import-in-the-middle/hook.mjs', import.meta.url, registerOptions);\n\nconst sdk = new NodeSDK({\n\tserviceName: 'test-sveltekit-tracing',\n\ttraceExporter: new OTLPTraceExporter(),\n\tinstrumentations: [getNodeAutoInstrumentations()]\n});\n\nsdk.start();\n```\n\nNow, server-side requests will begin generating traces, which you can view in Jaeger's web console at [localhost:16686](http://localhost:16686).\n\n## `@opentelemetry/api`\n\nSvelteKit uses `@opentelemetry/api` to generate its spans. This is declared as an optional peer dependency so that users not needing traces see no impact on install size or runtime performance. In most cases, if you're configuring your application to collect SvelteKit's spans, you'll end up installing a library like `@opentelemetry/sdk-node` or `@vercel/otel`, which in turn depend on `@opentelemetry/api`, which will satisfy SvelteKit's dependency as well. If you see an error from SvelteKit telling you it can't find `@opentelemetry/api`, it may just be because you haven't set up your trace collection yet. If you _have_ done that and are still seeing the error, you can install `@opentelemetry/api` yourself.","size_bytes":4736,"metadata":{"title":"Observability"},"created_at":"2025-08-16T14:00:05.341Z","updated_at":"2025-08-27T14:00:04.688Z"},{"path":"apps/svelte.dev/content/docs/kit/30-advanced/70-packaging.md","title":"Packaging","filename":"70-packaging.md","content":"You can use SvelteKit to build apps as well as component libraries, using the `@sveltejs/package` package (`npx sv create` has an option to set this up for you).\n\nWhen you're creating an app, the contents of `src/routes` is the public-facing stuff; [`src/lib`]($lib) contains your app's internal library.\n\nA component library has the exact same structure as a SvelteKit app, except that `src/lib` is the public-facing bit, and your root `package.json` is used to publish the package. `src/routes` might be a documentation or demo site that accompanies the library, or it might just be a sandbox you use during development.\n\nRunning the `svelte-package` command from `@sveltejs/package` will take the contents of `src/lib` and generate a `dist` directory (which can be [configured](#Options)) containing the following:\n\n- All the files in `src/lib`. Svelte components will be preprocessed, TypeScript files will be transpiled to JavaScript.\n- Type definitions (`d.ts` files) which are generated for Svelte, JavaScript and TypeScript files. You need to install `typescript >= 4.0.0` for this. Type definitions are placed next to their implementation, hand-written `d.ts` files are copied over as is. You can [disable generation](#Options), but we strongly recommend against it — people using your library might use TypeScript, for which they require these type definition files.\n\n\n## Anatomy of a package.json\n\nSince you're now building a library for public use, the contents of your `package.json` will become more important. Through it, you configure the entry points of your package, which files are published to npm, and which dependencies your library has. Let's go through the most important fields one by one.\n\n### name\n\nThis is the name of your package. It will be available for others to install using that name, and visible on `https://npmjs.com/package/<name>`.\n\n```json\n{\n\t\"name\": \"your-library\"\n}\n```\n\nRead more about it [here](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#name).\n\n### license\n\nEvery package should have a license field so people know how they are allowed to use it. A very popular license which is also very permissive in terms of distribution and reuse without warranty is `MIT`.\n\n```json\n{\n\t\"license\": \"MIT\"\n}\n```\n\nRead more about it [here](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#license). Note that you should also include a `LICENSE` file in your package.\n\n### files\n\nThis tells npm which files it will pack up and upload to npm. It should contain your output folder (`dist` by default). Your `package.json` and `README` and `LICENSE` will always be included, so you don't need to specify them.\n\n```json\n{\n\t\"files\": [\"dist\"]\n}\n```\n\nTo exclude unnecessary files (such as unit tests, or modules that are only imported from `src/routes` etc) you can add them to an `.npmignore` file. This will result in smaller packages that are faster to install.\n\nRead more about it [here](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#files).\n\n### exports\n\nThe `\"exports\"` field contains the package's entry points. If you set up a new library project through `npx sv create`, it's set to a single export, the package root:\n\n```json\n{\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"types\": \"./dist/index.d.ts\",\n\t\t\t\"svelte\": \"./dist/index.js\"\n\t\t}\n\t}\n}\n```\n\nThis tells bundlers and tooling that your package only has one entry point, the root, and everything should be imported through that, like this:\n\n```js\n// @errors: 2307\nimport { Something } from 'your-library';\n```\n\nThe `types` and `svelte` keys are [export conditions](https://nodejs.org/api/packages.html#conditional-exports). They tell tooling what file to import when they look up the `your-library` import:\n\n- TypeScript sees the `types` condition and looks up the type definition file. If you don't publish type definitions, omit this condition.\n- Svelte-aware tooling sees the `svelte` condition and knows this is a Svelte component library. If you publish a library that does not export any Svelte components and that could also work in non-Svelte projects (for example a Svelte store library), you can replace this condition with `default`.\n\n\nYou can adjust `exports` to your liking and provide more entry points. For example, if instead of a `src/lib/index.js` file that re-exported components you wanted to expose a `src/lib/Foo.svelte` component directly, you could create the following export map...\n\n```json\n{\n\t\"exports\": {\n\t\t\"./Foo.svelte\": {\n\t\t\t\"types\": \"./dist/Foo.svelte.d.ts\",\n\t\t\t\"svelte\": \"./dist/Foo.svelte\"\n\t\t}\n\t}\n}\n```\n\n...and a consumer of your library could import the component like so:\n\n```js\n// @filename: ambient.d.ts\ndeclare module 'your-library/Foo.svelte';\n\n// @filename: index.js\n//cut\nimport Foo from 'your-library/Foo.svelte';\n```\n\n\nIn general, each key of the exports map is the path the user will have to use to import something from your package, and the value is the path to the file that will be imported or a map of export conditions which in turn contains these file paths.\n\nRead more about `exports` [here](https://nodejs.org/docs/latest-v18.x/api/packages.html#package-entry-points).\n\n### svelte\n\nThis is a legacy field that enabled tooling to recognise Svelte component libraries. It's no longer necessary when using the `svelte` [export condition](#Anatomy-of-a-package.json-exports), but for backwards compatibility with outdated tooling that doesn't yet know about export conditions it's good to keep it around. It should point towards your root entry point.\n\n```json\n{\n\t\"svelte\": \"./dist/index.js\"\n}\n```\n\n### sideEffects\n\nThe `sideEffects` field in `package.json` is used by bundlers to determine if a module may contain code that has side effects. A module is considered to have side effects if it makes changes that are observable from other scripts outside the module when it's imported. For example, side effects include modifying global variables or the prototype of built-in JavaScript objects. Because a side effect could potentially affect the behavior of other parts of the application, these files/modules will be included in the final bundle regardless of whether their exports are used in the application. It is a best practice to avoid side effects in your code.\n\nSetting the `sideEffects` field in `package.json` can help the bundler to be more aggressive in eliminating unused exports from the final bundle, a process known as tree-shaking. This results in smaller and more efficient bundles. Different bundlers handle `sideEffects` in various manners. While not necessary for Vite, we recommend that libraries state that all CSS files have side effects so that your library will be [compatible with webpack](https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free). This is the configuration that comes with newly created projects:\n\n```json\n/// file: package.json\n{\n\t\"sideEffects\": [\"**/*.css\"]\n}\n```\n\n\nIf your package has files with side effects, you can specify them in an array:\n\n```json\n/// file: package.json\n{\n    \"sideEffects\": [\n    \t\"**/*.css\",\n    \t\"./dist/sideEffectfulFile.js\"\n    ]\n}\n```\n\nThis will treat only the specified files as having side effects.\n\n## TypeScript\n\nYou should ship type definitions for your library even if you don't use TypeScript yourself so that people who do get proper intellisense when using your library. `@sveltejs/package` makes the process of generating types mostly opaque to you. By default, when packaging your library, type definitions are auto-generated for JavaScript, TypeScript and Svelte files. All you need to ensure is that the `types` condition in the [exports](#Anatomy-of-a-package.json-exports) map points to the correct files. When initialising a library project through `npx sv create`, this is automatically set up for the root export.\n\nIf you have something else than a root export however — for example providing a `your-library/foo` import — you need to take additional care for providing type definitions. Unfortunately, TypeScript by default will _not_ resolve the `types` condition for an export like `{ \"./foo\": { \"types\": \"./dist/foo.d.ts\", ... }}`. Instead, it will search for a `foo.d.ts` relative to the root of your library (i.e. `your-library/foo.d.ts` instead of `your-library/dist/foo.d.ts`). To fix this, you have two options:\n\nThe first option is to require people using your library to set the `moduleResolution` option in their `tsconfig.json` (or `jsconfig.json`) to `bundler` (available since TypeScript 5, the best and recommended option in the future), `node16` or `nodenext`. This opts TypeScript into actually looking at the exports map and resolving the types correctly.\n\nThe second option is to (ab)use the `typesVersions` feature from TypeScript to wire up the types. This is a field inside `package.json` TypeScript uses to check for different type definitions depending on the TypeScript version, and also contains a path mapping feature for that. We leverage that path mapping feature to get what we want. For the mentioned `foo` export above, the corresponding `typesVersions` looks like this:\n\n```json\n{\n\t\"exports\": {\n\t\t\"./foo\": {\n\t\t\t\"types\": \"./dist/foo.d.ts\",\n\t\t\t\"svelte\": \"./dist/foo.js\"\n\t\t}\n\t},\n\t\"typesVersions\": {\n\t\t\">4.0\": {\n\t\t\t\"foo\": [\"./dist/foo.d.ts\"]\n\t\t}\n\t}\n}\n```\n\n`>4.0` tells TypeScript to check the inner map if the used TypeScript version is greater than 4 (which should in practice always be true). The inner map tells TypeScript that the typings for `your-library/foo` are found within `./dist/foo.d.ts`, which essentially replicates the `exports` condition. You also have `*` as a wildcard at your disposal to make many type definitions at once available without repeating yourself. Note that if you opt into `typesVersions` you have to declare all type imports through it, including the root import (which is defined as `\"index.d.ts\": [..]`).\n\nYou can read more about that feature [here](https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html#version-selection-with-typesversions).\n\n## Best practices\n\nYou should avoid using SvelteKit-specific modules like `$app/environment` in your packages unless you intend for them to only be consumable by other SvelteKit projects. E.g. rather than using `import { browser } from '$app/environment'` you could use `import { BROWSER } from 'esm-env'` ([see esm-env docs](https://github.com/benmccann/esm-env)). You may also wish to pass in things like the current URL or a navigation action as a prop rather than relying directly on `$app/state`, `$app/navigation`, etc. Writing your app in this more generic fashion will also make it easier to set up tools for testing, UI demos and so on.\n\nEnsure that you add [aliases](configuration#alias) via `svelte.config.js` (not `vite.config.js` or `tsconfig.json`), so that they are processed by `svelte-package`.\n\nYou should think carefully about whether or not the changes you make to your package are a bug fix, a new feature, or a breaking change, and update the package version accordingly. Note that if you remove any paths from `exports` or any `export` conditions inside them from your existing library, that should be regarded as a breaking change.\n\n```json\n{\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"types\": \"./dist/index.d.ts\",\n// changing `svelte` to `default` is a breaking change:\n\"svelte\": \"./dist/index.js\"\n\"default\": \"./dist/index.js\"\n\t\t},\n// removing this is a breaking change:\n\"./foo\": {\n\t\t\t\"types\": \"./dist/foo.d.ts\",\n\t\t\t\"svelte\": \"./dist/foo.js\",\n\t\t\t\"default\": \"./dist/foo.js\"\n\t\t},\n// adding this is ok:\n\"./bar\": {\n\t\t\t\"types\": \"./dist/bar.d.ts\",\n\t\t\t\"svelte\": \"./dist/bar.js\",\n\t\t\t\"default\": \"./dist/bar.js\"\n\t\t}\n\t}\n}\n```\n\n## Source maps\n\nYou can create so-called declaration maps (`d.ts.map` files) by setting `\"declarationMap\": true` in your `tsconfig.json`. This will allow editors such as VS Code to go to the original `.ts` or `.svelte` file when using features like _Go to Definition_. This means you also need to publish your source files alongside your dist folder in a way that the relative path inside the declaration files leads to a file on disk. Assuming that you have all your library code inside `src/lib` as suggested by Svelte's CLI, this is as simple as adding `src/lib` to `files` in your `package.json`:\n\n```json\n{\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"!dist/**/*.test.*\",\n\t\t\"!dist/**/*.spec.*\",\n\t\t\"src/lib\",\n\t\t\"!src/lib/**/*.test.*\",\n\t\t\"!src/lib/**/*.spec.*\"\n\t]\n}\n```\n\n## Options\n\n`svelte-package` accepts the following options:\n\n- `-w`/`--watch` — watch files in `src/lib` for changes and rebuild the package\n- `-i`/`--input` — the input directory which contains all the files of the package. Defaults to `src/lib`\n- `-o`/`--output` — the output directory where the processed files are written to. Your `package.json`'s `exports` should point to files inside there, and the `files` array should include that folder. Defaults to `dist`\n- `-p`/`--preserve-output` — prevent deletion of the output directory before packaging. Defaults to `false`, which means that the output directory will be emptied first\n- `-t`/`--types` — whether or not to create type definitions (`d.ts` files). We strongly recommend doing this as it fosters ecosystem library quality. Defaults to `true`\n- `--tsconfig` - the path to a tsconfig or jsconfig. When not provided, searches for the next upper tsconfig/jsconfig in the workspace path.\n\n## Publishing\n\nTo publish the generated package:\n\n```sh\nnpm publish\n```\n\n## Caveats\n\nAll relative file imports need to be fully specified, adhering to Node's ESM algorithm. This means that for a file like `src/lib/something/index.js`, you must include the filename with the extension:\n\n```js\n// @errors: 2307\nimport { something } from './something/index.js';\n```\n\nIf you are using TypeScript, you need to import `.ts` files the same way, but using a `.js` file ending, _not_ a `.ts` file ending. (This is a TypeScript design decision outside our control.) Setting `\"moduleResolution\": \"NodeNext\"` in your `tsconfig.json` or `jsconfig.json` will help you with this.\n\nAll files except Svelte files (preprocessed) and TypeScript files (transpiled to JavaScript) are copied across as-is.","size_bytes":14159,"metadata":{"title":"Packaging"},"created_at":"2025-07-18T15:47:38.817Z","updated_at":"2026-02-14T01:33:24.853Z"},{"path":"apps/svelte.dev/content/docs/kit/40-best-practices/03-auth.md","title":"Auth","filename":"03-auth.md","content":"Auth refers to authentication and authorization, which are common needs when building a web application. Authentication means verifying that the user is who they say they are based on their provided credentials. Authorization means determining which actions they are allowed to take.\n\n## Sessions vs tokens\n\nAfter the user has provided their credentials such as a username and password, we want to allow them to use the application without needing to provide their credentials again for future requests. Users are commonly authenticated on subsequent requests with either a session identifier or signed token such as a JSON Web Token (JWT).\n\nSession IDs are most commonly stored in a database. They can be immediately revoked, but require a database query to be made on each request.\n\nIn contrast, JWT generally are not checked against a datastore, which means they cannot be immediately revoked. The advantage of this method is improved latency and reduced load on your datastore.\n\n## Integration points\n\nAuth [cookies](@sveltejs-kit#Cookies) can be checked inside [server hooks](hooks#Server-hooks). If a user is found matching the provided credentials, the user information can be stored in [`locals`](hooks#Server-hooks-locals).\n\n## Libraries\n\nThe [Svelte CLI](/docs/cli) gives the option to [set up Better Auth](https://svelte.dev/docs/cli/better-auth) with a new project or add it to an existing project.\n\n## Guides\n\nIf you'd like to implement your own auth system, [the Lucia auth guide](https://lucia-auth.com/) provides a reference for session-based web app auth with SvelteKit examples.","size_bytes":1618,"metadata":{"title":"Auth"},"created_at":"2025-07-18T15:47:38.821Z","updated_at":"2026-02-26T02:00:03.903Z"},{"path":"apps/svelte.dev/content/docs/kit/40-best-practices/05-performance.md","title":"Performance","filename":"05-performance.md","content":"Out of the box, SvelteKit does a lot of work to make your applications as performant as possible:\n\n- Code-splitting, so that only the code you need for the current page is loaded\n- Asset preloading, so that 'waterfalls' (of files requesting other files) are prevented\n- File hashing, so that your assets can be cached forever\n- Request coalescing, so that data fetched from separate server `load` functions is grouped into a single HTTP request\n- Parallel loading, so that separate universal `load` functions fetch data simultaneously\n- Data inlining, so that requests made with `fetch` during server rendering can be replayed in the browser without issuing a new request\n- Conservative invalidation, so that `load` functions are only re-run when necessary\n- Prerendering (configurable on a per-route basis, if necessary) so that pages without dynamic data can be served instantaneously\n- Link preloading, so that data and code requirements for a client-side navigation are eagerly anticipated\n\nNevertheless, we can't (yet) eliminate all sources of slowness. To eke out maximum performance, you should be mindful of the following tips.\n\n## Diagnosing issues\n\nGoogle's [PageSpeed Insights](https://pagespeed.web.dev/) and (for more advanced analysis) [WebPageTest](https://www.webpagetest.org/) are excellent ways to understand the performance characteristics of a site that is already deployed to the internet.\n\nYour browser also includes useful developer tools for analysing your site, whether deployed or running locally:\n\n* Chrome - [Lighthouse](https://developer.chrome.com/docs/lighthouse/overview#devtools), [Network](https://developer.chrome.com/docs/devtools/network), and [Performance](https://developer.chrome.com/docs/devtools/performance) devtools\n* Edge - [Lighthouse](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/lighthouse/lighthouse-tool), [Network](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/network/), and [Performance](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/evaluate-performance/) devtools\n* Firefox - [Network](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/) and [Performance](https://hacks.mozilla.org/2022/03/performance-tool-in-firefox-devtools-reloaded/) devtools\n* Safari - [enhancing the performance of your webpage](https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/Web_Inspector_Tutorial/EnhancingyourWebpagesPerformance/EnhancingyourWebpagesPerformance.html)\n\nNote that your site running locally in `dev` mode will exhibit different behaviour than your production app, so you should do performance testing in [preview](building-your-app#Preview-your-app) mode after building.\n\n### Instrumenting\n\nIf you see in the network tab of your browser that an API call is taking a long time and you'd like to understand why, you may consider instrumenting your backend with a tool like [OpenTelemetry](https://opentelemetry.io/) or [Server-Timing headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing).\n\n## Optimizing assets\n\n### Images\n\nReducing the size of image files is often one of the most impactful changes you can make to a site's performance. Svelte provides the `@sveltejs/enhanced-img` package, detailed on the [images](images) page, for making this easier. Additionally, Lighthouse is useful for identifying the worst offenders.\n\n### Videos\n\nVideo files can be very large, so extra care should be taken to ensure that they're optimized:\n\n- Compress videos with tools such as [Handbrake](https://handbrake.fr/). Consider converting the videos to web-friendly formats such as `.webm` or `.mp4`.\n- You can [lazy-load videos](https://web.dev/articles/lazy-loading-video) located below the fold with `preload=\"none\"` (though note that this will slow down playback when the user _does_ initiate it).\n- Strip the audio track out of muted videos using a tool like [FFmpeg](https://ffmpeg.org/).\n\n### Fonts\n\nSvelteKit automatically preloads critical `.js` and `.css` files when the user visits a page, but it does _not_ preload fonts by default, since this may cause unnecessary files (such as font weights that are referenced by your CSS but not actually used on the current page) to be downloaded. Having said that, preloading fonts correctly can make a big difference to how fast your site feels. In your [`handle`](hooks#Server-hooks-handle) hook, you can call `resolve` with a `preload` filter that includes your fonts.\n\nYou can reduce the size of font files by [subsetting](https://web.dev/learn/performance/optimize-web-fonts#subset_your_web_fonts) your fonts.\n\n## Reducing code size\n\n### Svelte version\n\nWe recommend running the latest version of Svelte. Svelte 5 is smaller and faster than Svelte 4, which is smaller and faster than Svelte 3.\n\n### Packages\n\n[`rollup-plugin-visualizer`](https://www.npmjs.com/package/rollup-plugin-visualizer) can be helpful for identifying which packages are contributing the most to the size of your site. You may also find opportunities to remove code by manually inspecting the build output (use `build: { minify: false }` in your [Vite config](https://vitejs.dev/config/build-options.html#build-minify) to make the output readable, but remember to undo that before deploying your app), or via the network tab of your browser's devtools.\n\n### External scripts\n\nTry to minimize the number of third-party scripts running in the browser. For example, instead of using JavaScript-based analytics consider using server-side implementations, such as those offered by many platforms with SvelteKit adapters including [Cloudflare](https://www.cloudflare.com/web-analytics/), [Netlify](https://docs.netlify.com/monitor-sites/site-analytics/), and [Vercel](https://vercel.com/docs/analytics).\n\nTo run third party scripts in a web worker (which avoids blocking the main thread), use [Partytown's SvelteKit integration](https://partytown.builder.io/sveltekit).\n\n### Selective loading\n\nCode imported with static `import` declarations will be automatically bundled with the rest of your page. If there is a piece of code you need only when some condition is met, use the dynamic `import(...)` form to selectively lazy-load the component.\n\n## Navigation\n\n### Preloading\n\nYou can speed up client-side navigations by eagerly preloading the necessary code and data, using [link options](link-options). This is configured by default on the `<body>` element when you create a new SvelteKit app.\n\n### Non-essential data\n\nFor slow-loading data that isn't needed immediately, the object returned from your `load` function can contain promises rather than the data itself. For server `load` functions, this will cause the data to [stream](load#Streaming-with-promises) in after the navigation (or initial page load).\n\n### Preventing waterfalls\n\nOne of the biggest performance killers is what is referred to as a _waterfall_, which is a series of requests that is made sequentially. This can happen on the server or in the browser, but is especially costly when dealing with data that has to travel further or across slower networks, such as a mobile user making a call to a distant server.\n\nIn the browser, waterfalls can occur when your HTML kicks off request chains such as requesting JS which requests CSS which requests a background image and web font. SvelteKit will largely solve this class of problems for you by adding [`modulepreload`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/modulepreload) tags or headers, but you should view [the network tab in your devtools](#Diagnosing-issues) to check whether additional resources need to be preloaded.\n- Pay special attention to this if you use [web fonts](#Optimizing-assets-Fonts) since they need to be handled manually.\n- Enabling [single page app (SPA) mode](single-page-apps) will cause such waterfalls. With SPA mode, an empty page is generated, which fetches JavaScript, which ultimately loads and renders the page. This results in extra network round trips before a single pixel can be displayed.\n\nWaterfalls can also occur on calls to the backend whether made from the browser or server. E.g. if a universal `load` function makes an API call to fetch the current user, then uses the details from that response to fetch a list of saved items, and then uses _that_ response to fetch the details for each item, the browser will end up making multiple sequential requests. This is deadly for performance, especially for users that are physically located far from your backend.\n- Avoid this issue by using [server `load` functions](load#Universal-vs-server) to make requests to backend services that are dependencies from the server rather than from the browser. Note, however, that server `load` functions are also not immune to waterfalls (though they are much less costly since they rarely involve round trips with high latency). For example, if you query a database to get the current user and then use that data to make a second query for a list of saved items, it will typically be more performant to issue a single query with a database join.\n\n## Hosting\n\nYour frontend should be located in the same data center as your backend to minimize latency. For sites with no central backend, many SvelteKit adapters support deploying to the _edge_, which means handling each user's requests from a nearby server. This can reduce load times significantly. Some adapters even support [configuring deployment on a per-route basis](page-options#config). You should also consider serving images from a CDN (which are typically edge networks) — the hosts for many SvelteKit adapters will do this automatically.\n\nEnsure your host uses HTTP/2 or newer. Vite's code splitting creates numerous small files for improved cacheability, which results in excellent performance, but this does assume that your files can be loaded in parallel with HTTP/2.\n\n## Further reading\n\nFor the most part, building a performant SvelteKit app is the same as building any performant web app. You should be able to apply information from general performance resources such as [Core Web Vitals](https://web.dev/explore/learn-core-web-vitals) to any web experience you build.","size_bytes":10280,"metadata":{"title":"Performance"},"created_at":"2025-07-18T15:47:38.822Z","updated_at":"2025-08-20T14:00:05.545Z"},{"path":"apps/svelte.dev/content/docs/kit/40-best-practices/06-icons.md","title":"Icons","filename":"06-icons.md","content":"## CSS\n\nA great way to use icons is to define them purely via CSS. Iconify offers support for [many popular icon sets](https://icon-sets.iconify.design/) that [can be included via CSS](https://iconify.design/docs/usage/css/). This method can also be used with popular CSS frameworks by leveraging the Iconify [Tailwind CSS plugin](https://iconify.design/docs/usage/css/tailwind/) or [UnoCSS plugin](https://iconify.design/docs/usage/css/unocss/). As opposed to libraries based on Svelte components, it doesn't require each icon to be imported into your `.svelte` file.\n\n## Svelte\n\nThere are many [icon libraries for Svelte](/packages#icons). When choosing an icon library, it is recommended to avoid those that provide a `.svelte` file per icon, as these libraries can have thousands of `.svelte` files which really slow down [Vite's dependency optimization](https://vite.dev/guide/dep-pre-bundling.html). This can become especially pathological if the icons are imported both via an umbrella import and subpath import [as described in the `vite-plugin-svelte` FAQ](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#what-is-going-on-with-vite-and-pre-bundling-dependencies).","size_bytes":1216,"metadata":{"title":"Icons"},"created_at":"2025-07-18T15:47:38.825Z","updated_at":"2025-10-31T02:00:10.347Z"},{"path":"apps/svelte.dev/content/docs/kit/40-best-practices/07-images.md","title":"Images","filename":"07-images.md","content":"Images can have a big impact on your app's performance. For best results, you should optimize them by doing the following:\n\n- generate optimal formats like `.avif` and `.webp`\n- create different sizes for different screens\n- ensure that assets can be cached effectively\n\nDoing this manually is tedious. There are a variety of techniques you can use, depending on your needs and preferences.\n\n## Vite's built-in handling\n\n[Vite will automatically process imported assets](https://vitejs.dev/guide/assets.html) for improved performance. This includes assets referenced via the CSS `url()` function. Hashes will be added to the filenames so that they can be cached, and assets smaller than `assetsInlineLimit` will be inlined. Vite's asset handling is most often used for images, but is also useful for video, audio, etc.\n\n```svelte\n<script>\n\timport logo from '$lib/assets/logo.png';\n</script>\n\n<img alt=\"The project logo\" src={logo} />\n```\n\n## @sveltejs/enhanced-img\n\n`@sveltejs/enhanced-img` is a plugin offered on top of Vite's built-in asset handling. It provides plug and play image processing that serves smaller file formats like `avif` or `webp`, automatically sets the intrinsic `width` and `height` of the image to avoid layout shift, creates images of multiple sizes for various devices, and strips EXIF data for privacy. It will work in any Vite-based project including, but not limited to, SvelteKit projects.\n\n\n### Setup\n\nInstall:\n\n```sh\nnpm i -D @sveltejs/enhanced-img\n```\n\nAdjust `vite.config.js`:\n\n```js\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { enhancedImages } from '@sveltejs/enhanced-img';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n\tplugins: [\n\t\tenhancedImages(), // must come before the SvelteKit plugin\n\t\tsveltekit()\n\t]\n});\n```\n\nBuilding will take longer on the first build due to the computational expense of transforming images. However, the build output will be cached in `./node_modules/.cache/imagetools` so that subsequent builds will be fast.\n\n### Basic usage\n\nUse in your `.svelte` components by using `<enhanced:img>` rather than `<img>` and referencing the image file with a [Vite asset import](https://vitejs.dev/guide/assets.html#static-asset-handling) path:\n\n```svelte\n<enhanced:img src=\"./path/to/your/image.jpg\" alt=\"An alt text\" />\n```\n\nAt build time, your `<enhanced:img>` tag will be replaced with an `<img>` wrapped by a `<picture>` providing multiple image types and sizes. It's only possible to downscale images without losing quality, which means that you should provide the highest resolution image that you need — smaller versions will be generated for the various device types that may request an image.\n\nYou should provide your image at 2x resolution for HiDPI displays (a.k.a. retina displays). `<enhanced:img>` will automatically take care of serving smaller versions to smaller devices.\n\n\n### Dynamically choosing an image\n\nYou can also manually import an image asset and pass it to an `<enhanced:img>`. This is useful when you have a collection of static images and would like to dynamically choose one or [iterate over them](https://github.com/sveltejs/kit/blob/0ab1733e394b6310895a1d3bf0f126ce34531170/sites/kit.svelte.dev/src/routes/home/Showcase.svelte). In this case you will need to update both the `import` statement and `<img>` element as shown below to indicate you'd like process them.\n\n```svelte\n<script>\n\timport MyImage from './path/to/your/image.jpg?enhanced';\n</script>\n\n<enhanced:img src={MyImage} alt=\"some alt text\" />\n```\n\nYou can also use [Vite's `import.meta.glob`](https://vitejs.dev/guide/features.html#glob-import). Note that you will have to specify `enhanced` via a [custom query](https://vitejs.dev/guide/features.html#custom-queries):\n\n```svelte\n<script>\n\tconst imageModules = import.meta.glob(\n\t\t'/path/to/assets/*.{avif,AVIF,gif,GIF,heif,HEIF,jpeg,JPEG,jpg,JPG,png,PNG,tiff,TIFF,webp,WEBP}',\n\t\t{\n\t\t\teager: true,\n\t\t\tquery: {\n\t\t\t\tenhanced: true\n\t\t\t}\n\t\t}\n\t)\n</script>\n\n{#each Object.entries(imageModules) as [_path, module]}\n\t<enhanced:img src={module.default} alt=\"some alt text\" />\n{/each}\n```\n\n\n### Intrinsic Dimensions\n\n`width` and `height` are optional as they can be inferred from the source image and will be automatically added when the `<enhanced:img>` tag is preprocessed. With these attributes, the browser can reserve the correct amount of space, preventing [layout shift](https://web.dev/articles/cls). If you'd like to use a different `width` and `height` you can style the image with CSS. Because the preprocessor adds a `width` and `height` for you, if you'd like one of the dimensions to be automatically calculated then you will need to specify that:\n\n```svelte\n<style>\n\t.hero-image img {\n\t\twidth: var(--size);\n\t\theight: auto;\n\t}\n</style>\n```\n\n### `srcset` and `sizes`\n\nIf you have a large image, such as a hero image taking the width of the design, you should specify `sizes` so that smaller versions are requested on smaller devices. E.g. if you have a 1280px image you may want to specify something like:\n\n```svelte\n<enhanced:img src=\"./image.png\" sizes=\"min(1280px, 100vw)\"/>\n```\n\nIf `sizes` is specified, `<enhanced:img>` will generate small images for smaller devices and populate the `srcset` attribute.\n\nThe smallest picture generated automatically will have a width of 540px. If you'd like smaller images or would otherwise like to specify custom widths, you can do that with the `w` query parameter:\n```svelte\n<enhanced:img\n  src=\"./image.png?w=1280;640;400\"\n  sizes=\"(min-width:1920px) 1280px, (min-width:1080px) 640px, (min-width:768px) 400px\"\n/>\n```\n\nIf `sizes` is not provided, then a HiDPI/Retina image and a standard resolution image will be generated. The image you provide should be 2x the resolution you wish to display so that the browser can display that image on devices with a high [device pixel ratio](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio).\n\n### Per-image transforms\n\nBy default, enhanced images will be transformed to more efficient formats. However, you may wish to apply other transforms such as a blur, quality, flatten, or rotate operation. You can run per-image transforms by appending a query string:\n\n```svelte\n<enhanced:img src=\"./path/to/your/image.jpg?blur=15\" alt=\"An alt text\" />\n```\n\n[See the imagetools repo for the full list of directives](https://github.com/JonasKruckenberg/imagetools/blob/main/docs/directives.md).\n\n## Loading images dynamically from a CDN\n\nIn some cases, the images may not be accessible at build time — e.g. they may live inside a content management system or elsewhere.\n\nUsing a content delivery network (CDN) can allow you to optimize these images dynamically, and provides more flexibility with regards to sizes, but it may involve some setup overhead and usage costs. Depending on caching strategy, the browser may not be able to use a cached copy of the asset until a [304 response](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304) is received from the CDN. Building HTML to target CDNs allows using an `<img>` tag since the CDN can serve the appropriate format based on the `User-Agent` header, whereas build-time optimizations must produce `<picture>` tags with multiple sources. Finally, some CDNs may generate images lazily, which could have a negative performance impact for sites with low traffic and frequently changing images.\n\nCDNs can generally be used without any need for a library. However, there are a number of libraries with Svelte support that make it easier. [`@unpic/svelte`](https://unpic.pics/img/svelte/) is a CDN-agnostic library with support for a large number of providers. You may also find that specific CDNs like [Cloudinary](https://svelte.cloudinary.dev/) have Svelte support. Finally, some content management systems (CMS) which support Svelte (such as [Contentful](https://www.contentful.com/sveltekit-starter-guide/), [Storyblok](https://www.storyblok.com/docs/guides/svelte), and [Contentstack](https://www.contentstack.com/docs/developers/sample-apps/build-a-starter-website-with-sveltekit-and-contentstack)) have built-in support for image handling.\n\n## Best practices\n\n- For each image type, use the appropriate solution from those discussed above. You can mix and match all three solutions in one project. For example, you may use Vite's built-in handling to provide images for `<meta>` tags, display images on your homepage with `@sveltejs/enhanced-img`, and display user-submitted content with a dynamic approach.\n- Consider serving all images via CDN regardless of the image optimization types you use. CDNs reduce latency by distributing copies of static assets globally.\n- Your original images should have a good quality/resolution and should have 2x the width it will be displayed at to serve HiDPI devices. Image processing can size images down to save bandwidth when serving smaller screens, but it would be a waste of bandwidth to invent pixels to size images up.\n- For images which are much larger than the width of a mobile device (roughly 400px), such as a hero image taking the width of the page design, specify `sizes` so that smaller images can be served on smaller devices.\n- For important images, such as the [largest contentful paint (LCP)](https://web.dev/articles/lcp) image, set `fetchpriority=\"high\"` and avoid `loading=\"lazy\"` to prioritize loading as early as possible.\n- Give the image a container or styling so that it is constrained and does not jump around while the page is loading affecting your [cumulative layout shift (CLS)](https://web.dev/articles/cls). `width` and `height` help the browser to reserve space while the image is still loading, so `@sveltejs/enhanced-img` will add a `width` and `height` for you.\n- Always provide a good `alt` text. The Svelte compiler will warn you if you don't do this.\n- Do not use `em` or `rem` in `sizes` and change the default size of these measures. When used in `sizes` or `@media` queries, `em` and `rem` are both defined to mean the user's default `font-size`. For a `sizes` declaration like `sizes=\"(min-width: 768px) min(100vw, 108rem), 64rem\"`, the actual `em` or `rem` that controls how the image is laid out on the page can be different if changed by CSS. For example, do not do something like `html { font-size: 62.5%; }` as the slot reserved by the browser preloader will now end up being larger than the actual slot of the CSS object model once it has been created.","size_bytes":10467,"metadata":{"title":"Images"},"created_at":"2025-07-18T15:47:38.826Z","updated_at":"2026-02-26T02:00:03.932Z"},{"path":"apps/svelte.dev/content/docs/kit/40-best-practices/10-accessibility.md","title":"Accessibility","filename":"10-accessibility.md","content":"SvelteKit strives to provide an accessible platform for your app by default. Svelte's [compile-time accessibility checks](../svelte/compiler-warnings) will also apply to any SvelteKit application you build.\n\nHere's how SvelteKit's built-in accessibility features work and what you need to do to help these features to work as well as possible. Keep in mind that while SvelteKit provides an accessible foundation, you are still responsible for making sure your application code is accessible. If you're new to accessibility, see the [\"further reading\"](accessibility#Further-reading) section of this guide for additional resources.\n\nWe recognize that accessibility can be hard to get right. If you want to suggest improvements to how SvelteKit handles accessibility, please [open a GitHub issue](https://github.com/sveltejs/kit/issues).\n\n## Route announcements\n\nIn traditional server-rendered applications, every navigation (e.g. clicking on an `<a>` tag) triggers a full page reload. When this happens, screen readers and other assistive technology will read out the new page's title so that users understand that the page has changed.\n\nSince navigation between pages in SvelteKit happens without reloading the page (known as [client-side routing](glossary#Routing)), SvelteKit injects a [live region](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) onto the page that will read out the new page name after each navigation. This determines the page name to announce by inspecting the `<title>` element.\n\nBecause of this behavior, every page in your app should have a unique, descriptive title. In SvelteKit, you can do this by placing a `<svelte:head>` element on each page:\n\n```svelte\n<!file: src/routes/+page.svelte>\n<svelte:head>\n\t<title>Todo List</title>\n</svelte:head>\n```\n\nThis will allow screen readers and other assistive technology to identify the new page after a navigation occurs. Providing a descriptive title is also important for [SEO](seo#Manual-setup-title-and-meta).\n\n## Focus management\n\nIn traditional server-rendered applications, every navigation will reset focus to the top of the page. This ensures that people browsing the web with a keyboard or screen reader will start interacting with the page from the beginning.\n\nTo simulate this behavior during client-side routing, SvelteKit focuses the `<body>` element after each navigation and [enhanced form submission](form-actions#Progressive-enhancement). There is one exception - if an element with the [`autofocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autofocus) attribute is present, SvelteKit will focus that element instead. Make sure to [consider the implications for assistive technology](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autofocus#accessibility_considerations) when using that attribute.\n\nIf you want to customize SvelteKit's focus management, you can use the `afterNavigate` hook:\n\n```js\n/// <reference types=\"@sveltejs/kit\" />\n//cut\nimport { afterNavigate } from '$app/navigation';\n\nafterNavigate(() => {\n\t/** @type {HTMLElement | null} */\n\tconst to_focus = document.querySelector('.focus-me');\n\tto_focus?.focus();\n});\n```\n\nYou can also programmatically navigate to a different page using the [`goto`]($app-navigation#goto) function. By default, this will have the same client-side routing behavior as clicking on a link. However, `goto` also accepts a `keepFocus` option that will preserve the currently-focused element instead of resetting focus. If you enable this option, make sure the currently-focused element still exists on the page after navigation. If the element no longer exists, the user's focus will be lost, making for a confusing experience for assistive technology users.\n\n## The \"lang\" attribute\n\nBy default, SvelteKit's page template sets the default language of the document to English. If your content is not in English, you should update the `<html>` element in `src/app.html` to have the correct [`lang`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang#accessibility) attribute. This will ensure that any assistive technology reading the document uses the correct pronunciation. For example, if your content is in German, you should update `app.html` to the following:\n\n```html\n/// file: src/app.html\n<html lang=\"de\">\n```\n\nIf your content is available in multiple languages, you should set the `lang` attribute based on the language of the current page. You can do this with SvelteKit's [handle hook](hooks#Server-hooks-handle):\n\n```html\n/// file: src/app.html\n<html lang=\"%lang%\">\n```\n\n```js\n/// file: src/hooks.server.js\n/**\n * @param {import('@sveltejs/kit').RequestEvent} event\n */\nfunction get_lang(event) {\n\treturn 'en';\n}\n//cut\n/** @type {import('@sveltejs/kit').Handle} */\nexport function handle({ event, resolve }) {\n\treturn resolve(event, {\n\t\ttransformPageChunk: ({ html }) => html.replace('%lang%', get_lang(event))\n\t});\n}\n```\n\n## Further reading\n\nFor the most part, building an accessible SvelteKit app is the same as building an accessible web app. You should be able to apply information from the following general accessibility resources to any web experience you build:\n\n- [MDN Web Docs: Accessibility](https://developer.mozilla.org/en-US/docs/Learn/Accessibility)\n- [The A11y Project](https://www.a11yproject.com/)\n- [How to Meet WCAG (Quick Reference)](https://www.w3.org/WAI/WCAG21/quickref/)","size_bytes":5474,"metadata":{"title":"Accessibility"},"created_at":"2025-07-18T15:47:38.828Z","updated_at":"2025-07-18T15:47:40.100Z"},{"path":"apps/svelte.dev/content/docs/kit/40-best-practices/20-seo.md","title":"SEO","filename":"20-seo.md","content":"The most important aspect of SEO is to create high-quality content that is widely linked to from around the web. However, there are a few technical considerations for building sites that rank well.\n\n## Out of the box\n\n### SSR\n\nWhile search engines have got better in recent years at indexing content that was rendered with client-side JavaScript, server-side rendered content is indexed more frequently and reliably. SvelteKit employs SSR by default, and while you can disable it in [`handle`](hooks#Server-hooks-handle), you should leave it on unless you have a good reason not to.\n\n\n### Performance\n\nSignals such as [Core Web Vitals](https://web.dev/vitals/#core-web-vitals) impact search engine ranking. Because Svelte and SvelteKit introduce minimal overhead, they make it easier to build high performance sites. You can test your site's performance using Google's [PageSpeed Insights](https://pagespeed.web.dev/) or [Lighthouse](https://developers.google.com/web/tools/lighthouse). With just a few key actions like using SvelteKit's default [hybrid rendering](glossary#Hybrid-app) mode and [optimizing your images](images), you can greatly improve your site's speed. Read [the performance page](performance) for more details.\n\n### Normalized URLs\n\nSvelteKit redirects pathnames with trailing slashes to ones without (or vice versa depending on your [configuration](page-options#trailingSlash)), as duplicate URLs are bad for SEO.\n\n## Manual setup\n\n### &lt;title&gt; and &lt;meta&gt;\n\nEvery page should have well-written and unique `<title>` and `<meta name=\"description\">` elements inside a [`<svelte:head>`](../svelte/svelte-head). Guidance on how to write descriptive titles and descriptions, along with other suggestions on making content understandable by search engines, can be found on Google's [Lighthouse SEO audits](https://web.dev/lighthouse-seo/) documentation.\n\n\n### Sitemaps\n\n[Sitemaps](https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap) help search engines prioritize pages within your site, particularly when you have a large amount of content. You can create a sitemap dynamically using an endpoint:\n\n```js\n/// file: src/routes/sitemap.xml/+server.js\nexport async function GET() {\n\treturn new Response(\n\t\t`\n\t\t<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n\t\t<urlset\n\t\t\txmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n\t\t\txmlns:xhtml=\"http://www.w3.org/1999/xhtml\"\n\t\t\txmlns:mobile=\"http://www.google.com/schemas/sitemap-mobile/1.0\"\n\t\t\txmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\"\n\t\t\txmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\"\n\t\t\txmlns:video=\"http://www.google.com/schemas/sitemap-video/1.1\"\n\t\t>\n\t\t\t<!-- <url> elements go here -->\n\t\t</urlset>`.trim(),\n\t\t{\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/xml'\n\t\t\t}\n\t\t}\n\t);\n}\n```\n\n### AMP\n\nAn unfortunate reality of modern web development is that it is sometimes necessary to create an [Accelerated Mobile Pages (AMP)](https://amp.dev/) version of your site. In SvelteKit this can be done by setting the [`inlineStyleThreshold`](configuration#inlineStyleThreshold) option...\n\n```js\n/// file: svelte.config.js\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\t// since <link rel=\"stylesheet\"> isn't\n\t\t// allowed, inline all styles\n\t\tinlineStyleThreshold: Infinity\n\t}\n};\n\nexport default config;\n```\n\n...disabling `csr` in your root `+layout.js`/`+layout.server.js`...\n\n```js\n/// file: src/routes/+layout.server.js\nexport const csr = false;\n```\n\n...adding `amp` to your `app.html`\n\n```html\n<html amp>\n...\n```\n\n...and transforming the HTML using `transformPageChunk` along with `transform` imported from `@sveltejs/amp`:\n\n```js\n/// file: src/hooks.server.js\nimport * as amp from '@sveltejs/amp';\n\n/** @type {import('@sveltejs/kit').Handle} */\nexport async function handle({ event, resolve }) {\n\tlet buffer = '';\n\treturn await resolve(event, {\n\t\ttransformPageChunk: ({ html, done }) => {\n\t\t\tbuffer += html;\n\t\t\tif (done) return amp.transform(buffer);\n\t\t}\n\t});\n}\n```\n\nTo prevent shipping any unused CSS as a result of transforming the page to amp, we can use [`dropcss`](https://www.npmjs.com/package/dropcss):\n\n```js\n// @filename: ambient.d.ts\ndeclare module 'dropcss';\n\n// @filename: index.js\n//cut\n/// file: src/hooks.server.js\n// @errors: 2307\nimport * as amp from '@sveltejs/amp';\nimport dropcss from 'dropcss';\n\n/** @type {import('@sveltejs/kit').Handle} */\nexport async function handle({ event, resolve }) {\n\tlet buffer = '';\n\n\treturn await resolve(event, {\n\t\ttransformPageChunk: ({ html, done }) => {\n\t\t\tbuffer += html;\n\n\t\t\tif (done) {\n\t\t\t\tlet css = '';\n\t\t\t\tconst markup = amp\n\t\t\t\t\t.transform(buffer)\n\t\t\t\t\t.replace('⚡', 'amp') // dropcss can't handle this character\n\t\t\t\t\t.replace(/<style amp-custom([^>]*?)>([^]+?)<\\/style>/, (match, attributes, contents) => {\n\t\t\t\t\t\tcss = contents;\n\t\t\t\t\t\treturn `<style amp-custom${attributes}></style>`;\n\t\t\t\t\t});\n\n\t\t\t\tcss = dropcss({ css, html: markup }).css;\n\t\t\t\treturn markup.replace('</style>', `${css}</style>`);\n\t\t\t}\n\t\t}\n\t});\n}\n\n```","size_bytes":5039,"metadata":{"title":"SEO"},"created_at":"2025-07-18T15:47:38.829Z","updated_at":"2025-11-14T14:00:04.848Z"},{"path":"apps/svelte.dev/content/docs/kit/60-appendix/10-faq.md","title":"Frequently asked questions","filename":"10-faq.md","content":"## Other resources\n\nPlease see [the Svelte FAQ](../svelte/faq) and [`vite-plugin-svelte` FAQ](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md) as well for the answers to questions deriving from those libraries.\n\n## What can I make with SvelteKit?\n\nSee [the documentation regarding project types](project-types) for more details.\n\n## How do I include details from package.json in my application?\n\nIf you'd like to include your application's version number or other information from `package.json` in your application, you can load JSON like so:\n\n```ts\n// @errors: 2732\n/// file: svelte.config.js\nimport pkg from './package.json' with { type: 'json' };\n```\n\n## How do I fix the error I'm getting trying to include a package?\n\nMost issues related to including a library are due to incorrect packaging. You can check if a library's packaging is compatible with Node.js by entering it into [the publint website](https://publint.dev/).\n\nHere are a few things to keep in mind when checking if a library is packaged correctly:\n\n- `exports` takes precedence over the other entry point fields such as `main` and `module`. Adding an `exports` field may not be backwards-compatible as it prevents deep imports.\n- ESM files should end with `.mjs` unless `\"type\": \"module\"` is set in which any case CommonJS files should end with `.cjs`.\n- `main` should be defined if `exports` is not. It should be either a CommonJS or ESM file and adhere to the previous bullet. If a `module` field is defined, it should refer to an ESM file.\n- Svelte components should be distributed as uncompiled `.svelte` files with any JS in the package written as ESM only. Custom script and style languages, like TypeScript and SCSS, should be preprocessed as vanilla JS and CSS respectively. We recommend using [`svelte-package`](./packaging) for packaging Svelte libraries, which will do this for you.\n\nLibraries work best in the browser with Vite when they distribute an ESM version, especially if they are dependencies of a Svelte component library. You may wish to suggest to library authors that they provide an ESM version. However, CommonJS (CJS) dependencies should work as well since, by default, [`vite-plugin-svelte` will ask Vite to pre-bundle them](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#what-is-going-on-with-vite-and-pre-bundling-dependencies) using `esbuild` to convert them to ESM.\n\nIf you are still encountering issues we recommend searching both [the Vite issue tracker](https://github.com/vitejs/vite/issues) and the issue tracker of the library in question. Sometimes issues can be worked around by fiddling with the [`optimizeDeps`](https://vitejs.dev/config/#dep-optimization-options) or [`ssr`](https://vitejs.dev/config/#ssr-options) config values though we recommend this as only a short-term workaround in favor of fixing the library in question.\n\n## How do I use the view transitions API?\n\nWhile SvelteKit does not have any specific integration with [view transitions](https://developer.chrome.com/docs/web-platform/view-transitions/), you can call `document.startViewTransition` in [`onNavigate`]($app-navigation#onNavigate) to trigger a view transition on every client-side navigation.\n\n```js\n// @errors: 2339 2810\nimport { onNavigate } from '$app/navigation';\n\nonNavigate((navigation) => {\n\tif (!document.startViewTransition) return;\n\n\treturn new Promise((resolve) => {\n\t\tdocument.startViewTransition(async () => {\n\t\t\tresolve();\n\t\t\tawait navigation.complete;\n\t\t});\n\t});\n});\n```\n\nFor more, see [\"Unlocking view transitions\"](/blog/view-transitions) on the Svelte blog.\n\n## How do I set up a database?\n\nPut the code to query your database in a [server route](./routing#server) - don't query the database in .svelte files. You can create a `db.js` or similar that sets up a connection immediately and makes the client accessible throughout the app as a singleton. You can execute any one-time setup code in `hooks.server.js` and import your database helpers into any endpoint that needs them.\n\nYou can use [the Svelte CLI](/docs/cli/overview) to automatically set up database integrations.\n\n## How do I use a client-side library accessing `document` or `window`?\n\nIf you need access to the `document` or `window` variables or otherwise need code to run only on the client-side you can wrap it in a `browser` check:\n\n```js\n/// <reference types=\"@sveltejs/kit\" />\n//cut\nimport { browser } from '$app/environment';\n\nif (browser) {\n\t// client-only code here\n}\n```\n\nYou can also run code in `onMount` if you'd like to run it after the component has been first rendered to the DOM:\n\n```js\n// @filename: ambient.d.ts\n// @lib: ES2015\ndeclare module 'some-browser-only-library';\n\n// @filename: index.js\n//cut\nimport { onMount } from 'svelte';\n\nonMount(async () => {\n\tconst { method } = await import('some-browser-only-library');\n\tmethod('hello world');\n});\n```\n\nIf the library you'd like to use is side-effect free you can also statically import it and it will be tree-shaken out in the server-side build where `onMount` will be automatically replaced with a no-op:\n\n```js\n// @filename: ambient.d.ts\n// @lib: ES2015\ndeclare module 'some-browser-only-library';\n\n// @filename: index.js\n//cut\nimport { onMount } from 'svelte';\nimport { method } from 'some-browser-only-library';\n\nonMount(() => {\n\tmethod('hello world');\n});\n```\n\nFinally, you may also consider using an `{#await}` block:\n```svelte\n<!file: index.svelte>\n<script>\n\timport { browser } from '$app/environment';\n\n\tconst ComponentConstructor = browser ?\n\t\timport('some-browser-only-library').then((module) => module.Component) :\n\t\tnew Promise(() => {});\n</script>\n\n{#await ComponentConstructor}\n\t<p>Loading...</p>\n{:then component}\n\t<svelte:component this={component} />\n{:catch error}\n\t<p>Something went wrong: {error.message}</p>\n{/await}\n```\n\n## How do I use a different backend API server?\n\nYou can use [`event.fetch`](./load#Making-fetch-requests) to request data from an external API server, but be aware that you would need to deal with [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), which will result in complications such as generally requiring requests to be preflighted resulting in higher latency. Requests to a separate subdomain may also increase latency due to an additional DNS lookup, TLS setup, etc. If you wish to use this method, you may find [`handleFetch`](./hooks#Server-hooks-handleFetch) helpful.\n\nAnother approach is to set up a proxy to bypass CORS headaches. In production, you would rewrite a path like `/api` to the API server; for local development, use Vite's [`server.proxy`](https://vitejs.dev/config/server-options.html#server-proxy) option.\n\nHow to set up rewrites in production will depend on your deployment platform. If rewrites aren't an option, you could alternatively add an [API route](./routing#server):\n\n```js\n/// file: src/routes/api/[...path]/+server.js\n/** @type {import('./$types').RequestHandler} */\nexport function GET({ params, url }) {\n\treturn fetch(`https://example.com/${params.path + url.search}`);\n}\n```\n\n(Note that you may also need to proxy `POST`/`PATCH` etc requests, and forward `request.headers`, depending on your needs.)\n\n## How do I use middleware?\n\n`adapter-node` builds a middleware that you can use with your own server for production mode. In dev, you can add middleware to Vite by using a Vite plugin. For example:\n\n```js\n// @errors: 2322\n// @filename: ambient.d.ts\ndeclare module '@sveltejs/kit/vite'; // TODO this feels unnecessary, why can't it 'see' the declarations?\n\n// @filename: index.js\n//cut\nimport { sveltekit } from '@sveltejs/kit/vite';\n\n/** @type {import('vite').Plugin} */\nconst myPlugin = {\n\tname: 'log-request-middleware',\n\tconfigureServer(server) {\n\t\tserver.middlewares.use((req, res, next) => {\n\t\t\tconsole.log(`Got request ${req.url}`);\n\t\t\tnext();\n\t\t});\n\t}\n};\n\n/** @type {import('vite').UserConfig} */\nconst config = {\n\tplugins: [myPlugin, sveltekit()]\n};\n\nexport default config;\n```\n\nSee [Vite's `configureServer` docs](https://vitejs.dev/guide/api-plugin.html#configureserver) for more details including how to control ordering.\n\n## How do I use Yarn?\n\n### Does it work with Yarn 2?\n\nSort of. The Plug'n'Play feature, aka 'pnp', is broken (it deviates from the Node module resolution algorithm, and [doesn't yet work with native JavaScript modules](https://github.com/yarnpkg/berry/issues/638) which SvelteKit — along with an [increasing number of packages](https://github.com/wooorm/npm-esm-vs-cjs) — uses). You can use `nodeLinker: 'node-modules'` in your [`.yarnrc.yml`](https://yarnpkg.com/configuration/yarnrc#nodeLinker) file to disable pnp, but it's probably easier to just use npm or [pnpm](https://pnpm.io/), which is similarly fast and efficient but without the compatibility headaches.\n\n### How do I use with Yarn 3?\n\nCurrently ESM Support within the latest Yarn (version 3) is considered [experimental](https://github.com/yarnpkg/berry/pull/2161).\n\nThe below seems to work although your results may vary. First create a new application:\n\n```sh\nyarn create svelte myapp\ncd myapp\n```\n\nAnd enable Yarn Berry:\n\n```sh\nyarn set version berry\nyarn install\n```\n\nOne of the more interesting features of Yarn Berry is the ability to have a single global cache for packages, instead of having multiple copies for each project on the disk. However, setting `enableGlobalCache` to true causes building to fail, so it is recommended to add the following to the `.yarnrc.yml` file:\n\n```yaml\nnodeLinker: node-modules\n```\n\nThis will cause packages to be downloaded into a local node_modules directory but avoids the above problem and is your best bet for using version 3 of Yarn at this point in time.","size_bytes":9742,"metadata":{"title":"Frequently asked questions"},"created_at":"2025-07-18T15:47:38.837Z","updated_at":"2026-02-26T02:00:03.928Z"},{"path":"apps/svelte.dev/content/docs/kit/60-appendix/20-integrations.md","title":"Integrations","filename":"20-integrations.md","content":"## `vitePreprocess`\n\n[`vitePreprocess`](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/preprocess.md) preprocesses `<style>` and `<script>` tags in `.svelte` files.\n\n```js\n// svelte.config.js\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n  preprocess: [\n    vitePreprocess({\n      style: true,      // default value\n      script: false     // default value\n    })\n  ]\n};\n\nexport default config;\n```\n\n### `style`\n\nUse `vitePreprocess()` to enable CSS preprocessors in `<style>` tags: PostCSS, SCSS, Less, Stylus, and SugarSS.\n\n### `script`\n\nUse `vitePreprocess({ script: true })` if: \n- your project is before Svelte 5\n- you are using advanced TypeScript features that emit code _(check [`vitePreprocess`](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/preprocess.md) documentation)_\n\nTypeScript is supported natively in Svelte 5, so if you are using Svelte 5 and you don't need to use advanced TypeScript features that emit code, you probably don't need to use `vitePreprocess`.\n\n## Add-ons\n\nRun [`npx sv add`](/docs/cli/sv-add) to set up many different complex integrations with a single command including:\n- prettier (formatting)\n- eslint (linting)\n- vitest (unit testing)\n- playwright (e2e testing)\n- lucia (auth)\n- tailwind (CSS)\n- drizzle (DB)\n- paraglide (i18n)\n- mdsvex (markdown)\n- storybook (frontend workshop)\n\n## Packages\n\nCheck out [the packages page](/packages) for a curated set of high quality Svelte packages. You can also see [sveltesociety.dev](https://sveltesociety.dev/) for additional libraries, templates, and resources.\n\n## Additional integrations\n\n### `svelte-preprocess`\n\n`svelte-preprocess` has some additional functionality not found in `vitePreprocess` such as support for Pug, Babel, and global styles. However, `vitePreprocess` may be faster and require less configuration, so it is used by default. Note that CoffeeScript is [not supported](https://github.com/sveltejs/kit/issues/2920#issuecomment-996469815) by SvelteKit.\n\nYou will need to install `svelte-preprocess` with `npm i -D svelte-preprocess` and [add it to your `svelte.config.js`](https://github.com/sveltejs/svelte-preprocess/blob/main/docs/usage.md#with-svelte-config). After that, you will often need to [install the corresponding library](https://github.com/sveltejs/svelte-preprocess/blob/main/docs/getting-started.md) such as `npm i -D sass` or `npm i -D less`.\n\n## Vite plugins\n\nSince SvelteKit projects are built with Vite, you can use Vite plugins to enhance your project. See a list of available plugins at [`vitejs/awesome-vite`](https://github.com/vitejs/awesome-vite?tab=readme-ov-file#plugins).\n\n## Integration FAQs\n\n[The SvelteKit FAQ](./faq) answers many questions about how to do X with SvelteKit, which may be helpful if you still have questions.","size_bytes":2898,"metadata":{"title":"Integrations"},"created_at":"2025-07-18T15:47:38.839Z","updated_at":"2026-02-14T01:33:24.854Z"},{"path":"apps/svelte.dev/content/docs/kit/60-appendix/25-debugging.md","title":"Breakpoint Debugging","filename":"25-debugging.md","content":"In addition to the [`@debug`](../svelte/@debug) tag, you can also debug Svelte and SvelteKit projects using breakpoints within various tools and development environments. This includes both frontend and backend code.\n\nThe following guides assume your JavaScript runtime environment is Node.js.\n\n## Visual Studio Code\n\nWith the built-in debug terminal, you can set up breakpoints in source files within VSCode.\n\n1. Open the command palette: `CMD/Ctrl` + `Shift` + `P`.\n2. Find and launch \"Debug: JavaScript Debug Terminal\".\n3. Start your project using the debug terminal. For example: `npm run dev`.\n4. Set some breakpoints in your client or server-side source code.\n5. Trigger the breakpoint.\n\n### Launch via debug pane\n\nYou may alternatively set up a `.vscode/launch.json` in your project. To set one up automatically:\n\n1. Go to the \"Run and Debug\" pane.\n2. In the \"Run\" select menu, choose \"Node.js...\".\n3. Select the \"run script\" that corresponds to your project, such as \"Run script: dev\".\n4. Press the \"Start debugging\" play button, or hit `F5` to begin breakpoint debugging.\n\nHere's an example `launch.json`:\n\n```json\n{\n\t\"version\": \"0.2.0\",\n\t\"configurations\": [\n\t\t{\n\t\t\t\"command\": \"npm run dev\",\n\t\t\t\"name\": \"Run development server\",\n\t\t\t\"request\": \"launch\",\n\t\t\t\"type\": \"node-terminal\"\n\t\t}\n\t]\n}\n```\n\nFurther reading: <https://code.visualstudio.com/docs/editor/debugging>.\n\n## Other Editors\n\nIf you use a different editor, these community guides might be useful for you:\n\n- [WebStorm Svelte: Debug Your Application](https://www.jetbrains.com/help/webstorm/svelte.html#ws_svelte_debug)\n- [Debugging JavaScript Frameworks in Neovim](https://theosteiner.de/debugging-javascript-frameworks-in-neovim)\n\n## Google Chrome and Microsoft Edge Developer Tools\n\nIt's possible to debug Node.js applications using a browser-based debugger.\n\n\n1. Run the `--inspect` flag when starting the Vite server with Node.js. For instance: `NODE_OPTIONS=\"--inspect\" npm run dev`\n2. Open your site in a new tab. Typically at `localhost:5173`.\n3. Open your browser's dev tools, and click on the \"Open dedicated DevTools for Node.js\" icon near the top-left. It should display the Node.js logo.\n4. Set up breakpoints and debug your application.\n\nYou may alternatively open the debugger devtools by navigating to `chrome://inspect` in Google Chrome, or `edge://inspect` in Microsoft Edge.\n\n## References\n\n- [Debugging Node.js](https://nodejs.org/en/learn/getting-started/debugging)","size_bytes":2491,"metadata":{"title":"Breakpoint Debugging"},"created_at":"2025-07-18T15:47:38.842Z","updated_at":"2025-07-18T15:47:40.109Z"},{"path":"apps/svelte.dev/content/docs/kit/60-appendix/30-migrating-to-sveltekit-2.md","title":"Migrating to SvelteKit v2","filename":"30-migrating-to-sveltekit-2.md","content":"Upgrading from SvelteKit version 1 to version 2 should be mostly seamless. There are a few breaking changes to note, which are listed here. You can use `npx sv migrate sveltekit-2` to migrate some of these changes automatically.\n\nWe highly recommend upgrading to the most recent 1.x version before upgrading to 2.0, so that you can take advantage of targeted deprecation warnings. We also recommend [updating to Svelte 4](../svelte/v4-migration-guide) first: Later versions of SvelteKit 1.x support it, and SvelteKit 2.0 requires it.\n\n## `redirect` and `error` are no longer thrown by you\n\nPreviously, you had to `throw` the values returned from `error(...)` and `redirect(...)` yourself. In SvelteKit 2 this is no longer the case — calling the functions is sufficient.\n\n```js\nimport { error } from '@sveltejs/kit'\n\n// ...\nthrow error(500, 'something went wrong');\nerror(500, 'something went wrong');\n```\n\n`svelte-migrate` will do these changes automatically for you.\n\nIf the error or redirect is thrown inside a `try {...}` block (hint: don't do this!), you can distinguish them from unexpected errors using [`isHttpError`](@sveltejs-kit#isHttpError) and [`isRedirect`](@sveltejs-kit#isRedirect) imported from `@sveltejs/kit`.\n\n## path is required when setting cookies\n\nWhen receiving a `Set-Cookie` header that doesn't specify a `path`, browsers will [set the cookie path](https://www.rfc-editor.org/rfc/rfc6265#section-5.1.4) to the parent of the resource in question. This behaviour isn't particularly helpful or intuitive, and frequently results in bugs because the developer expected the cookie to apply to the domain as a whole.\n\nAs of SvelteKit 2.0, you need to set a `path` when calling `cookies.set(...)`, `cookies.delete(...)` or `cookies.serialize(...)` so that there's no ambiguity. Most of the time, you probably want to use `path: '/'`, but you can set it to whatever you like, including relative paths — `''` means 'the current path', `'.'` means 'the current directory'.\n\n```js\n/** @type {import('./$types').PageServerLoad} */\nexport function load({ cookies }) {\n\tcookies.set(name, value,{ path: '/' });\n\treturn { response }\n}\n```\n\n`svelte-migrate` will add comments highlighting the locations that need to be adjusted.\n\n## Top-level promises are no longer awaited\n\nIn SvelteKit version 1, if the top-level properties of the object returned from a `load` function were promises, they were automatically awaited. With the introduction of [streaming](/blog/streaming-snapshots-sveltekit) this behavior became a bit awkward as it forces you to nest your streamed data one level deep.\n\nAs of version 2, SvelteKit no longer differentiates between top-level and non-top-level promises. To get back the blocking behavior, use `await` (with `Promise.all` to prevent waterfalls, where appropriate):\n\n```js\n// @filename: ambient.d.ts\ndeclare const url: string;\n\n// @filename: index.js\n//cut\n// If you have a single promise\n/** @type {import('./$types').PageServerLoad} */\nexportasyncfunction load({ fetch }) {\n\tconst response =awaitfetch(url).then(r => r.json());\n\treturn { response }\n}\n```\n\n```js\n// @filename: ambient.d.ts\ndeclare const url1: string;\ndeclare const url2: string;\n\n// @filename: index.js\n//cut\n// If you have multiple promises\n/** @type {import('./$types').PageServerLoad} */\nexportasyncfunction load({ fetch }) {\nconst a = fetch(url1).then(r => r.json());\nconst b = fetch(url2).then(r => r.json());\nconst [a, b] = await Promise.all([\n\t  fetch(url1).then(r => r.json()),\n\t  fetch(url2).then(r => r.json()),\n\t]);\n\treturn { a, b };\n}\n```\n\n## goto(...) changes\n\n`goto(...)` no longer accepts external URLs. To navigate to an external URL, use `window.location.href = url`. The `state` object now determines `$page.state` and must adhere to the `App.PageState` interface, if declared. See [shallow routing](shallow-routing) for more details.\n\n## paths are now relative by default\n\nIn SvelteKit 1, `%sveltekit.assets%` in your `app.html` was replaced with a relative path by default (i.e. `.` or `..` or `../..` etc, depending on the path being rendered) during server-side rendering unless the [`paths.relative`](configuration#paths) config option was explicitly set to `false`. The same was true for `base` and `assets` imported from `$app/paths`, but only if the `paths.relative` option was explicitly set to `true`.\n\nThis inconsistency is fixed in version 2. Paths are either always relative or always absolute, depending on the value of [`paths.relative`](configuration#paths). It defaults to `true` as this results in more portable apps: if the `base` is something other than the app expected (as is the case when viewed on the [Internet Archive](https://archive.org/), for example) or unknown at build time (as is the case when deploying to [IPFS](https://ipfs.tech/) and so on), fewer things are likely to break.\n\n## Server fetches are not trackable anymore\n\nPreviously it was possible to track URLs from `fetch`es on the server in order to rerun load functions. This poses a possible security risk (private URLs leaking), and for this reason it was behind the `dangerZone.trackServerFetches` setting, which is now removed.\n\n## `preloadCode` arguments must be prefixed with `base`\n\nSvelteKit exposes two functions, [`preloadCode`]($app-navigation#preloadCode) and [`preloadData`]($app-navigation#preloadData), for programmatically loading the code and data associated with a particular path. In version 1, there was a subtle inconsistency — the path passed to `preloadCode` did not need to be prefixed with the `base` path (if set), while the path passed to `preloadData` did.\n\nThis is fixed in SvelteKit 2 — in both cases, the path should be prefixed with `base` if it is set.\n\nAdditionally, `preloadCode` now takes a single argument rather than _n_ arguments.\n\n## `resolvePath` has been removed\n\nSvelteKit 1 included a function called `resolvePath` which allows you to resolve a route ID (like `/blog/[slug]`) and a set of parameters (like `{ slug: 'hello' }`) to a pathname. Unfortunately the return value didn't include the `base` path, limiting its usefulness in cases where `base` was set.\n\nFor this reason, SvelteKit 2 replaces `resolvePath` with a (slightly better named) function called `resolveRoute`, which is imported from `$app/paths` and which takes `base` into account.\n\n```js\nimport { resolvePath } from '@sveltejs/kit';\nimport { base } from '$app/paths';\nimport { resolveRoute } from '$app/paths';\n\nconst path = base + resolvePath('/blog/[slug]', { slug });\nconst path = resolveRoute('/blog/[slug]', { slug });\n```\n\n`svelte-migrate` will do the method replacement for you, though if you later prepend the result with `base`, you need to remove that yourself.\n\n## Improved error handling\n\nErrors are handled inconsistently in SvelteKit 1. Some errors trigger the `handleError` hook but there is no good way to discern their status (for example, the only way to tell a 404 from a 500 is by seeing if `event.route.id` is `null`), while others (such as 405 errors for `POST` requests to pages without actions) don't trigger `handleError` at all, but should. In the latter case, the resulting `$page.error` will deviate from the [`App.Error`](types#Error) type, if it is specified.\n\nSvelteKit 2 cleans this up by calling `handleError` hooks with two new properties: `status` and `message`. For errors thrown from your code (or library code called by your code) the status will be `500` and the message will be `Internal Error`. While `error.message` may contain sensitive information that should not be exposed to users, `message` is safe.\n\n## Dynamic environment variables cannot be used during prerendering\n\nThe `$env/dynamic/public` and `$env/dynamic/private` modules provide access to _run time_ environment variables, as opposed to the _build time_ environment variables exposed by `$env/static/public` and `$env/static/private`.\n\nDuring prerendering in SvelteKit 1, they are one and the same. This means that prerendered pages that make use of 'dynamic' environment variables are really 'baking in' build time values, which is incorrect. Worse, `$env/dynamic/public` is populated in the browser with these stale values if the user happens to land on a prerendered page before navigating to dynamically-rendered pages.\n\nBecause of this, dynamic environment variables can no longer be read during prerendering in SvelteKit 2 — you should use the `static` modules instead. If the user lands on a prerendered page, SvelteKit will request up-to-date values for `$env/dynamic/public` from the server (by default from a module called `/_app/env.js`) instead of reading them from the server-rendered HTML.\n\n## `form` and `data` have been removed from `use:enhance` callbacks\n\nIf you provide a callback to [`use:enhance`](form-actions#Progressive-enhancement-use:enhance), it will be called with an object containing various useful properties.\n\nIn SvelteKit 1, those properties included `form` and `data`. These were deprecated some time ago in favour of `formElement` and `formData`, and have been removed altogether in SvelteKit 2.\n\n## Forms containing file inputs must use `multipart/form-data`\n\nIf a form contains an `<input type=\"file\">` but does not have an `enctype=\"multipart/form-data\"` attribute, non-JS submissions will omit the file. SvelteKit 2 will throw an error if it encounters a form like this during a `use:enhance` submission to ensure that your forms work correctly when JavaScript is not present.\n\n## Generated `tsconfig.json` is more strict\n\nPreviously, the generated `tsconfig.json` was trying its best to still produce a somewhat valid config when your `tsconfig.json` included `paths` or `baseUrl`. In SvelteKit 2, the validation is more strict and will warn when you use either `paths` or `baseUrl` in your `tsconfig.json`. These settings are used to generate path aliases and you should use [the `alias` config](configuration#alias) option in your `svelte.config.js` instead, to also create a corresponding alias for the bundler.\n\n## `getRequest` no longer throws errors\n\nThe `@sveltejs/kit/node` module exports helper functions for use in Node environments, including `getRequest` which turns a Node [`ClientRequest`](https://nodejs.org/api/http.html#class-httpclientrequest) into a standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object.\n\nIn SvelteKit 1, `getRequest` could throw if the `Content-Length` header exceeded the specified size limit. In SvelteKit 2, the error will not be thrown until later, when the request body (if any) is being read. This enables better diagnostics and simpler code.\n\n## `vitePreprocess` is no longer exported from `@sveltejs/kit/vite`\n\nSince `@sveltejs/vite-plugin-svelte` is now a peer dependency, SvelteKit 2 no longer re-exports `vitePreprocess`. You should import it directly from `@sveltejs/vite-plugin-svelte`.\n\n## Updated dependency requirements\n\nSvelteKit 2 requires Node `18.13` or higher, and the following minimum dependency versions:\n\n- `svelte@4`\n- `vite@5`\n- `typescript@5`\n- `@sveltejs/vite-plugin-svelte@3` (this is now required as a `peerDependency` of SvelteKit — previously it was directly depended upon)\n- `@sveltejs/adapter-cloudflare@3` (if you're using these adapters)\n- `@sveltejs/adapter-cloudflare-workers@2`\n- `@sveltejs/adapter-netlify@3`\n- `@sveltejs/adapter-node@2`\n- `@sveltejs/adapter-static@3`\n- `@sveltejs/adapter-vercel@4`\n\n`svelte-migrate` will update your `package.json` for you.\n\nAs part of the TypeScript upgrade, the generated `tsconfig.json` (the one your `tsconfig.json` extends from) now uses `\"moduleResolution\": \"bundler\"` (which is recommended by the TypeScript team, as it properly resolves types from packages with an `exports` map in package.json) and `verbatimModuleSyntax` (which replaces the existing `importsNotUsedAsValues ` and `preserveValueImports` flags — if you have those in your `tsconfig.json`, remove them. `svelte-migrate` will do this for you).\n\n## SvelteKit 2.12: $app/stores deprecated\n\nSvelteKit 2.12 introduced `$app/state` based on the [Svelte 5 runes API](/docs/svelte/what-are-runes). `$app/state` provides everything that `$app/stores` provides but with more flexibility as to where and how you use it. Most importantly, the `page` object is now fine-grained, e.g. updates to `page.state` will not invalidate `page.data` and vice-versa.\n\nAs a consequence, `$app/stores` is deprecated and subject to be removed in SvelteKit 3. We recommend [upgrading to Svelte 5](/docs/svelte/v5-migration-guide), if you haven't already, and then migrate away from `$app/stores`. Most of the replacements should be pretty simple: Replace the `$app/stores` import with `$app/state` and remove the `$` prefixes from the usage sites.\n\n```svelte\n<script>\n\timport { page } from '$app/stores';\n\timport { page } from '$app/state';\n</script>\n\n{$page.data}\n{page.data}\n```\n\nUse `npx sv migrate app-state` to auto-migrate most of your `$app/stores` usages inside `.svelte` components.","size_bytes":13018,"metadata":{"title":"Migrating to SvelteKit v2"},"created_at":"2025-07-18T15:47:38.842Z","updated_at":"2025-08-08T02:00:08.339Z"},{"path":"apps/svelte.dev/content/docs/kit/60-appendix/40-migrating.md","title":"Migrating from Sapper","filename":"40-migrating.md","content":"SvelteKit is the successor to Sapper and shares many elements of its design.\n\nIf you have an existing Sapper app that you plan to migrate to SvelteKit, there are a number of changes you will need to make. You may find it helpful to view [some examples](additional-resources#Examples) while migrating.\n\n## package.json\n\n### type: \"module\"\n\nAdd `\"type\": \"module\"` to your `package.json`. You can do this step separately from the rest as part of an incremental migration if you are using Sapper 0.29.3\nor newer.\n\n### dependencies\n\nRemove `polka` or `express`, if you're using one of those, and any middleware such as `sirv` or `compression`.\n\n### devDependencies\n\nRemove `sapper` from your `devDependencies` and replace it with `@sveltejs/kit` and whichever [adapter](adapters) you plan to use (see [next section](migrating#Project-files-Configuration)).\n\n### scripts\n\nAny scripts that reference `sapper` should be updated:\n\n- `sapper build` should become `vite build` using the Node [adapter](adapters)\n- `sapper export` should become `vite build` using the static [adapter](adapters)\n- `sapper dev` should become `vite dev`\n- `node __sapper__/build` should become `node build`\n\n## Project files\n\nThe bulk of your app, in `src/routes`, can be left where it is, but several project files will need to be moved or updated.\n\n### Configuration\n\nYour `webpack.config.js` or `rollup.config.js` should be replaced with a `svelte.config.js`, as documented [here](configuration). Svelte preprocessor options should be moved to `config.preprocess`.\n\nYou will need to add an [adapter](adapters). `sapper build` is roughly equivalent to [adapter-node](adapter-node) while `sapper export` is roughly equivalent to [adapter-static](adapter-static), though you might prefer to use an adapter designed for the platform you're deploying to.\n\nIf you were using plugins for filetypes that are not automatically handled by [Vite](https://vitejs.dev), you will need to find Vite equivalents and add them to the [Vite config](project-structure#Project-files-vite.config.js).\n\n### src/client.js\n\nThis file has no equivalent in SvelteKit. Any custom logic (beyond `sapper.start(...)`) should be expressed in your `+layout.svelte` file, inside an `onMount` callback.\n\n### src/server.js\n\nWhen using `adapter-node` the equivalent is a [custom server](adapter-node#Custom-server). Otherwise, this file has no direct equivalent, since SvelteKit apps can run in serverless environments.\n\n### src/service-worker.js\n\nMost imports from `@sapper/service-worker` have equivalents in [`$service-worker`]($service-worker):\n\n- `files` is unchanged\n- `routes` has been removed\n- `shell` is now `build`\n- `timestamp` is now `version`\n\n### src/template.html\n\nThe `src/template.html` file should be renamed `src/app.html`.\n\nRemove `%sapper.base%`, `%sapper.scripts%` and `%sapper.styles%`. Replace `%sapper.head%` with `%sveltekit.head%` and `%sapper.html%` with `%sveltekit.body%`. The `<div id=\"sapper\">` is no longer necessary.\n\n### src/node_modules\n\nA common pattern in Sapper apps is to put your internal library in a directory inside `src/node_modules`. This doesn't work with Vite, so we use [`src/lib`]($lib) instead.\n\n## Pages and layouts\n\n### Renamed files\n\nRoutes now are made up of the folder name exclusively to remove ambiguity, the folder names leading up to a `+page.svelte` correspond to the route. See [the routing docs](routing) for an overview. The following shows a old/new comparison:\n\n| Old                       | New                       |\n| ------------------------- | ------------------------- |\n| routes/about/index.svelte | routes/about/+page.svelte |\n| routes/about.svelte       | routes/about/+page.svelte |\n\nYour custom error page component should be renamed from `_error.svelte` to `+error.svelte`. Any `_layout.svelte` files should likewise be renamed `+layout.svelte`. [Any other files are ignored](routing#Other-files).\n\n### Imports\n\nThe `goto`, `prefetch` and `prefetchRoutes` imports from `@sapper/app` should be replaced with `goto`, `preloadData` and `preloadCode` imports respectively from [`$app/navigation`]($app-navigation).\n\nThe `stores` import from `@sapper/app` should be replaced — see the [Stores](migrating#Pages-and-layouts-Stores) section below.\n\nAny files you previously imported from directories in `src/node_modules` will need to be replaced with [`$lib`]($lib) imports.\n\n### Preload\n\nAs before, pages and layouts can export a function that allows data to be loaded before rendering takes place.\n\nThis function has been renamed from `preload` to [`load`](load), it now lives in a `+page.js` (or `+layout.js`) next to its `+page.svelte` (or `+layout.svelte`), and its API has changed. Instead of two arguments — `page` and `session` — there is a single `event` argument.\n\nThere is no more `this` object, and consequently no `this.fetch`, `this.error` or `this.redirect`. Instead, you can get [`fetch`](load#Making-fetch-requests) from the input methods, and both [`error`](load#Errors) and [`redirect`](load#Redirects) are now thrown.\n\n### Stores\n\nIn Sapper, you would get references to provided stores like so:\n\n```js\n// @filename: ambient.d.ts\ndeclare module '@sapper/app';\n\n// @filename: index.js\n//cut\nimport { stores } from '@sapper/app';\nconst { preloading, page, session } = stores();\n```\n\nThe `page` store still exists; `preloading` has been replaced with a `navigating` store that contains `from` and `to` properties. `page` now has `url` and `params` properties, but no `path` or `query`.\n\nYou access them differently in SvelteKit. `stores` is now `getStores`, but in most cases it is unnecessary since you can import `navigating`, and `page` directly from [`$app/stores`]($app-stores). If you're on Svelte 5 and SvelteKit 2.12 or higher, consider using [`$app/state`]($app-state) instead.\n\n### Routing\n\nRegex routes are no longer supported. Instead, use [advanced route matching](advanced-routing#Matching).\n\n### Segments\n\nPreviously, layout components received a `segment` prop indicating the child segment. This has been removed; you should use the more flexible `$page.url.pathname` (or `page.url.pathname`) value to derive the segment you're interested in.\n\n### URLs\n\nIn Sapper, all relative URLs were resolved against the base URL — usually `/`, unless the `basepath` option was used — rather than against the current page.\n\nThis caused problems and is no longer the case in SvelteKit. Instead, relative URLs are resolved against the current page (or the destination page, for `fetch` URLs in `load` functions) instead. In most cases, it's easier to use root-relative (i.e. starts with `/`) URLs, since their meaning is not context-dependent.\n\n### &lt;a&gt; attributes\n\n- `sapper:prefetch` is now `data-sveltekit-preload-data`\n- `sapper:noscroll` is now `data-sveltekit-noscroll`\n\n## Endpoints\n\nIn Sapper, [server routes](routing#server) received the `req` and `res` objects exposed by Node's `http` module (or the augmented versions provided by frameworks like Polka and Express).\n\nSvelteKit is designed to be agnostic as to where the app is running — it could be running on a Node server, but could equally be running on a serverless platform or in a Cloudflare Worker. For that reason, you no longer interact directly with `req` and `res`. Your endpoints will need to be updated to match the new signature.\n\nTo support this environment-agnostic behavior, `fetch` is now available in the global context, so you don't need to import `node-fetch`, `cross-fetch`, or similar server-side fetch implementations in order to use it.\n\n## Integrations\n\nSee [integrations](./integrations) for detailed information about integrations.\n\n### HTML minifier\n\nSapper includes `html-minifier` by default. SvelteKit does not include this, but you can add it as a prod dependency and then use it through a [hook](hooks#Server-hooks-handle):\n\n```js\n// @filename: ambient.d.ts\n/// <reference types=\"@sveltejs/kit\" />\ndeclare module 'html-minifier';\n\n// @filename: index.js\n//cut\nimport { minify } from 'html-minifier';\nimport { building } from '$app/environment';\n\nconst minification_options = {\n\tcollapseBooleanAttributes: true,\n\tcollapseWhitespace: true,\n\tconservativeCollapse: true,\n\tdecodeEntities: true,\n\thtml5: true,\n\tignoreCustomComments: [/^#/],\n\tminifyCSS: true,\n\tminifyJS: false,\n\tremoveAttributeQuotes: true,\n\tremoveComments: false, // some hydration code needs comments, so leave them in\n\tremoveOptionalTags: true,\n\tremoveRedundantAttributes: true,\n\tremoveScriptTypeAttributes: true,\n\tremoveStyleLinkTypeAttributes: true,\n\tsortAttributes: true,\n\tsortClassName: true\n};\n\n/** @type {import('@sveltejs/kit').Handle} */\nexport async function handle({ event, resolve }) {\n\tlet page = '';\n\n\treturn resolve(event, {\n\t\ttransformPageChunk: ({ html, done }) => {\n\t\t\tpage += html;\n\t\t\tif (done) {\n\t\t\t\treturn building ? minify(page, minification_options) : page;\n\t\t\t}\n\t\t}\n\t});\n}\n```\n\nNote that `prerendering` is `false` when using `vite preview` to test the production build of the site, so to verify the results of minifying, you'll need to inspect the built HTML files directly.","size_bytes":9146,"metadata":{"rank":1,"title":"Migrating from Sapper"},"created_at":"2025-07-18T15:47:38.845Z","updated_at":"2025-07-18T15:47:40.113Z"},{"path":"apps/svelte.dev/content/docs/kit/60-appendix/50-additional-resources.md","title":"Additional resources","filename":"50-additional-resources.md","content":"## FAQs\n\nPlease see the [SvelteKit FAQ](faq) for solutions to common issues and helpful tips and tricks.\n\nThe [Svelte FAQ](../svelte/faq) and [`vite-plugin-svelte` FAQ](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md) may also be helpful for questions deriving from those libraries.\n\n## Examples\n\nWe've written and published a few different SvelteKit sites as examples:\n\n- [`sveltejs/realworld`](https://github.com/sveltejs/realworld) contains an example blog site\n- [A HackerNews clone](https://github.com/sveltejs/sites/tree/master/sites/hn.svelte.dev)\n- [`svelte.dev`](https://github.com/sveltejs/svelte.dev)\n\nSvelteKit users have also published plenty of examples on GitHub, under the [#sveltekit](https://github.com/topics/sveltekit) and [#sveltekit-template](https://github.com/topics/sveltekit-template) topics, as well as on [the Svelte Society site](https://sveltesociety.dev/recipe/sveltekit-templates-and-examples-e789ed397e7f38fc). Note that these have not been vetted by the maintainers and may not be up to date.\n\n## Support\n\nYou can ask for help on [Discord](/chat) and [StackOverflow](https://stackoverflow.com/questions/tagged/sveltekit). Please first search for information related to your issue in the FAQ, Google or another search engine, issue tracker, and Discord chat history in order to be respectful of others' time. There are many more people asking questions than answering them, so this will help in allowing the community to grow in a scalable fashion.","size_bytes":1540,"metadata":{"title":"Additional resources"},"created_at":"2025-07-18T15:47:38.845Z","updated_at":"2025-12-07T14:00:04.407Z"},{"path":"apps/svelte.dev/content/docs/kit/60-appendix/60-glossary.md","title":"Glossary","filename":"60-glossary.md","content":"The core of SvelteKit provides a highly configurable rendering engine. This section describes some of the terms used when discussing rendering. A reference for setting these options is provided in the documentation above.\n\n## CSR\n\nClient-side rendering (CSR) is the generation of the page contents in the web browser using JavaScript.\n\nIn SvelteKit, client-side rendering will be used by default, but you can turn off JavaScript with [the `csr = false` page option](page-options#csr).\n\n## Edge\n\nRendering on the edge refers to rendering an application in a content delivery network (CDN) near the user. Edge rendering allows the request and response for a page to travel a shorter distance thus improving latency.\n\n## Hybrid app\n\nSvelteKit uses a hybrid rendering mode by default where it loads the initial HTML from the server (SSR), and then updates the page contents on subsequent navigations via client-side rendering (CSR).\n\n## Hydration\n\nSvelte components store some state and update the DOM when the state is updated. When fetching data during SSR, by default SvelteKit will store this data and transmit it to the client along with the server-rendered HTML. The components can then be initialized on the client with that data without having to call the same API endpoints again. Svelte will then check that the DOM is in the expected state and attach event listeners in a process called hydration. Once the components are fully hydrated, they can react to changes to their properties just like any newly created Svelte component.\n\nIn SvelteKit, pages will be hydrated by default, but you can turn off JavaScript with [the `csr = false` page option](page-options#csr).\n\n## ISR\n\nIncremental static regeneration (ISR) allows you to generate static pages on your site as visitors request those pages without redeploying. This may reduces build times compared to [SSG](#SSG) sites with a large number of pages. You can do [ISR with `adapter-vercel`](adapter-vercel#Incremental-Static-Regeneration).\n\n## MPA\n\nTraditional applications that render each page view on the server — such as those written in languages other than JavaScript — are often referred to as multi-page apps (MPA).\n\n## Prerendering\n\nPrerendering means computing the contents of a page at build time and saving the HTML for display. This approach has the same benefits as traditional server-rendered pages, but avoids recomputing the page for each visitor and so scales nearly for free as the number of visitors increases. The tradeoff is that the build process is more expensive and prerendered content can only be updated by building and deploying a new version of the application.\n\nFor content to be prerenderable, any two users hitting it directly must get the same content from the server, and the page must not contain [actions](form-actions). Note that you can still prerender content that is loaded based on the page's parameters as long as all users will be seeing the same prerendered content. Prerendering all of your pages is also known as [Static Site Generation](#SSG).\n\nPre-rendered pages are not limited to static content. You can build personalized pages if user-specific data is fetched and rendered client-side. This is subject to the caveat that you will experience the downsides of not doing SSR for that content as discussed above.\n\nIn SvelteKit, you can control prerendering with [the `prerender` page option](page-options#prerender) and [`prerender` config](configuration#prerender) in `svelte.config.js`.\n\n\n## PWA\n\nA progressive web app (PWA) is an app that's built using web APIs and technologies, but functions like a mobile or desktop app. Sites served as [PWAs can be installed](https://web.dev/learn/pwa/installation), allowing you to add a shortcut to the application on your launcher, home screen, or start menu. Many PWAs will utilize [service workers](service-workers) to build offline capabilities.\n\n## Routing\n\nBy default, when you navigate to a new page (by clicking on a link or using the browser's forward or back buttons), SvelteKit will intercept the attempted navigation and handle it instead of allowing the browser to send a request to the server for the destination page. SvelteKit will then update the displayed contents on the client by rendering the component for the new page, which in turn can make calls to the necessary API endpoints. This process of updating the page on the client in response to attempted navigation is called client-side routing.\n\nIn SvelteKit, client-side routing will be used by default, but you can skip it with [`data-sveltekit-reload`](link-options#data-sveltekit-reload).\n\n## SPA\n\nA single-page app (SPA) is an application in which all requests to the server load a single HTML file which then does client-side rendering based on the requested URL. All navigation is handled on the client-side in a process called client-side routing with per-page contents being updated and common layout elements remaining largely unchanged. Throughout this site, when we refer to a SPA, we use this definition where a SPA simply serves an empty shell on the initial request. It should not be confused with a [hybrid app](#Hybrid-app), which serves HTML on the initial request. It has a large performance impact by forcing two network round trips before rendering can begin. Because SPA mode has large negative performance and SEO impacts, it is recommended only in very limited circumstances such as when being wrapped in a mobile app.\n\nIn SvelteKit, you can [build SPAs with `adapter-static`](single-page-apps).\n\n## SSG\n\nStatic Site Generation (SSG) is a term that refers to a site where every page is prerendered. One benefit of fully prerendering a site is that you do not need to maintain or pay for servers to perform SSR. Once generated, the site can be served from CDNs, leading to great “time to first byte” performance. This delivery model is often referred to as JAMstack.\n\nIn SvelteKit, you can do static site generation by using [`adapter-static`](adapter-static) or by configuring every page to be [prerendered](#Prerendering) using [the `prerender` page option](page-options#prerender) or [`prerender` config](configuration#prerender) in `svelte.config.js`.\n\n## SSR\n\nServer-side rendering (SSR) is the generation of the page contents on the server. Returning the page contents from the server via SSR or prerendering is highly preferred for performance and SEO. It significantly improves performance by avoiding the introduction of extra round trips necessary in a SPA, and makes your app accessible to users if JavaScript fails or is disabled (which happens [more often than you probably think](https://kryogenix.org/code/browser/everyonehasjs.html)). While some search engines can index content that is dynamically generated on the client-side, it is likely to take longer even in these cases.\n\nIn SvelteKit, pages are server-side rendered by default. You can disable SSR with [the `ssr` page option](page-options#ssr).","size_bytes":7002,"metadata":{"title":"Glossary"},"created_at":"2025-07-18T15:47:38.847Z","updated_at":"2026-02-14T01:33:24.854Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md","title":"@sveltejs/kit","filename":"10-@sveltejs-kit.md","content":"```js\n// @noErrors\nimport {\n\tServer,\n\tVERSION,\n\terror,\n\tfail,\n\tinvalid,\n\tisActionFailure,\n\tisHttpError,\n\tisRedirect,\n\tisValidationError,\n\tjson,\n\tnormalizeUrl,\n\tredirect,\n\ttext\n} from '@sveltejs/kit';\n```\n\n## Server\n\n<div class=\"ts-block\">\n\n```dts\nclass Server {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nconstructor(manifest: SSRManifest);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ninit(options: ServerInitOptions): Promise<void>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrespond(request: Request, options: RequestOptions): Promise<Response>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n\n\n## VERSION\n\n<div class=\"ts-block\">\n\n```dts\nconst VERSION: string;\n```\n\n</div>\n\n\n\n## error\n\nThrows an error with a HTTP status code and an optional message.\nWhen called during request handling, this will cause SvelteKit to\nreturn an error response without invoking `handleError`.\nMake sure you're not catching the thrown error, which would prevent SvelteKit from handling it.\n\n<div class=\"ts-block\">\n\n```dts\nfunction error(status: number, body: App.Error): never;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction error(\n\tstatus: number,\n\tbody?: {\n\t\tmessage: string;\n\t} extends App.Error\n\t\t? App.Error | string | undefined\n\t\t: never\n): never;\n```\n\n</div>\n\n\n\n## fail\n\nCreate an `ActionFailure` object. Call when form submission fails.\n\n<div class=\"ts-block\">\n\n```dts\nfunction fail(status: number): ActionFailure<undefined>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction fail<T = undefined>(\n\tstatus: number,\n\tdata: T\n): ActionFailure<T>;\n```\n\n</div>\n\n\n\n## invalid\n\n<blockquote class=\"since note\">\n\nAvailable since 2.47.3\n\n</blockquote>\n\nUse this to throw a validation error to imperatively fail form validation.\nCan be used in combination with `issue` passed to form actions to create field-specific issues.\n\n```ts\nimport { invalid } from '@sveltejs/kit';\nimport { form } from '$app/server';\nimport { tryLogin } from '$lib/server/auth';\nimport * as v from 'valibot';\n\nexport const login = form(\n\tv.object({ name: v.string(), _password: v.string() }),\n\tasync ({ name, _password }) => {\n\t\tconst success = tryLogin(name, _password);\n\t\tif (!success) {\n\t\t\tinvalid('Incorrect username or password');\n\t\t}\n\n\t\t// ...\n\t}\n);\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction invalid(\n\t...issues: (StandardSchemaV1.Issue | string)[]\n): never;\n```\n\n</div>\n\n\n\n## isActionFailure\n\nChecks whether this is an action failure thrown by `fail`.\n\n<div class=\"ts-block\">\n\n```dts\nfunction isActionFailure(e: unknown): e is ActionFailure;\n```\n\n</div>\n\n\n\n## isHttpError\n\nChecks whether this is an error thrown by `error`.\n\n<div class=\"ts-block\">\n\n```dts\nfunction isHttpError<T extends number>(\n\te: unknown,\n\tstatus?: T\n): e is HttpError_1 & {\n\tstatus: T extends undefined ? never : T;\n};\n```\n\n</div>\n\n\n\n## isRedirect\n\nChecks whether this is a redirect thrown by `redirect`.\n\n<div class=\"ts-block\">\n\n```dts\nfunction isRedirect(e: unknown): e is Redirect_1;\n```\n\n</div>\n\n\n\n## isValidationError\n\n<blockquote class=\"since note\">\n\nAvailable since 2.47.3\n\n</blockquote>\n\nChecks whether this is an validation error thrown by `invalid`.\n\n<div class=\"ts-block\">\n\n```dts\nfunction isValidationError(e: unknown): e is ActionFailure;\n```\n\n</div>\n\n\n\n## json\n\nCreate a JSON `Response` object from the supplied data.\n\n<div class=\"ts-block\">\n\n```dts\nfunction json(data: any, init?: ResponseInit): Response;\n```\n\n</div>\n\n\n\n## normalizeUrl\n\n<blockquote class=\"since note\">\n\nAvailable since 2.18.0\n\n</blockquote>\n\nStrips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.\nReturns the normalized URL as well as a method for adding the potential suffix back\nbased on a new pathname (possibly including search) or URL.\n```js\n// @errors: 7031\nimport { normalizeUrl } from '@sveltejs/kit';\n\nconst { url, denormalize } = normalizeUrl('/blog/post/__data.json');\nconsole.log(url.pathname); // /blog/post\nconsole.log(denormalize('/blog/post/a')); // /blog/post/a/__data.json\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction normalizeUrl(url: URL | string): {\n\turl: URL;\n\twasNormalized: boolean;\n\tdenormalize: (url?: string | URL) => URL;\n};\n```\n\n</div>\n\n\n\n## redirect\n\nRedirect a request. When called during request handling, SvelteKit will return a redirect response.\nMake sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.\n\nMost common status codes:\n * `303 See Other`: redirect as a GET request (often used after a form POST request)\n * `307 Temporary Redirect`: redirect will keep the request method\n * `308 Permanent Redirect`: redirect will keep the request method, SEO will be transferred to the new page\n\n[See all redirect status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages)\n\n<div class=\"ts-block\">\n\n```dts\nfunction redirect(\n\tstatus:\n\t\t| 300\n\t\t| 301\n\t\t| 302\n\t\t| 303\n\t\t| 304\n\t\t| 305\n\t\t| 306\n\t\t| 307\n\t\t| 308\n\t\t| ({} & number),\n\tlocation: string | URL\n): never;\n```\n\n</div>\n\n\n\n## text\n\nCreate a `Response` object from the supplied body.\n\n<div class=\"ts-block\">\n\n```dts\nfunction text(body: string, init?: ResponseInit): Response;\n```\n\n</div>\n\n\n\n## Action\n\nShape of a form action method that is part of `export const actions = {...}` in `+page.server.js`.\nSee [form actions](/docs/kit/form-actions) for more information.\n\n<div class=\"ts-block\">\n\n```dts\ntype Action<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tOutputData extends Record<string, any> | void = Record<\n\t\tstring,\n\t\tany\n\t> | void,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> = (\n\tevent: RequestEvent<Params, RouteId>\n) => MaybePromise<OutputData>;\n```\n\n</div>\n\n## ActionFailure\n\n<div class=\"ts-block\">\n\n```dts\ninterface ActionFailure<T = undefined> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nstatus: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndata: T;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n[uniqueSymbol]: true;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## ActionResult\n\nWhen calling a form action via fetch, the response will be one of these shapes.\n```svelte\n<form method=\"post\" use:enhance={() => {\n\treturn ({ result }) => {\n\t\t// result is of type ActionResult\n\t};\n}}\n```\n\n<div class=\"ts-block\">\n\n```dts\ntype ActionResult<\n\tSuccess extends Record<string, unknown> | undefined =\n\t\tRecord<string, any>,\n\tFailure extends Record<string, unknown> | undefined =\n\t\tRecord<string, any>\n> =\n\t| { type: 'success'; status: number; data?: Success }\n\t| { type: 'failure'; status: number; data?: Failure }\n\t| { type: 'redirect'; status: number; location: string }\n\t| { type: 'error'; status?: number; error: any };\n```\n\n</div>\n\n## Actions\n\nShape of the `export const actions = {...}` object in `+page.server.js`.\nSee [form actions](/docs/kit/form-actions) for more information.\n\n<div class=\"ts-block\">\n\n```dts\ntype Actions<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tOutputData extends Record<string, any> | void = Record<\n\t\tstring,\n\t\tany\n\t> | void,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> = Record<string, Action<Params, OutputData, RouteId>>;\n```\n\n</div>\n\n## Adapter\n\n[Adapters](/docs/kit/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Adapter {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nname: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe name of the adapter, using for logging. Will typically correspond to the package name.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nadapt: (builder: Builder) => MaybePromise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `builder` An object provided by SvelteKit that contains methods for adapting the app\n\n</div>\n\nThis function is called after SvelteKit has built your app.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsupports?: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\nChecks called during dev and build to determine whether specific features will work in production with this adapter.\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nread?: (details: { config: any; route: { id: string } }) => boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `details.config` The merged route config\n\n</div>\n\nTest support for `read` from `$app/server`.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\ninstrumentation?: () => boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nTest support for `instrumentation.server.js`. To pass, the adapter must support running `instrumentation.server.js` prior to the application code.\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nemulate?: () => MaybePromise<Emulator>;\n```\n\n<div class=\"ts-block-property-details\">\n\nCreates an `Emulator`, which allows the adapter to influence the environment\nduring dev, build and prerendering.\n\n</div>\n</div></div>\n\n## AfterNavigate\n\nThe argument passed to [`afterNavigate`](/docs/kit/$app-navigation#afterNavigate) callbacks.\n\n<div class=\"ts-block\">\n\n```dts\ntype AfterNavigate = (Navigation | NavigationEnter) & {\n\t/**\n\t * The type of navigation:\n\t * - `enter`: The app has hydrated/started\n\t * - `form`: The user submitted a `<form method=\"GET\">`\n\t * - `link`: Navigation was triggered by a link click\n\t * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect\n\t * - `popstate`: Navigation was triggered by back/forward navigation\n\t */\n\ttype: Exclude<NavigationType, 'leave'>;\n\t/**\n\t * Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.\n\t */\n\twillUnload: false;\n};\n```\n\n</div>\n\n## AwaitedActions\n\n<div class=\"ts-block\">\n\n```dts\ntype AwaitedActions<\n\tT extends Record<string, (...args: any) => any>\n> = OptionalUnion<\n\t{\n\t\t[Key in keyof T]: UnpackValidationError<\n\t\t\tAwaited<ReturnType<T[Key]>>\n\t\t>;\n\t}[keyof T]\n>;\n```\n\n</div>\n\n## BeforeNavigate\n\nThe argument passed to [`beforeNavigate`](/docs/kit/$app-navigation#beforeNavigate) callbacks.\n\n<div class=\"ts-block\">\n\n```dts\ntype BeforeNavigate = Navigation & {\n\t/**\n\t * Call this to prevent the navigation from starting.\n\t */\n\tcancel: () => void;\n};\n```\n\n</div>\n\n## Builder\n\nThis object is passed to the `adapt` function of adapters.\nIt contains various methods and properties that are useful for adapting the app.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Builder {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nlog: Logger;\n```\n\n<div class=\"ts-block-property-details\">\n\nPrint messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrimraf: (dir: string) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\nRemove `dir` and all its contents.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nmkdirp: (dir: string) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\nCreate `dir` and any required parent directories.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nconfig: ValidatedConfig;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe fully resolved Svelte config.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nprerendered: Prerendered;\n```\n\n<div class=\"ts-block-property-details\">\n\nInformation about prerendered pages and assets, if any.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nroutes: RouteDefinition[];\n```\n\n<div class=\"ts-block-property-details\">\n\nAn array of all routes (including prerendered)\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncreateEntries: (fn: (route: RouteDefinition) => AdapterEntry) => Promise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `fn` A function that groups a set of routes into an entry point\n- <span class=\"tag deprecated\">deprecated</span> Use `builder.routes` instead\n\n</div>\n\nCreate separate functions that map to one or more routes of your app.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nfindServerAssets: (routes: RouteDefinition[]) => string[];\n```\n\n<div class=\"ts-block-property-details\">\n\nFind all the assets imported by server files belonging to `routes`\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngenerateFallback: (dest: string) => Promise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\nGenerate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngenerateEnvModule: () => void;\n```\n\n<div class=\"ts-block-property-details\">\n\nGenerate a module exposing build-time environment variables as `$env/dynamic/public`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngenerateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `opts` a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated\n\n</div>\n\nGenerate a server-side manifest to initialise the SvelteKit [server](/docs/kit/@sveltejs-kit#Server) with.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngetBuildDirectory: (name: string) => string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `name` path to the file, relative to the build directory\n\n</div>\n\nResolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngetClientDirectory: () => string;\n```\n\n<div class=\"ts-block-property-details\">\n\nGet the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngetServerDirectory: () => string;\n```\n\n<div class=\"ts-block-property-details\">\n\nGet the fully resolved path to the directory containing server-side code.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngetAppPath: () => string;\n```\n\n<div class=\"ts-block-property-details\">\n\nGet the application path including any configured `base` path, e.g. `my-base-path/_app`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nwriteClient: (dest: string) => string[];\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `dest` the destination folder\n- <span class=\"tag\">returns</span> an array of files written to `dest`\n\n</div>\n\nWrite client assets to `dest`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nwritePrerendered: (dest: string) => string[];\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `dest` the destination folder\n- <span class=\"tag\">returns</span> an array of files written to `dest`\n\n</div>\n\nWrite prerendered files to `dest`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nwriteServer: (dest: string) => string[];\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `dest` the destination folder\n- <span class=\"tag\">returns</span> an array of files written to `dest`\n\n</div>\n\nWrite server-side code to `dest`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncopy: (\n\tfrom: string,\n\tto: string,\n\topts?: {\n\t\tfilter?(basename: string): boolean;\n\t\treplace?: Record<string, string>;\n\t}\n) => string[];\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `from` the source file or directory\n- `to` the destination file or directory\n- `opts.filter` a function to determine whether a file or directory should be copied\n- `opts.replace` a map of strings to replace\n- <span class=\"tag\">returns</span> an array of files that were copied\n\n</div>\n\nCopy a file or directory.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nhasServerInstrumentationFile: () => boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">returns</span> true if the server instrumentation file exists, false otherwise\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nCheck if the server instrumentation file exists.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ninstrument: (args: {\n\tentrypoint: string;\n\tinstrumentation: string;\n\tstart?: string;\n\tmodule?:\n\t\t| {\n\t\t\t\texports: string[];\n\t\t  }\n\t\t| {\n\t\t\t\tgenerateText: (args: { instrumentation: string; start: string }) => string;\n\t\t  };\n}) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `options` an object containing the following properties:\n- `options.entrypoint` the path to the entrypoint to trace.\n- `options.instrumentation` the path to the instrumentation file.\n- `options.start` the name of the start file. This is what `entrypoint` will be renamed to.\n- `options.module` configuration for the resulting entrypoint module.\n- `options.module.generateText` a function that receives the relative paths to the instrumentation and start files, and generates the text of the module to be traced. If not provided, the default implementation will be used, which uses top-level await.\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nInstrument `entrypoint` with `instrumentation`.\n\nRenames `entrypoint` to `start` and creates a new module at\n`entrypoint` which imports `instrumentation` and then dynamically imports `start`. This allows\nthe module hooks necessary for instrumentation libraries to be loaded prior to any application code.\n\nCaveats:\n- \"Live exports\" will not work. If your adapter uses live exports, your users will need to manually import the server instrumentation on startup.\n- If `tla` is `false`, OTEL auto-instrumentation may not work properly. Use it if your environment supports it.\n- Use `hasServerInstrumentationFile` to check if the user has a server instrumentation file; if they don't, you shouldn't do this.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncompress: (directory: string) => Promise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `directory` The directory containing the files to be compressed\n\n</div>\n\nCompress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals.\n\n</div>\n</div></div>\n\n## ClientInit\n\n<blockquote class=\"since note\">\n\nAvailable since 2.10.0\n\n</blockquote>\n\nThe [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked once the app starts in the browser\n\n<div class=\"ts-block\">\n\n```dts\ntype ClientInit = () => MaybePromise<void>;\n```\n\n</div>\n\n## Config\n\nSee the [configuration reference](/docs/kit/configuration) for details.\n\n## Cookies\n\n<div class=\"ts-block\">\n\n```dts\ninterface Cookies {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nget: (name: string, opts?: import('cookie').CookieParseOptions) => string | undefined;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `name` the name of the cookie\n- `opts` the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options)\n\n</div>\n\nGets a cookie that was previously set with `cookies.set`, or from the request headers.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngetAll: (opts?: import('cookie').CookieParseOptions) => Array<{ name: string; value: string }>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `opts` the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options)\n\n</div>\n\nGets all cookies that were previously set with `cookies.set`, or from the request headers.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nset: (\n\tname: string,\n\tvalue: string,\n\topts: import('cookie').CookieSerializeOptions & { path: string }\n) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `name` the name of the cookie\n- `value` the cookie value\n- `opts` the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options)\n\n</div>\n\nSets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` or `cookies.getAll` during the current request.\n\nThe `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`.\n\nYou must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndelete: (name: string, opts: import('cookie').CookieSerializeOptions & { path: string }) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `name` the name of the cookie\n- `opts` the options, passed directly to `cookie.serialize`. The `path` must match the path of the cookie you want to delete. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options)\n\n</div>\n\nDeletes a cookie by setting its value to an empty string and setting the expiry date in the past.\n\nYou must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nserialize: (\n\tname: string,\n\tvalue: string,\n\topts: import('cookie').CookieSerializeOptions & { path: string }\n) => string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `name` the name of the cookie\n- `value` the cookie value\n- `opts` the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options)\n\n</div>\n\nSerialize a cookie name-value pair into a `Set-Cookie` header string, but don't apply it to the response.\n\nThe `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`.\n\nYou must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children\n\n</div>\n</div></div>\n\n## Emulator\n\nA collection of functions that influence the environment during dev, build and prerendering\n\n<div class=\"ts-block\">\n\n```dts\ninterface Emulator {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nplatform?(details: { config: any; prerender: PrerenderOption }): MaybePromise<App.Platform>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA function that is called with the current route `config` and `prerender` option\nand returns an `App.Platform` object\n\n</div>\n</div></div>\n\n## Handle\n\nThe [`handle`](/docs/kit/hooks#Server-hooks-handle) hook runs every time the SvelteKit server receives a [request](/docs/kit/web-standards#Fetch-APIs-Request) and\ndetermines the [response](/docs/kit/web-standards#Fetch-APIs-Response).\nIt receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`.\nThis allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).\n\n<div class=\"ts-block\">\n\n```dts\ntype Handle = (input: {\n\tevent: RequestEvent;\n\tresolve: (\n\t\tevent: RequestEvent,\n\t\topts?: ResolveOptions\n\t) => MaybePromise<Response>;\n}) => MaybePromise<Response>;\n```\n\n</div>\n\n## HandleClientError\n\nThe client-side [`handleError`](/docs/kit/hooks#Shared-hooks-handleError) hook runs when an unexpected error is thrown while navigating.\n\nIf an unexpected error is thrown during loading or the following render, this function will be called with the error and the event.\nMake sure that this function _never_ throws an error.\n\n<div class=\"ts-block\">\n\n```dts\ntype HandleClientError = (input: {\n\terror: unknown;\n\tevent: NavigationEvent;\n\tstatus: number;\n\tmessage: string;\n}) => MaybePromise<void | App.Error>;\n```\n\n</div>\n\n## HandleFetch\n\nThe [`handleFetch`](/docs/kit/hooks#Server-hooks-handleFetch) hook allows you to modify (or replace) the result of an [`event.fetch`](/docs/kit/load#Making-fetch-requests) call that runs on the server (or during prerendering) inside an endpoint, `load`, `action`, `handle`, `handleError` or `reroute`.\n\n<div class=\"ts-block\">\n\n```dts\ntype HandleFetch = (input: {\n\tevent: RequestEvent;\n\trequest: Request;\n\tfetch: typeof fetch;\n}) => MaybePromise<Response>;\n```\n\n</div>\n\n## HandleServerError\n\nThe server-side [`handleError`](/docs/kit/hooks#Shared-hooks-handleError) hook runs when an unexpected error is thrown while responding to a request.\n\nIf an unexpected error is thrown during loading or rendering, this function will be called with the error and the event.\nMake sure that this function _never_ throws an error.\n\n<div class=\"ts-block\">\n\n```dts\ntype HandleServerError = (input: {\n\terror: unknown;\n\tevent: RequestEvent;\n\tstatus: number;\n\tmessage: string;\n}) => MaybePromise<void | App.Error>;\n```\n\n</div>\n\n## HandleValidationError\n\nThe [`handleValidationError`](/docs/kit/hooks#Server-hooks-handleValidationError) hook runs when the argument to a remote function fails validation.\n\nIt will be called with the validation issues and the event, and must return an object shape that matches `App.Error`.\n\n<div class=\"ts-block\">\n\n```dts\ntype HandleValidationError<\n\tIssue extends StandardSchemaV1.Issue =\n\t\tStandardSchemaV1.Issue\n> = (input: {\n\tissues: Issue[];\n\tevent: RequestEvent;\n}) => MaybePromise<App.Error>;\n```\n\n</div>\n\n## HttpError\n\nThe object returned by the [`error`](/docs/kit/@sveltejs-kit#error) function.\n\n<div class=\"ts-block\">\n\n```dts\ninterface HttpError {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nstatus: number;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nbody: App.Error;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe content of the error.\n\n</div>\n</div></div>\n\n## InvalidField\n\nA function and proxy object used to imperatively create validation errors in form handlers.\n\nAccess properties to create field-specific issues: `issue.fieldName('message')`.\nThe type structure mirrors the input data structure for type-safe field access.\nCall `invalid(issue.foo(...), issue.nested.bar(...))` to throw a validation error.\n\n<div class=\"ts-block\">\n\n```dts\ntype InvalidField<T> =\n\tWillRecurseIndefinitely<T> extends true\n\t\t? Record<string | number, any>\n\t\t: NonNullable<T> extends\n\t\t\t\t\t| string\n\t\t\t\t\t| number\n\t\t\t\t\t| boolean\n\t\t\t\t\t| File\n\t\t\t? (message: string) => StandardSchemaV1.Issue\n\t\t\t: NonNullable<T> extends Array<infer U>\n\t\t\t\t? {\n\t\t\t\t\t\t[K in number]: InvalidField<U>;\n\t\t\t\t\t} & ((message: string) => StandardSchemaV1.Issue)\n\t\t\t\t: NonNullable<T> extends RemoteFormInput\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t[K in keyof T]-?: InvalidField<T[K]>;\n\t\t\t\t\t\t} & ((\n\t\t\t\t\t\t\tmessage: string\n\t\t\t\t\t\t) => StandardSchemaV1.Issue)\n\t\t\t\t\t: Record<string, never>;\n```\n\n</div>\n\n## KitConfig\n\nSee the [configuration reference](/docs/kit/configuration) for details.\n\n## LessThan\n\n<div class=\"ts-block\">\n\n```dts\ntype LessThan<\n\tTNumber extends number,\n\tTArray extends any[] = []\n> = TNumber extends TArray['length']\n\t? TArray[number]\n\t: LessThan<TNumber, [...TArray, TArray['length']]>;\n```\n\n</div>\n\n## Load\n\nThe generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))\nrather than using `Load` directly.\n\n<div class=\"ts-block\">\n\n```dts\ntype Load<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tInputData extends Record<string, unknown> | null = Record<\n\t\tstring,\n\t\tany\n\t> | null,\n\tParentData extends Record<string, unknown> = Record<\n\t\tstring,\n\t\tany\n\t>,\n\tOutputData extends Record<string, unknown> | void =\n\t\tRecord<string, any> | void,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> = (\n\tevent: LoadEvent<Params, InputData, ParentData, RouteId>\n) => MaybePromise<OutputData>;\n```\n\n</div>\n\n## LoadEvent\n\nThe generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))\nrather than using `LoadEvent` directly.\n\n<div class=\"ts-block\">\n\n```dts\ninterface LoadEvent<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tData extends Record<string, unknown> | null = Record<\n\t\tstring,\n\t\tany\n\t> | null,\n\tParentData extends Record<string, unknown> = Record<\n\t\tstring,\n\t\tany\n\t>,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> extends NavigationEvent<Params, RouteId> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nfetch: typeof fetch;\n```\n\n<div class=\"ts-block-property-details\">\n\n`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features:\n\n- It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request.\n- It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context).\n- Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.\n- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](/docs/kit/hooks#Server-hooks-handle)\n- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.\n\nYou can learn more about making credentialed requests with cookies [here](/docs/kit/load#Cookies)\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndata: Data;\n```\n\n<div class=\"ts-block-property-details\">\n\nContains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsetHeaders: (headers: Record<string, string>) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\nIf you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:\n\n```js\n// @errors: 7031\n/// file: src/routes/blog/+page.js\nexport async function load({ fetch, setHeaders }) {\n\tconst url = `https://cms.example.com/articles.json`;\n\tconst response = await fetch(url);\n\n\tsetHeaders({\n\t\tage: response.headers.get('age'),\n\t\t'cache-control': response.headers.get('cache-control')\n\t});\n\n\treturn response.json();\n}\n```\n\nSetting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once.\n\nYou cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API in a server-only `load` function instead.\n\n`setHeaders` has no effect when a `load` function runs in the browser.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nparent: () => Promise<ParentData>;\n```\n\n<div class=\"ts-block-property-details\">\n\n`await parent()` returns data from parent `+layout.js` `load` functions.\nImplicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files.\n\nBe careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndepends: (...deps: Array<`${string}:${string}`>) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\nThis function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/$app-navigation#invalidate) to cause `load` to rerun.\n\nMost of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`.\n\nURLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).\n\nCustom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html).\n\nThe following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.\n\n```js\n// @errors: 7031\n/// file: src/routes/+page.js\nlet count = 0;\nexport async function load({ depends }) {\n\tdepends('increase:count');\n\n\treturn { count: count++ };\n}\n```\n\n```html\n/// file: src/routes/+page.svelte\n<script>\n\timport { invalidate } from '$app/navigation';\n\n\tlet { data } = $props();\n\n\tconst increase = async () => {\n\t\tawait invalidate('increase:count');\n\t}\n</script>\n\n<p>{data.count}<p>\n<button on:click={increase}>Increase Count</button>\n```\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nuntrack: <T>(fn: () => T) => T;\n```\n\n<div class=\"ts-block-property-details\">\n\nUse this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:\n\n```js\n// @errors: 7031\n/// file: src/routes/+page.server.js\nexport async function load({ untrack, url }) {\n\t// Untrack url.pathname so that path changes don't trigger a rerun\n\tif (untrack(() => url.pathname === '/')) {\n\t\treturn { message: 'Welcome!' };\n\t}\n}\n```\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ntracing: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nAccess to spans for tracing. If tracing is not enabled or the function is being run in the browser, these spans will do nothing.\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nenabled: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\nWhether tracing is enabled.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nroot: Span;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe root span for the request. This span is named `sveltekit.handle.root`.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\ncurrent: Span;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe span associated with the current `load` function.\n\n</div>\n</div></div>\n\n</div>\n</div></div>\n\n## LoadProperties\n\n<div class=\"ts-block\">\n\n```dts\ntype LoadProperties<\n\tinput extends Record<string, any> | void\n> = input extends void\n\t? undefined // needs to be undefined, because void will break intellisense\n\t: input extends Record<string, any>\n\t\t? input\n\t\t: unknown;\n```\n\n</div>\n\n## Navigation\n\n<div class=\"ts-block\">\n\n```dts\ntype Navigation =\n\t| NavigationExternal\n\t| NavigationFormSubmit\n\t| NavigationPopState\n\t| NavigationLink;\n```\n\n</div>\n\n## NavigationBase\n\n<div class=\"ts-block\">\n\n```dts\ninterface NavigationBase {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nfrom: NavigationTarget | null;\n```\n\n<div class=\"ts-block-property-details\">\n\nWhere navigation was triggered from\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nto: NavigationTarget | null;\n```\n\n<div class=\"ts-block-property-details\">\n\nWhere navigation is going to/has gone to\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nwillUnload: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\nWhether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation)\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncomplete: Promise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA promise that resolves once the navigation is complete, and rejects if the navigation\nfails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve\n\n</div>\n</div></div>\n\n## NavigationEnter\n\n<div class=\"ts-block\">\n\n```dts\ninterface NavigationEnter extends NavigationBase {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ntype: 'enter';\n```\n\n<div class=\"ts-block-property-details\">\n\nThe type of navigation:\n- `form`: The user submitted a `<form method=\"GET\">`\n- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring\n- `link`: Navigation was triggered by a link click\n- `goto`: Navigation was triggered by a `goto(...)` call or a redirect\n- `popstate`: Navigation was triggered by back/forward navigation\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndelta?: undefined;\n```\n\n<div class=\"ts-block-property-details\">\n\nIn case of a history back/forward navigation, the number of steps to go back/forward\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nevent?: undefined;\n```\n\n<div class=\"ts-block-property-details\">\n\nDispatched `Event` object when navigation occurred by `popstate` or `link`.\n\n</div>\n</div></div>\n\n## NavigationEvent\n\n<div class=\"ts-block\">\n\n```dts\ninterface NavigationEvent<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nparams: Params;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nroute: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\nInfo about the current route\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nid: RouteId;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nurl: URL;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe URL of the current page\n\n</div>\n</div></div>\n\n## NavigationExternal\n\n<div class=\"ts-block\">\n\n```dts\ninterface NavigationExternal extends NavigationBase {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ntype: Exclude<NavigationType, 'enter' | 'popstate' | 'link' | 'form'>;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe type of navigation:\n- `form`: The user submitted a `<form method=\"GET\">`\n- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring\n- `link`: Navigation was triggered by a link click\n- `goto`: Navigation was triggered by a `goto(...)` call or a redirect\n- `popstate`: Navigation was triggered by back/forward navigation\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndelta?: undefined;\n```\n\n<div class=\"ts-block-property-details\">\n\nIn case of a history back/forward navigation, the number of steps to go back/forward\n\n</div>\n</div></div>\n\n## NavigationFormSubmit\n\n<div class=\"ts-block\">\n\n```dts\ninterface NavigationFormSubmit extends NavigationBase {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ntype: 'form';\n```\n\n<div class=\"ts-block-property-details\">\n\nThe type of navigation:\n- `form`: The user submitted a `<form method=\"GET\">`\n- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring\n- `link`: Navigation was triggered by a link click\n- `goto`: Navigation was triggered by a `goto(...)` call or a redirect\n- `popstate`: Navigation was triggered by back/forward navigation\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nevent: SubmitEvent;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe `SubmitEvent` that caused the navigation\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndelta?: undefined;\n```\n\n<div class=\"ts-block-property-details\">\n\nIn case of a history back/forward navigation, the number of steps to go back/forward\n\n</div>\n</div></div>\n\n## NavigationLink\n\n<div class=\"ts-block\">\n\n```dts\ninterface NavigationLink extends NavigationBase {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ntype: 'link';\n```\n\n<div class=\"ts-block-property-details\">\n\nThe type of navigation:\n- `form`: The user submitted a `<form method=\"GET\">`\n- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring\n- `link`: Navigation was triggered by a link click\n- `goto`: Navigation was triggered by a `goto(...)` call or a redirect\n- `popstate`: Navigation was triggered by back/forward navigation\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nevent: PointerEvent;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe `PointerEvent` that caused the navigation\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndelta?: undefined;\n```\n\n<div class=\"ts-block-property-details\">\n\nIn case of a history back/forward navigation, the number of steps to go back/forward\n\n</div>\n</div></div>\n\n## NavigationPopState\n\n<div class=\"ts-block\">\n\n```dts\ninterface NavigationPopState extends NavigationBase {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ntype: 'popstate';\n```\n\n<div class=\"ts-block-property-details\">\n\nThe type of navigation:\n- `form`: The user submitted a `<form method=\"GET\">`\n- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring\n- `link`: Navigation was triggered by a link click\n- `goto`: Navigation was triggered by a `goto(...)` call or a redirect\n- `popstate`: Navigation was triggered by back/forward navigation\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndelta: number;\n```\n\n<div class=\"ts-block-property-details\">\n\nIn case of a history back/forward navigation, the number of steps to go back/forward\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nevent: PopStateEvent;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe `PopStateEvent` that caused the navigation\n\n</div>\n</div></div>\n\n## NavigationTarget\n\nInformation about the target of a specific navigation.\n\n<div class=\"ts-block\">\n\n```dts\ninterface NavigationTarget<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nparams: Params | null;\n```\n\n<div class=\"ts-block-property-details\">\n\nParameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.\nIs `null` if the target is not part of the SvelteKit app (could not be resolved to a route).\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nroute: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\nInfo about the target route\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nid: RouteId | null;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nurl: URL;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe URL that is navigated to\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nscroll: { x: number; y: number } | null;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe scroll position associated with this navigation.\n\nFor the `from` target, this is the scroll position at the moment of navigation.\n\nFor the `to` target, this represents the scroll position that will be or was restored:\n- In `beforeNavigate` and `onNavigate`, this is only available for `popstate` navigations (back/forward button)\n\tand will be `null` for other navigation types, since the final scroll position isn't known\n\tahead of time.\n- In `afterNavigate`, this is always the scroll position that was applied after the navigation\n\tcompleted.\n\n</div>\n</div></div>\n\n## NavigationType\n\n- `enter`: The app has hydrated/started\n- `form`: The user submitted a `<form method=\"GET\">`\n- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring\n- `link`: Navigation was triggered by a link click\n- `goto`: Navigation was triggered by a `goto(...)` call or a redirect\n- `popstate`: Navigation was triggered by back/forward navigation\n\n<div class=\"ts-block\">\n\n```dts\ntype NavigationType =\n\t| 'enter'\n\t| 'form'\n\t| 'leave'\n\t| 'link'\n\t| 'goto'\n\t| 'popstate';\n```\n\n</div>\n\n## NumericRange\n\n<div class=\"ts-block\">\n\n```dts\ntype NumericRange<\n\tTStart extends number,\n\tTEnd extends number\n> = Exclude<TEnd | LessThan<TEnd>, LessThan<TStart>>;\n```\n\n</div>\n\n## OnNavigate\n\nThe argument passed to [`onNavigate`](/docs/kit/$app-navigation#onNavigate) callbacks.\n\n<div class=\"ts-block\">\n\n```dts\ntype OnNavigate = Navigation & {\n\t/**\n\t * The type of navigation:\n\t * - `form`: The user submitted a `<form method=\"GET\">`\n\t * - `link`: Navigation was triggered by a link click\n\t * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect\n\t * - `popstate`: Navigation was triggered by back/forward navigation\n\t */\n\ttype: Exclude<NavigationType, 'enter' | 'leave'>;\n\t/**\n\t * Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.\n\t */\n\twillUnload: false;\n};\n```\n\n</div>\n\n## Page\n\nThe shape of the [`page`](/docs/kit/$app-state#page) reactive object and the [`$page`](/docs/kit/$app-stores) store.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Page<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nurl: URL & { pathname: ResolvedPathname };\n```\n\n<div class=\"ts-block-property-details\">\n\nThe URL of the current page.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nparams: Params;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nroute: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\nInfo about the current route.\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nid: RouteId;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nstatus: number;\n```\n\n<div class=\"ts-block-property-details\">\n\nHTTP status code of the current page.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nerror: App.Error | null;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe error object of the current page, if any. Filled from the `handleError` hooks.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndata: App.PageData & Record<string, any>;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nstate: App.PageState;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe page state, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nform: any;\n```\n\n<div class=\"ts-block-property-details\">\n\nFilled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.\n\n</div>\n</div></div>\n\n## ParamMatcher\n\nThe shape of a param matcher. See [matching](/docs/kit/advanced-routing#Matching) for more info.\n\n<div class=\"ts-block\">\n\n```dts\ntype ParamMatcher = (param: string) => boolean;\n```\n\n</div>\n\n## PrerenderOption\n\n<div class=\"ts-block\">\n\n```dts\ntype PrerenderOption = boolean | 'auto';\n```\n\n</div>\n\n## Redirect\n\nThe object returned by the [`redirect`](/docs/kit/@sveltejs-kit#redirect) function.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Redirect {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nstatus: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nlocation: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe location to redirect to.\n\n</div>\n</div></div>\n\n## RemoteCommand\n\nThe return value of a remote `command` function. See [Remote functions](/docs/kit/remote-functions#command) for full documentation.\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteCommand<Input, Output> = {\n\t(\n\t\targ: undefined extends Input ? Input | void : Input\n\t): Promise<Awaited<Output>> & {\n\t\tupdates(\n\t\t\t...queries: Array<\n\t\t\t\tRemoteQuery<any> | RemoteQueryOverride\n\t\t\t>\n\t\t): Promise<Awaited<Output>>;\n\t};\n\t/** The number of pending command executions */\n\tget pending(): number;\n};\n```\n\n</div>\n\n## RemoteForm\n\nThe return value of a remote `form` function. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteForm<\n\tInput extends RemoteFormInput | void,\n\tOutput\n> = {\n\t/** Attachment that sets up an event handler that intercepts the form submission on the client to prevent a full page reload */\n\t[attachment: symbol]: (node: HTMLFormElement) => void;\n\tmethod: 'POST';\n\t/** The URL to send the form to. */\n\taction: string;\n\t/** Use the `enhance` method to influence what happens when the form is submitted. */\n\tenhance(\n\t\tcallback: (opts: {\n\t\t\tform: HTMLFormElement;\n\t\t\tdata: Input;\n\t\t\tsubmit: () => Promise<void> & {\n\t\t\t\tupdates: (\n\t\t\t\t\t...queries: Array<\n\t\t\t\t\t\tRemoteQuery<any> | RemoteQueryOverride\n\t\t\t\t\t>\n\t\t\t\t) => Promise<void>;\n\t\t\t};\n\t\t}) => void | Promise<void>\n\t): {\n\t\tmethod: 'POST';\n\t\taction: string;\n\t\t[attachment: symbol]: (node: HTMLFormElement) => void;\n\t};\n\t/**\n\t * Create an instance of the form for the given `id`.\n\t * The `id` is stringified and used for deduplication to potentially reuse existing instances.\n\t * Useful when you have multiple forms that use the same remote form action, for example in a loop.\n\t * ```svelte\n\t * {#each todos as todo}\n\t *\t{@const todoForm = updateTodo.for(todo.id)}\n\t *\t<form {...todoForm}>\n\t *\t\t{#if todoForm.result?.invalid}<p>Invalid data</p>{/if}\n\t *\t\t...\n\t *\t</form>\n\t *\t{/each}\n\t * ```\n\t */\n\tfor(\n\t\tid: ExtractId<Input>\n\t): Omit<RemoteForm<Input, Output>, 'for'>;\n\t/** Preflight checks */\n\tpreflight(\n\t\tschema: StandardSchemaV1<Input, any>\n\t): RemoteForm<Input, Output>;\n\t/** Validate the form contents programmatically */\n\tvalidate(options?: {\n\t\t/** Set this to `true` to also show validation issues of fields that haven't been touched yet. */\n\t\tincludeUntouched?: boolean;\n\t\t/** Set this to `true` to only run the `preflight` validation. */\n\t\tpreflightOnly?: boolean;\n\t}): Promise<void>;\n\t/** The result of the form submission */\n\tget result(): Output | undefined;\n\t/** The number of pending submissions */\n\tget pending(): number;\n\t/** Access form fields using object notation */\n\tfields: RemoteFormFieldsRoot<Input>;\n};\n```\n\n</div>\n\n## RemoteFormField\n\nForm field accessor type that provides name(), value(), and issues() methods\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteFormField<Value extends RemoteFormFieldValue> =\n\tRemoteFormFieldMethods<Value> & {\n\t\t/**\n\t\t * Returns an object that can be spread onto an input element with the correct type attribute,\n\t\t * aria-invalid attribute if the field is invalid, and appropriate value/checked property getters/setters.\n\t\t * @example\n\t\t * ```svelte\n\t\t * <input {...myForm.fields.myString.as('text')} />\n\t\t * <input {...myForm.fields.myNumber.as('number')} />\n\t\t * <input {...myForm.fields.myBoolean.as('checkbox')} />\n\t\t * ```\n\t\t */\n\t\tas<T extends RemoteFormFieldType<Value>>(\n\t\t\t...args: AsArgs<T, Value>\n\t\t): InputElementProps<T>;\n\t};\n```\n\n</div>\n\n## RemoteFormFieldType\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteFormFieldType<T> = {\n\t[K in keyof InputTypeMap]: T extends InputTypeMap[K]\n\t\t? K\n\t\t: never;\n}[keyof InputTypeMap];\n```\n\n</div>\n\n## RemoteFormFieldValue\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteFormFieldValue =\n\t| string\n\t| string[]\n\t| number\n\t| boolean\n\t| File\n\t| File[];\n```\n\n</div>\n\n## RemoteFormFields\n\nRecursive type to build form fields structure with proxy access\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteFormFields<T> =\n\tWillRecurseIndefinitely<T> extends true\n\t\t? RecursiveFormFields\n\t\t: NonNullable<T> extends\n\t\t\t\t\t| string\n\t\t\t\t\t| number\n\t\t\t\t\t| boolean\n\t\t\t\t\t| File\n\t\t\t? RemoteFormField<NonNullable<T>>\n\t\t\t: T extends string[] | File[]\n\t\t\t\t? RemoteFormField<T> & {\n\t\t\t\t\t\t[K in number]: RemoteFormField<T[number]>;\n\t\t\t\t\t}\n\t\t\t\t: T extends Array<infer U>\n\t\t\t\t\t? RemoteFormFieldContainer<T> & {\n\t\t\t\t\t\t\t[K in number]: RemoteFormFields<U>;\n\t\t\t\t\t\t}\n\t\t\t\t\t: RemoteFormFieldContainer<T> & {\n\t\t\t\t\t\t\t[K in keyof T]-?: RemoteFormFields<T[K]>;\n\t\t\t\t\t\t};\n```\n\n</div>\n\n## RemoteFormInput\n\n<div class=\"ts-block\">\n\n```dts\ninterface RemoteFormInput {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n[key: string]: MaybeArray<string | number | boolean | File | RemoteFormInput>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## RemoteFormIssue\n\n<div class=\"ts-block\">\n\n```dts\ninterface RemoteFormIssue {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nmessage: string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\npath: Array<string | number>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## RemotePrerenderFunction\n\nThe return value of a remote `prerender` function. See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.\n\n<div class=\"ts-block\">\n\n```dts\ntype RemotePrerenderFunction<Input, Output> = (\n\targ: undefined extends Input ? Input | void : Input\n) => RemoteResource<Output>;\n```\n\n</div>\n\n## RemoteQuery\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteQuery<T> = RemoteResource<T> & {\n\t/**\n\t * On the client, this function will update the value of the query without re-fetching it.\n\t *\n\t * On the server, this can be called in the context of a `command` or `form` and the specified data will accompany the action response back to the client.\n\t * This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.\n\t */\n\tset(value: T): void;\n\t/**\n\t * On the client, this function will re-fetch the query from the server.\n\t *\n\t * On the server, this can be called in the context of a `command` or `form` and the refreshed data will accompany the action response back to the client.\n\t * This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.\n\t */\n\trefresh(): Promise<void>;\n\t/**\n\t * Temporarily override the value of a query. This is used with the `updates` method of a [command](https://svelte.dev/docs/kit/remote-functions#command-Updating-queries) or [enhanced form submission](https://svelte.dev/docs/kit/remote-functions#form-enhance) to provide optimistic updates.\n\t *\n\t * ```svelte\n\t * <script>\n\t *   import { getTodos, addTodo } from './todos.remote.js';\n\t *   const todos = getTodos();\n\t * </script>\n\t *\n\t * <form {...addTodo.enhance(async ({ data, submit }) => {\n\t *   await submit().updates(\n\t *     todos.withOverride((todos) => [...todos, { text: data.get('text') }])\n\t *   );\n\t * })}>\n\t *   <input type=\"text\" name=\"text\" />\n\t *   <button type=\"submit\">Add Todo</button>\n\t * </form>\n\t * ```\n\t */\n\twithOverride(\n\t\tupdate: (current: Awaited<T>) => Awaited<T>\n\t): RemoteQueryOverride;\n};\n```\n\n</div>\n\n## RemoteQueryFunction\n\nThe return value of a remote `query` function. See [Remote functions](/docs/kit/remote-functions#query) for full documentation.\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteQueryFunction<Input, Output> = (\n\targ: undefined extends Input ? Input | void : Input\n) => RemoteQuery<Output>;\n```\n\n</div>\n\n## RemoteQueryOverride\n\n<div class=\"ts-block\">\n\n```dts\ninterface RemoteQueryOverride {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n_key: string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrelease(): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## RemoteResource\n\n<div class=\"ts-block\">\n\n```dts\ntype RemoteResource<T> = Promise<Awaited<T>> & {\n\t/** The error in case the query fails. Most often this is a [`HttpError`](https://svelte.dev/docs/kit/@sveltejs-kit#HttpError) but it isn't guaranteed to be. */\n\tget error(): any;\n\t/** `true` before the first result is available and during refreshes */\n\tget loading(): boolean;\n} & (\n\t\t| {\n\t\t\t\t/** The current value of the query. Undefined until `ready` is `true` */\n\t\t\t\tget current(): undefined;\n\t\t\t\tready: false;\n\t\t  }\n\t\t| {\n\t\t\t\t/** The current value of the query. Undefined until `ready` is `true` */\n\t\t\t\tget current(): Awaited<T>;\n\t\t\t\tready: true;\n\t\t  }\n\t);\n```\n\n</div>\n\n## RequestEvent\n\n<div class=\"ts-block\">\n\n```dts\ninterface RequestEvent<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ncookies: Cookies;\n```\n\n<div class=\"ts-block-property-details\">\n\nGet or set cookies related to the current request\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nfetch: typeof fetch;\n```\n\n<div class=\"ts-block-property-details\">\n\n`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features:\n\n- It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request.\n- It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context).\n- Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.\n- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](/docs/kit/hooks#Server-hooks-handle)\n- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.\n\nYou can learn more about making credentialed requests with cookies [here](/docs/kit/load#Cookies).\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngetClientAddress: () => string;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe client's IP address, set by the adapter.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nlocals: App.Locals;\n```\n\n<div class=\"ts-block-property-details\">\n\nContains custom data that was added to the request within the [`server handle hook`](/docs/kit/hooks#Server-hooks-handle).\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nparams: Params;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nplatform: Readonly<App.Platform> | undefined;\n```\n\n<div class=\"ts-block-property-details\">\n\nAdditional data made available through the adapter.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrequest: Request;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe original request object.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nroute: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\nInfo about the current route.\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nid: RouteId;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsetHeaders: (headers: Record<string, string>) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\nIf you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:\n\n```js\n// @errors: 7031\n/// file: src/routes/blog/+page.js\nexport async function load({ fetch, setHeaders }) {\n\tconst url = `https://cms.example.com/articles.json`;\n\tconst response = await fetch(url);\n\n\tsetHeaders({\n\t\tage: response.headers.get('age'),\n\t\t'cache-control': response.headers.get('cache-control')\n\t});\n\n\treturn response.json();\n}\n```\n\nSetting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once.\n\nYou cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API instead.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nurl: URL;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe requested URL.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nisDataRequest: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n`true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information\nrelated to the data request in this case. Use this property instead if the distinction is important to you.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nisSubRequest: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n`true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ntracing: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nAccess to spans for tracing. If tracing is not enabled, these spans will do nothing.\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nenabled: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\nWhether tracing is enabled.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nroot: Span;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe root span for the request. This span is named `sveltekit.handle.root`.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\ncurrent: Span;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe span associated with the current `handle` hook, `load` function, or form action.\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nisRemoteRequest: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n`true` if the request comes from the client via a remote function. The `url` property will be stripped of the internal information\nrelated to the data request in this case. Use this property instead if the distinction is important to you.\n\n</div>\n</div></div>\n\n## RequestHandler\n\nA `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method.\n\nIt receives `Params` as the first generic argument, which you can skip by using [generated types](/docs/kit/types#Generated-types) instead.\n\n<div class=\"ts-block\">\n\n```dts\ntype RequestHandler<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> = (\n\tevent: RequestEvent<Params, RouteId>\n) => MaybePromise<Response>;\n```\n\n</div>\n\n## Reroute\n\n<blockquote class=\"since note\">\n\nAvailable since 2.3.0\n\n</blockquote>\n\nThe [`reroute`](/docs/kit/hooks#Universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render.\n\n<div class=\"ts-block\">\n\n```dts\ntype Reroute = (event: {\n\turl: URL;\n\tfetch: typeof fetch;\n}) => MaybePromise<void | string>;\n```\n\n</div>\n\n## ResolveOptions\n\n<div class=\"ts-block\">\n\n```dts\ninterface ResolveOptions {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ntransformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise<string | undefined>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `input` the html chunk and the info if this is the last chunk\n\n</div>\n\nApplies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML\n(they could include an element's opening tag but not its closing tag, for example)\nbut they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nfilterSerializedResponseHeaders?: (name: string, value: string) => boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `name` header name\n- `value` header value\n\n</div>\n\nDetermines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`.\nBy default, none will be included.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\npreload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `input` the type of the file and its path\n\n</div>\n\nDetermines what should be added to the `<head>` tag to preload it.\nBy default, `js` and `css` files will be preloaded.\n\n</div>\n</div></div>\n\n## RouteDefinition\n\n<div class=\"ts-block\">\n\n```dts\ninterface RouteDefinition<Config = any> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nid: string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\napi: {\n\tmethods: Array<HttpMethod | '*'>;\n};\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\npage: {\n\tmethods: Array<Extract<HttpMethod, 'GET' | 'POST'>>;\n};\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\npattern: RegExp;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nprerender: PrerenderOption;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsegments: RouteSegment[];\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nmethods: Array<HttpMethod | '*'>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nconfig: Config;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## SSRManifest\n\n<div class=\"ts-block\">\n\n```dts\ninterface SSRManifest {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nappDir: string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nappPath: string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nassets: Set<string>;\n```\n\n<div class=\"ts-block-property-details\">\n\nStatic files from `kit.config.files.assets` and the service worker (if any).\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nmimeTypes: Record<string, string>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n_: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\nprivate fields\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nclient: NonNullable<BuildData['client']>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nnodes: SSRNodeLoader[];\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nremotes: Record<string, () => Promise<any>>;\n```\n\n<div class=\"ts-block-property-details\">\n\nhashed filename -> import to that file\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nroutes: SSRRoute[];\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nprerendered_routes: Set<string>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nmatchers: () => Promise<Record<string, ParamMatcher>>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nserver_assets: Record<string, number>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA `[file]: size` map of all assets imported by server code.\n\n</div>\n</div></div>\n\n</div>\n</div></div>\n\n## ServerInit\n\n<blockquote class=\"since note\">\n\nAvailable since 2.10.0\n\n</blockquote>\n\nThe [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request\n\n<div class=\"ts-block\">\n\n```dts\ntype ServerInit = () => MaybePromise<void>;\n```\n\n</div>\n\n## ServerInitOptions\n\n<div class=\"ts-block\">\n\n```dts\ninterface ServerInitOptions {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nenv: Record<string, string>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA map of environment variables.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nread?: (file: string) => MaybePromise<ReadableStream | null>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work.\n\n</div>\n</div></div>\n\n## ServerLoad\n\nThe generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))\nrather than using `ServerLoad` directly.\n\n<div class=\"ts-block\">\n\n```dts\ntype ServerLoad<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tParentData extends Record<string, any> = Record<\n\t\tstring,\n\t\tany\n\t>,\n\tOutputData extends Record<string, any> | void = Record<\n\t\tstring,\n\t\tany\n\t> | void,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> = (\n\tevent: ServerLoadEvent<Params, ParentData, RouteId>\n) => MaybePromise<OutputData>;\n```\n\n</div>\n\n## ServerLoadEvent\n\n<div class=\"ts-block\">\n\n```dts\ninterface ServerLoadEvent<\n\tParams extends AppLayoutParams<'/'> =\n\t\tAppLayoutParams<'/'>,\n\tParentData extends Record<string, any> = Record<\n\t\tstring,\n\t\tany\n\t>,\n\tRouteId extends AppRouteId | null = AppRouteId | null\n> extends RequestEvent<Params, RouteId> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nparent: () => Promise<ParentData>;\n```\n\n<div class=\"ts-block-property-details\">\n\n`await parent()` returns data from parent `+layout.server.js` `load` functions.\n\nBe careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndepends: (...deps: string[]) => void;\n```\n\n<div class=\"ts-block-property-details\">\n\nThis function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/$app-navigation#invalidate) to cause `load` to rerun.\n\nMost of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`.\n\nURLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).\n\nCustom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html).\n\nThe following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.\n\n```js\n// @errors: 7031\n/// file: src/routes/+page.js\nlet count = 0;\nexport async function load({ depends }) {\n\tdepends('increase:count');\n\n\treturn { count: count++ };\n}\n```\n\n```html\n/// file: src/routes/+page.svelte\n<script>\n\timport { invalidate } from '$app/navigation';\n\n\tlet { data } = $props();\n\n\tconst increase = async () => {\n\t\tawait invalidate('increase:count');\n\t}\n</script>\n\n<p>{data.count}<p>\n<button on:click={increase}>Increase Count</button>\n```\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nuntrack: <T>(fn: () => T) => T;\n```\n\n<div class=\"ts-block-property-details\">\n\nUse this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:\n\n```js\n// @errors: 7031\n/// file: src/routes/+page.js\nexport async function load({ untrack, url }) {\n\t// Untrack url.pathname so that path changes don't trigger a rerun\n\tif (untrack(() => url.pathname === '/')) {\n\t\treturn { message: 'Welcome!' };\n\t}\n}\n```\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ntracing: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nAccess to spans for tracing. If tracing is not enabled, these spans will do nothing.\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nenabled: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\nWhether tracing is enabled.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nroot: Span;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe root span for the request. This span is named `sveltekit.handle.root`.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\ncurrent: Span;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe span associated with the current server `load` function.\n\n</div>\n</div></div>\n\n</div>\n</div></div>\n\n## Snapshot\n\nThe type of `export const snapshot` exported from a page or layout component.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Snapshot<T = any> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ncapture: () => T;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrestore: (snapshot: T) => void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## SubmitFunction\n\n<div class=\"ts-block\">\n\n```dts\ntype SubmitFunction<\n\tSuccess extends Record<string, unknown> | undefined =\n\t\tRecord<string, any>,\n\tFailure extends Record<string, unknown> | undefined =\n\t\tRecord<string, any>\n> = (input: {\n\taction: URL;\n\tformData: FormData;\n\tformElement: HTMLFormElement;\n\tcontroller: AbortController;\n\tsubmitter: HTMLElement | null;\n\tcancel: () => void;\n}) => MaybePromise<\n\t| void\n\t| ((opts: {\n\t\t\tformData: FormData;\n\t\t\tformElement: HTMLFormElement;\n\t\t\taction: URL;\n\t\t\tresult: ActionResult<Success, Failure>;\n\t\t\t/**\n\t\t\t * Call this to get the default behavior of a form submission response.\n\t\t\t * @param options Set `reset: false` if you don't want the `<form>` values to be reset after a successful submission.\n\t\t\t * @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission.\n\t\t\t */\n\t\t\tupdate: (options?: {\n\t\t\t\treset?: boolean;\n\t\t\t\tinvalidateAll?: boolean;\n\t\t\t}) => Promise<void>;\n\t  }) => MaybePromise<void>)\n>;\n```\n\n</div>\n\n## Transport\n\n<blockquote class=\"since note\">\n\nAvailable since 2.11.0\n\n</blockquote>\n\nThe [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook allows you to transport custom types across the server/client boundary.\n\nEach transporter has a pair of `encode` and `decode` functions. On the server, `encode` determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or `false` otherwise).\n\nIn the browser, `decode` turns the encoding back into an instance of the custom type.\n\n```ts\nimport type { Transport } from '@sveltejs/kit';\n\ndeclare class MyCustomType {\n\tdata: any\n}\n\n// hooks.js\nexport const transport: Transport = {\n\tMyCustomType: {\n\t\tencode: (value) => value instanceof MyCustomType && [value.data],\n\t\tdecode: ([data]) => new MyCustomType(data)\n\t}\n};\n```\n\n<div class=\"ts-block\">\n\n```dts\ntype Transport = Record<string, Transporter>;\n```\n\n</div>\n\n## Transporter\n\nA member of the [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Transporter<\n\tT = any,\n\tU = Exclude<\n\t\tany,\n\t\tfalse | 0 | '' | null | undefined | typeof NaN\n\t>\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nencode: (value: T) => false | U;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndecode: (data: U) => T;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## ValidationError\n\nA validation error thrown by `invalid`.\n\n<div class=\"ts-block\">\n\n```dts\ninterface ValidationError {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nissues: StandardSchemaV1.Issue[];\n```\n\n<div class=\"ts-block-property-details\">\n\nThe validation issues\n\n</div>\n</div></div>\n\n\n\n## Private types\n\nThe following are referenced by the public types documented above, but cannot be imported directly:\n\n## AdapterEntry\n\n<div class=\"ts-block\">\n\n```dts\ninterface AdapterEntry {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nid: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nA string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication.\nFor example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both\nbe represented in a Netlify _redirects file as `/foo/:param`, so they share an ID\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nfilter(route: RouteDefinition): boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\nA function that compares the candidate route with the current route to determine\nif it should be grouped with the current route.\n\nUse cases:\n- Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes\n- Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncomplete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA function that is invoked once the entry has been created. This is where you\nshould write the function to the filesystem and generate redirect manifests.\n\n</div>\n</div></div>\n\n## Csp\n\n<div class=\"ts-block\">\n\n```dts\nnamespace Csp {\n\ttype ActionSource = 'strict-dynamic' | 'report-sample';\n\ttype BaseSource =\n\t\t| 'self'\n\t\t| 'unsafe-eval'\n\t\t| 'unsafe-hashes'\n\t\t| 'unsafe-inline'\n\t\t| 'wasm-unsafe-eval'\n\t\t| 'none';\n\ttype CryptoSource =\n\t\t`${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`;\n\ttype FrameSource =\n\t\t| HostSource\n\t\t| SchemeSource\n\t\t| 'self'\n\t\t| 'none';\n\ttype HostNameScheme = `${string}.${string}` | 'localhost';\n\ttype HostSource =\n\t\t`${HostProtocolSchemes}${HostNameScheme}${PortScheme}`;\n\ttype HostProtocolSchemes = `${string}://` | '';\n\ttype HttpDelineator = '/' | '?' | '#' | '\\\\';\n\ttype PortScheme = `:${number}` | '' | ':*';\n\ttype SchemeSource =\n\t\t| 'http:'\n\t\t| 'https:'\n\t\t| 'data:'\n\t\t| 'mediastream:'\n\t\t| 'blob:'\n\t\t| 'filesystem:';\n\ttype Source =\n\t\t| HostSource\n\t\t| SchemeSource\n\t\t| CryptoSource\n\t\t| BaseSource;\n\ttype Sources = Source[];\n}\n```\n\n</div>\n\n## CspDirectives\n\n<div class=\"ts-block\">\n\n```dts\ninterface CspDirectives {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n'child-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'default-src'?: Array<Csp.Source | Csp.ActionSource>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'frame-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'worker-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'connect-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'font-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'img-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'manifest-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'media-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'object-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'prefetch-src'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'script-src'?: Array<Csp.Source | Csp.ActionSource>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'script-src-elem'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'script-src-attr'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'style-src'?: Array<Csp.Source | Csp.ActionSource>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'style-src-elem'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'style-src-attr'?: Csp.Sources;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'base-uri'?: Array<Csp.Source | Csp.ActionSource>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsandbox?: Array<\n| 'allow-downloads-without-user-activation'\n| 'allow-forms'\n| 'allow-modals'\n| 'allow-orientation-lock'\n| 'allow-pointer-lock'\n| 'allow-popups'\n| 'allow-popups-to-escape-sandbox'\n| 'allow-presentation'\n| 'allow-same-origin'\n| 'allow-scripts'\n| 'allow-storage-access-by-user-activation'\n| 'allow-top-navigation'\n| 'allow-top-navigation-by-user-activation'\n>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'form-action'?: Array<Csp.Source | Csp.ActionSource>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'frame-ancestors'?: Array<Csp.HostSource | Csp.SchemeSource | Csp.FrameSource>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'navigate-to'?: Array<Csp.Source | Csp.ActionSource>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'report-uri'?: string[];\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'report-to'?: string[];\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'require-trusted-types-for'?: Array<'script'>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'upgrade-insecure-requests'?: boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'require-sri-for'?: Array<'script' | 'style' | 'script style'>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'block-all-mixed-content'?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n'plugin-types'?: Array<`${string}/${string}` | 'none'>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nreferrer?: Array<\n| 'no-referrer'\n| 'no-referrer-when-downgrade'\n| 'origin'\n| 'origin-when-cross-origin'\n| 'same-origin'\n| 'strict-origin'\n| 'strict-origin-when-cross-origin'\n| 'unsafe-url'\n| 'none'\n>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n\n</div>\n\n</div>\n</div></div>\n\n## DeepPartial\n\n<div class=\"ts-block\">\n\n```dts\ntype DeepPartial<T> = T extends\n\t| Record<PropertyKey, unknown>\n\t| unknown[]\n\t? {\n\t\t\t[K in keyof T]?: T[K] extends\n\t\t\t\t| Record<PropertyKey, unknown>\n\t\t\t\t| unknown[]\n\t\t\t\t? DeepPartial<T[K]>\n\t\t\t\t: T[K];\n\t\t}\n\t: T | undefined;\n```\n\n</div>\n\n## HttpMethod\n\n<div class=\"ts-block\">\n\n```dts\ntype HttpMethod =\n\t| 'GET'\n\t| 'HEAD'\n\t| 'POST'\n\t| 'PUT'\n\t| 'DELETE'\n\t| 'PATCH'\n\t| 'OPTIONS';\n```\n\n</div>\n\n## IsAny\n\n<div class=\"ts-block\">\n\n```dts\ntype IsAny<T> = 0 extends 1 & T ? true : false;\n```\n\n</div>\n\n## Logger\n\n<div class=\"ts-block\">\n\n```dts\ninterface Logger {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n(msg: string): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsuccess(msg: string): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nerror(msg: string): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nwarn(msg: string): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nminor(msg: string): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ninfo(msg: string): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## MaybePromise\n\n<div class=\"ts-block\">\n\n```dts\ntype MaybePromise<T> = T | Promise<T>;\n```\n\n</div>\n\n## PrerenderEntryGeneratorMismatchHandler\n\n<div class=\"ts-block\">\n\n```dts\ninterface PrerenderEntryGeneratorMismatchHandler {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## PrerenderEntryGeneratorMismatchHandlerValue\n\n<div class=\"ts-block\">\n\n```dts\ntype PrerenderEntryGeneratorMismatchHandlerValue =\n\t| 'fail'\n\t| 'warn'\n\t| 'ignore'\n\t| PrerenderEntryGeneratorMismatchHandler;\n```\n\n</div>\n\n## PrerenderHttpErrorHandler\n\n<div class=\"ts-block\">\n\n```dts\ninterface PrerenderHttpErrorHandler {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n(details: {\nstatus: number;\npath: string;\nreferrer: string | null;\nreferenceType: 'linked' | 'fetched';\nmessage: string;\n}): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## PrerenderHttpErrorHandlerValue\n\n<div class=\"ts-block\">\n\n```dts\ntype PrerenderHttpErrorHandlerValue =\n\t| 'fail'\n\t| 'warn'\n\t| 'ignore'\n\t| PrerenderHttpErrorHandler;\n```\n\n</div>\n\n## PrerenderMap\n\n<div class=\"ts-block\">\n\n```dts\ntype PrerenderMap = Map<string, PrerenderOption>;\n```\n\n</div>\n\n## PrerenderMissingIdHandler\n\n<div class=\"ts-block\">\n\n```dts\ninterface PrerenderMissingIdHandler {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n(details: { path: string; id: string; referrers: string[]; message: string }): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## PrerenderMissingIdHandlerValue\n\n<div class=\"ts-block\">\n\n```dts\ntype PrerenderMissingIdHandlerValue =\n\t| 'fail'\n\t| 'warn'\n\t| 'ignore'\n\t| PrerenderMissingIdHandler;\n```\n\n</div>\n\n## PrerenderOption\n\n<div class=\"ts-block\">\n\n```dts\ntype PrerenderOption = boolean | 'auto';\n```\n\n</div>\n\n## PrerenderUnseenRoutesHandler\n\n<div class=\"ts-block\">\n\n```dts\ninterface PrerenderUnseenRoutesHandler {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n(details: { routes: string[]; message: string }): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## PrerenderUnseenRoutesHandlerValue\n\n<div class=\"ts-block\">\n\n```dts\ntype PrerenderUnseenRoutesHandlerValue =\n\t| 'fail'\n\t| 'warn'\n\t| 'ignore'\n\t| PrerenderUnseenRoutesHandler;\n```\n\n</div>\n\n## Prerendered\n\n<div class=\"ts-block\">\n\n```dts\ninterface Prerendered {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\npages: Map<\nstring,\n{\n\t/** The location of the .html file relative to the output directory */\n\tfile: string;\n}\n>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nassets: Map<\nstring,\n{\n\t/** The MIME type of the asset */\n\ttype: string;\n}\n>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA map of `path` to `{ type }` objects.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nredirects: Map<\nstring,\n{\n\tstatus: number;\n\tlocation: string;\n}\n>;\n```\n\n<div class=\"ts-block-property-details\">\n\nA map of redirects encountered during prerendering.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\npaths: string[];\n```\n\n<div class=\"ts-block-property-details\">\n\nAn array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)\n\n</div>\n</div></div>\n\n## RequestOptions\n\n<div class=\"ts-block\">\n\n```dts\ninterface RequestOptions {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ngetClientAddress(): string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nplatform?: App.Platform;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## RouteSegment\n\n<div class=\"ts-block\">\n\n```dts\ninterface RouteSegment {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ncontent: string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndynamic: boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrest: boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## TrailingSlash\n\n<div class=\"ts-block\">\n\n```dts\ntype TrailingSlash = 'never' | 'always' | 'ignore';\n```\n\n</div>","size_bytes":91658,"metadata":{"title":"@sveltejs/kit"},"created_at":"2025-07-18T15:47:38.857Z","updated_at":"2026-03-01T14:00:04.035Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-hooks.md","title":"@sveltejs/kit/hooks","filename":"15-@sveltejs-kit-hooks.md","content":"```js\n// @noErrors\nimport { sequence } from '@sveltejs/kit/hooks';\n```\n\n## sequence\n\nA helper function for sequencing multiple `handle` calls in a middleware-like manner.\nThe behavior for the `handle` options is as follows:\n- `transformPageChunk` is applied in reverse order and merged\n- `preload` is applied in forward order, the first option \"wins\" and no `preload` options after it are called\n- `filterSerializedResponseHeaders` behaves the same as `preload`\n\n```js\n// @errors: 7031\n/// file: src/hooks.server.js\nimport { sequence } from '@sveltejs/kit/hooks';\n\n/** @type {import('@sveltejs/kit').Handle} */\nasync function first({ event, resolve }) {\n\tconsole.log('first pre-processing');\n\tconst result = await resolve(event, {\n\t\ttransformPageChunk: ({ html }) => {\n\t\t\t// transforms are applied in reverse order\n\t\t\tconsole.log('first transform');\n\t\t\treturn html;\n\t\t},\n\t\tpreload: () => {\n\t\t\t// this one wins as it's the first defined in the chain\n\t\t\tconsole.log('first preload');\n\t\t\treturn true;\n\t\t}\n\t});\n\tconsole.log('first post-processing');\n\treturn result;\n}\n\n/** @type {import('@sveltejs/kit').Handle} */\nasync function second({ event, resolve }) {\n\tconsole.log('second pre-processing');\n\tconst result = await resolve(event, {\n\t\ttransformPageChunk: ({ html }) => {\n\t\t\tconsole.log('second transform');\n\t\t\treturn html;\n\t\t},\n\t\tpreload: () => {\n\t\t\tconsole.log('second preload');\n\t\t\treturn true;\n\t\t},\n\t\tfilterSerializedResponseHeaders: () => {\n\t\t\t// this one wins as it's the first defined in the chain\n\t\t\tconsole.log('second filterSerializedResponseHeaders');\n\t\t\treturn true;\n\t\t}\n\t});\n\tconsole.log('second post-processing');\n\treturn result;\n}\n\nexport const handle = sequence(first, second);\n```\n\nThe example above would print:\n\n```\nfirst pre-processing\nfirst preload\nsecond pre-processing\nsecond filterSerializedResponseHeaders\nsecond transform\nfirst transform\nsecond post-processing\nfirst post-processing\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction sequence(...handlers: Handle[]): Handle;\n```\n\n</div>","size_bytes":2044,"metadata":{"title":"@sveltejs/kit/hooks"},"created_at":"2025-07-18T15:47:38.860Z","updated_at":"2025-08-16T14:00:05.369Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md","title":"@sveltejs/kit/node/polyfills","filename":"15-@sveltejs-kit-node-polyfills.md","content":"```js\n// @noErrors\nimport { installPolyfills } from '@sveltejs/kit/node/polyfills';\n```\n\n## installPolyfills\n\nMake various web APIs available as globals:\n- `crypto`\n- `File`\n\n<div class=\"ts-block\">\n\n```dts\nfunction installPolyfills(): void;\n```\n\n</div>","size_bytes":300,"metadata":{"title":"@sveltejs/kit/node/polyfills"},"created_at":"2025-07-18T15:47:38.863Z","updated_at":"2025-07-18T15:47:40.124Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node.md","title":"@sveltejs/kit/node","filename":"15-@sveltejs-kit-node.md","content":"```js\n// @noErrors\nimport {\n\tcreateReadableStream,\n\tgetRequest,\n\tsetResponse\n} from '@sveltejs/kit/node';\n```\n\n## createReadableStream\n\n<blockquote class=\"since note\">\n\nAvailable since 2.4.0\n\n</blockquote>\n\nConverts a file on disk to a readable stream\n\n<div class=\"ts-block\">\n\n```dts\nfunction createReadableStream(file: string): ReadableStream;\n```\n\n</div>\n\n\n\n## getRequest\n\n<div class=\"ts-block\">\n\n```dts\nfunction getRequest({\n\trequest,\n\tbase,\n\tbodySizeLimit\n}: {\n\trequest: import('http').IncomingMessage;\n\tbase: string;\n\tbodySizeLimit?: number;\n}): Promise<Request>;\n```\n\n</div>\n\n\n\n## setResponse\n\n<div class=\"ts-block\">\n\n```dts\nfunction setResponse(\n\tres: import('http').ServerResponse,\n\tresponse: Response\n): Promise<void>;\n```\n\n</div>","size_bytes":778,"metadata":{"title":"@sveltejs/kit/node"},"created_at":"2025-07-18T15:47:38.864Z","updated_at":"2025-07-18T15:47:40.126Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md","title":"@sveltejs/kit/vite","filename":"15-@sveltejs-kit-vite.md","content":"```js\n// @noErrors\nimport { sveltekit } from '@sveltejs/kit/vite';\n```\n\n## sveltekit\n\nReturns the SvelteKit Vite plugins.\n\n<div class=\"ts-block\">\n\n```dts\nfunction sveltekit(): Promise<import('vite').Plugin[]>;\n```\n\n</div>","size_bytes":260,"metadata":{"title":"@sveltejs/kit/vite"},"created_at":"2025-07-18T15:47:38.865Z","updated_at":"2025-07-18T15:47:40.128Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/20-$app-environment.md","title":"$app/environment","filename":"20-$app-environment.md","content":"```js\n// @noErrors\nimport { browser, building, dev, version } from '$app/environment';\n```\n\n## browser\n\n`true` if the app is running in the browser.\n\n<div class=\"ts-block\">\n\n```dts\nconst browser: boolean;\n```\n\n</div>\n\n\n\n## building\n\nSvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering.\n\n<div class=\"ts-block\">\n\n```dts\nconst building: boolean;\n```\n\n</div>\n\n\n\n## dev\n\nWhether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`.\n\n<div class=\"ts-block\">\n\n```dts\nconst dev: boolean;\n```\n\n</div>\n\n\n\n## version\n\nThe value of `config.kit.version.name`.\n\n<div class=\"ts-block\">\n\n```dts\nconst version: string;\n```\n\n</div>","size_bytes":780,"metadata":{"title":"$app/environment"},"created_at":"2025-07-18T15:47:38.867Z","updated_at":"2025-07-18T15:47:40.129Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/20-$app-forms.md","title":"$app/forms","filename":"20-$app-forms.md","content":"```js\n// @noErrors\nimport { applyAction, deserialize, enhance } from '$app/forms';\n```\n\n## applyAction\n\nThis action updates the `form` property of the current page with the given data and updates `page.status`.\nIn case of an error, it redirects to the nearest error page.\n\n<div class=\"ts-block\">\n\n```dts\nfunction applyAction<\n\tSuccess extends Record<string, unknown> | undefined,\n\tFailure extends Record<string, unknown> | undefined\n>(\n\tresult: import('@sveltejs/kit').ActionResult<\n\t\tSuccess,\n\t\tFailure\n\t>\n): Promise<void>;\n```\n\n</div>\n\n\n\n## deserialize\n\nUse this function to deserialize the response from a form submission.\nUsage:\n\n```js\n// @errors: 7031\nimport { deserialize } from '$app/forms';\n\nasync function handleSubmit(event) {\n\tconst response = await fetch('/form?/action', {\n\t\tmethod: 'POST',\n\t\tbody: new FormData(event.target)\n\t});\n\n\tconst result = deserialize(await response.text());\n\t// ...\n}\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction deserialize<\n\tSuccess extends Record<string, unknown> | undefined,\n\tFailure extends Record<string, unknown> | undefined\n>(\n\tresult: string\n): import('@sveltejs/kit').ActionResult<Success, Failure>;\n```\n\n</div>\n\n\n\n## enhance\n\nThis action enhances a `<form>` element that otherwise would work without JavaScript.\n\nThe `submit` function is called upon submission with the given FormData and the `action` that should be triggered.\nIf `cancel` is called, the form will not be submitted.\nYou can use the abort `controller` to cancel the submission in case another one starts.\nIf a function is returned, that function is called with the response from the server.\nIf nothing is returned, the fallback will be used.\n\nIf this function or its return value isn't set, it\n- falls back to updating the `form` prop with the returned data if the action is on the same page as the form\n- updates `page.status`\n- resets the `<form>` element and invalidates all data in case of successful submission with no redirect response\n- redirects in case of a redirect response\n- redirects to the nearest error page in case of an unexpected error\n\nIf you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback.\nIt accepts an options object\n- `reset: false` if you don't want the `<form>` values to be reset after a successful submission\n- `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission\n\n<div class=\"ts-block\">\n\n```dts\nfunction enhance<\n\tSuccess extends Record<string, unknown> | undefined,\n\tFailure extends Record<string, unknown> | undefined\n>(\n\tform_element: HTMLFormElement,\n\tsubmit?: import('@sveltejs/kit').SubmitFunction<\n\t\tSuccess,\n\t\tFailure\n\t>\n): {\n\tdestroy(): void;\n};\n```\n\n</div>","size_bytes":2747,"metadata":{"title":"$app/forms"},"created_at":"2025-07-18T15:47:38.868Z","updated_at":"2025-07-18T15:47:40.131Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/20-$app-navigation.md","title":"$app/navigation","filename":"20-$app-navigation.md","content":"```js\n// @noErrors\nimport {\n\tafterNavigate,\n\tbeforeNavigate,\n\tdisableScrollHandling,\n\tgoto,\n\tinvalidate,\n\tinvalidateAll,\n\tonNavigate,\n\tpreloadCode,\n\tpreloadData,\n\tpushState,\n\trefreshAll,\n\treplaceState\n} from '$app/navigation';\n```\n\n## afterNavigate\n\nA lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a URL.\n\n`afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted.\n\n<div class=\"ts-block\">\n\n```dts\nfunction afterNavigate(\n\tcallback: (\n\t\tnavigation: import('@sveltejs/kit').AfterNavigate\n\t) => void\n): void;\n```\n\n</div>\n\n\n\n## beforeNavigate\n\nA navigation interceptor that triggers before we navigate to a URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls.\n\nCalling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response.\n\nWhen a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`.\n\nIf the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`.\n\n`beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted.\n\n<div class=\"ts-block\">\n\n```dts\nfunction beforeNavigate(\n\tcallback: (\n\t\tnavigation: import('@sveltejs/kit').BeforeNavigate\n\t) => void\n): void;\n```\n\n</div>\n\n\n\n## disableScrollHandling\n\nIf called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling.\nThis is generally discouraged, since it breaks user expectations.\n\n<div class=\"ts-block\">\n\n```dts\nfunction disableScrollHandling(): void;\n```\n\n</div>\n\n\n\n## goto\n\nAllows you to navigate programmatically to a given route, with options such as keeping the current element focused.\nReturns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`.\n\nFor external URLs, use `window.location = url` instead of calling `goto(url)`.\n\n<div class=\"ts-block\">\n\n```dts\nfunction goto(\n\turl: string | URL,\n\topts?: {\n\t\treplaceState?: boolean | undefined;\n\t\tnoScroll?: boolean | undefined;\n\t\tkeepFocus?: boolean | undefined;\n\t\tinvalidateAll?: boolean | undefined;\n\t\tinvalidate?:\n\t\t\t| (string | URL | ((url: URL) => boolean))[]\n\t\t\t| undefined;\n\t\tstate?: App.PageState | undefined;\n\t}\n): Promise<void>;\n```\n\n</div>\n\n\n\n## invalidate\n\nCauses any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated.\n\nIf the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters).\nTo create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL.\n\nThe `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned.\nThis can be useful if you want to invalidate based on a pattern instead of a exact match.\n\n```ts\n// Example: Match '/path' regardless of the query parameters\nimport { invalidate } from '$app/navigation';\n\ninvalidate((url) => url.pathname === '/path');\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction invalidate(\n\tresource: string | URL | ((url: URL) => boolean)\n): Promise<void>;\n```\n\n</div>\n\n\n\n## invalidateAll\n\nCauses all `load` and `query` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated.\n\n<div class=\"ts-block\">\n\n```dts\nfunction invalidateAll(): Promise<void>;\n```\n\n</div>\n\n\n\n## onNavigate\n\nA lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations.\n\nIf you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.\n\nIf a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated.\n\n`onNavigate` must be called during a component initialization. It remains active as long as the component is mounted.\n\n<div class=\"ts-block\">\n\n```dts\nfunction onNavigate(\n\tcallback: (\n\t\tnavigation: import('@sveltejs/kit').OnNavigate\n\t) => MaybePromise<(() => void) | void>\n): void;\n```\n\n</div>\n\n\n\n## preloadCode\n\nProgrammatically imports the code for routes that haven't yet been fetched.\nTypically, you might call this to speed up subsequent navigation.\n\nYou can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`).\n\nUnlike `preloadData`, this won't call `load` functions.\nReturns a Promise that resolves when the modules have been imported.\n\n<div class=\"ts-block\">\n\n```dts\nfunction preloadCode(pathname: string): Promise<void>;\n```\n\n</div>\n\n\n\n## preloadData\n\nProgrammatically preloads the given page, which means\n 1. ensuring that the code for the page is loaded, and\n 2. calling the page's load function with the appropriate options.\n\nThis is the same behaviour that SvelteKit triggers when the user taps or mouses over an `<a>` element with `data-sveltekit-preload-data`.\nIf the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous.\nReturns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete.\n\n<div class=\"ts-block\">\n\n```dts\nfunction preloadData(href: string): Promise<\n\t| {\n\t\t\ttype: 'loaded';\n\t\t\tstatus: number;\n\t\t\tdata: Record<string, any>;\n\t  }\n\t| {\n\t\t\ttype: 'redirect';\n\t\t\tlocation: string;\n\t  }\n>;\n```\n\n</div>\n\n\n\n## pushState\n\nProgrammatically create a new history entry with the given `page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing).\n\n<div class=\"ts-block\">\n\n```dts\nfunction pushState(\n\turl: string | URL,\n\tstate: App.PageState\n): void;\n```\n\n</div>\n\n\n\n## refreshAll\n\nCauses all currently active remote functions to refresh, and all `load` functions belonging to the currently active page to re-run (unless disabled via the option argument).\nReturns a `Promise` that resolves when the page is subsequently updated.\n\n<div class=\"ts-block\">\n\n```dts\nfunction refreshAll({\n\tincludeLoadFunctions\n}?: {\n\tincludeLoadFunctions?: boolean;\n}): Promise<void>;\n```\n\n</div>\n\n\n\n## replaceState\n\nProgrammatically replace the current history entry with the given `page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing).\n\n<div class=\"ts-block\">\n\n```dts\nfunction replaceState(\n\turl: string | URL,\n\tstate: App.PageState\n): void;\n```\n\n</div>","size_bytes":7514,"metadata":{"title":"$app/navigation"},"created_at":"2025-07-18T15:47:38.870Z","updated_at":"2025-12-09T02:00:05.826Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md","title":"$app/paths","filename":"20-$app-paths.md","content":"```js\n// @noErrors\nimport { asset, assets, base, match, resolve, resolveRoute } from '$app/paths';\n```\n\n## asset\n\n<blockquote class=\"since note\">\n\nAvailable since 2.26\n\n</blockquote>\n\nResolve the URL of an asset in your `static` directory, by prefixing it with [`config.kit.paths.assets`](/docs/kit/configuration#paths) if configured, or otherwise by prefixing it with the base path.\n\nDuring server rendering, the base path is relative and depends on the page currently being rendered.\n\n```svelte\n<script>\n\timport { asset } from '$app/paths';\n</script>\n\n<img alt=\"a potato\" src={asset('/potato.jpg')} />\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction asset(file: Asset): string;\n```\n\n</div>\n\n\n\n## assets\n\n<blockquote class=\"tag deprecated note\">\n\nUse [`asset(...)`](/docs/kit/$app-paths#asset) instead\n\n</blockquote>\n\nAn absolute path that matches [`config.kit.paths.assets`](/docs/kit/configuration#paths).\n\n\n<div class=\"ts-block\">\n\n```dts\nlet assets:\n\t| ''\n\t| `https://${string}`\n\t| `http://${string}`\n\t| '/_svelte_kit_assets';\n```\n\n</div>\n\n\n\n## base\n\n<blockquote class=\"tag deprecated note\">\n\nUse [`resolve(...)`](/docs/kit/$app-paths#resolve) instead\n\n</blockquote>\n\nA string that matches [`config.kit.paths.base`](/docs/kit/configuration#paths).\n\nExample usage: `<a href=\"{base}/your-page\">Link</a>`\n\n<div class=\"ts-block\">\n\n```dts\nlet base: '' | `/${string}`;\n```\n\n</div>\n\n\n\n## match\n\n<blockquote class=\"since note\">\n\nAvailable since 2.52.0\n\n</blockquote>\n\nMatch a path or URL to a route ID and extracts any parameters.\n\n```js\n// @errors: 7031\nimport { match } from '$app/paths';\n\nconst route = await match('/blog/hello-world');\n\nif (route?.id === '/blog/[slug]') {\n\tconst slug = route.params.slug;\n\tconst response = await fetch(`/api/posts/${slug}`);\n\tconst post = await response.json();\n}\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction match(\n\turl: Pathname_1 | URL | (string & {})\n): Promise<{\n\tid: RouteId;\n\tparams: Record<string, string>;\n} | null>;\n```\n\n</div>\n\n\n\n## resolve\n\n<blockquote class=\"since note\">\n\nAvailable since 2.26\n\n</blockquote>\n\nResolve a pathname by prefixing it with the base path, if any, or resolve a route ID by populating dynamic segments with parameters.\n\nDuring server rendering, the base path is relative and depends on the page currently being rendered.\n\n```js\n// @errors: 7031\nimport { resolve } from '$app/paths';\n\n// using a pathname\nconst resolved = resolve(`/blog/hello-world`);\n\n// using a route ID plus parameters\nconst resolved = resolve('/blog/[slug]', {\n\tslug: 'hello-world'\n});\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction resolve<\n\tT extends\n\t\t| RouteIdWithSearchOrHash\n\t\t| PathnameWithSearchOrHash\n>(...args: ResolveArgs<T>): ResolvedPathname;\n```\n\n</div>\n\n\n\n## resolveRoute\n\n<blockquote class=\"tag deprecated note\">\n\nUse [`resolve(...)`](/docs/kit/$app-paths#resolve) instead\n\n</blockquote>\n\n<div class=\"ts-block\">\n\n```dts\nfunction resolveRoute<\n\tT extends\n\t\t| RouteIdWithSearchOrHash\n\t\t| PathnameWithSearchOrHash\n>(...args: ResolveArgs<T>): ResolvedPathname;\n```\n\n</div>","size_bytes":3050,"metadata":{"title":"$app/paths"},"created_at":"2025-07-18T15:47:38.872Z","updated_at":"2026-03-04T02:00:04.103Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/20-$app-server.md","title":"$app/server","filename":"20-$app-server.md","content":"```js\n// @noErrors\nimport {\n\tcommand,\n\tform,\n\tgetRequestEvent,\n\tprerender,\n\tquery,\n\tread\n} from '$app/server';\n```\n\n## command\n\n<blockquote class=\"since note\">\n\nAvailable since 2.27\n\n</blockquote>\n\nCreates a remote command. When called from the browser, the function will be invoked on the server via a `fetch` call.\n\nSee [Remote functions](/docs/kit/remote-functions#command) for full documentation.\n\n<div class=\"ts-block\">\n\n```dts\nfunction command<Output>(\n\tfn: () => Output\n): RemoteCommand<void, Output>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction command<Input, Output>(\n\tvalidate: 'unchecked',\n\tfn: (arg: Input) => Output\n): RemoteCommand<Input, Output>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction command<Schema extends StandardSchemaV1, Output>(\n\tvalidate: Schema,\n\tfn: (arg: StandardSchemaV1.InferOutput<Schema>) => Output\n): RemoteCommand<\n\tStandardSchemaV1.InferInput<Schema>,\n\tOutput\n>;\n```\n\n</div>\n\n\n\n## form\n\n<blockquote class=\"since note\">\n\nAvailable since 2.27\n\n</blockquote>\n\nCreates a form object that can be spread onto a `<form>` element.\n\nSee [Remote functions](/docs/kit/remote-functions#form) for full documentation.\n\n<div class=\"ts-block\">\n\n```dts\nfunction form<Output>(\n\tfn: () => MaybePromise<Output>\n): RemoteForm<void, Output>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction form<Input extends RemoteFormInput, Output>(\n\tvalidate: 'unchecked',\n\tfn: (\n\t\tdata: Input,\n\t\tissue: InvalidField<Input>\n\t) => MaybePromise<Output>\n): RemoteForm<Input, Output>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction form<\n\tSchema extends StandardSchemaV1<\n\t\tRemoteFormInput,\n\t\tRecord<string, any>\n\t>,\n\tOutput\n>(\n\tvalidate: Schema,\n\tfn: (\n\t\tdata: StandardSchemaV1.InferOutput<Schema>,\n\t\tissue: InvalidField<StandardSchemaV1.InferInput<Schema>>\n\t) => MaybePromise<Output>\n): RemoteForm<StandardSchemaV1.InferInput<Schema>, Output>;\n```\n\n</div>\n\n\n\n## getRequestEvent\n\n<blockquote class=\"since note\">\n\nAvailable since 2.20.0\n\n</blockquote>\n\nReturns the current `RequestEvent`. Can be used inside server hooks, server `load` functions, actions, and endpoints (and functions called by them).\n\nIn environments without [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage), this must be called synchronously (i.e. not after an `await`).\n\n<div class=\"ts-block\">\n\n```dts\nfunction getRequestEvent(): RequestEvent;\n```\n\n</div>\n\n\n\n## prerender\n\n<blockquote class=\"since note\">\n\nAvailable since 2.27\n\n</blockquote>\n\nCreates a remote prerender function. When called from the browser, the function will be invoked on the server via a `fetch` call.\n\nSee [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.\n\n<div class=\"ts-block\">\n\n```dts\nfunction prerender<Output>(\n\tfn: () => MaybePromise<Output>,\n\toptions?:\n\t\t| {\n\t\t\t\tinputs?: RemotePrerenderInputsGenerator<void>;\n\t\t\t\tdynamic?: boolean;\n\t\t  }\n\t\t| undefined\n): RemotePrerenderFunction<void, Output>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction prerender<Input, Output>(\n\tvalidate: 'unchecked',\n\tfn: (arg: Input) => MaybePromise<Output>,\n\toptions?:\n\t\t| {\n\t\t\t\tinputs?: RemotePrerenderInputsGenerator<Input>;\n\t\t\t\tdynamic?: boolean;\n\t\t  }\n\t\t| undefined\n): RemotePrerenderFunction<Input, Output>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction prerender<Schema extends StandardSchemaV1, Output>(\n\tschema: Schema,\n\tfn: (\n\t\targ: StandardSchemaV1.InferOutput<Schema>\n\t) => MaybePromise<Output>,\n\toptions?:\n\t\t| {\n\t\t\t\tinputs?: RemotePrerenderInputsGenerator<\n\t\t\t\t\tStandardSchemaV1.InferInput<Schema>\n\t\t\t\t>;\n\t\t\t\tdynamic?: boolean;\n\t\t  }\n\t\t| undefined\n): RemotePrerenderFunction<\n\tStandardSchemaV1.InferInput<Schema>,\n\tOutput\n>;\n```\n\n</div>\n\n\n\n## query\n\n<blockquote class=\"since note\">\n\nAvailable since 2.27\n\n</blockquote>\n\nCreates a remote query. When called from the browser, the function will be invoked on the server via a `fetch` call.\n\nSee [Remote functions](/docs/kit/remote-functions#query) for full documentation.\n\n<div class=\"ts-block\">\n\n```dts\nfunction query<Output>(\n\tfn: () => MaybePromise<Output>\n): RemoteQueryFunction<void, Output>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction query<Input, Output>(\n\tvalidate: 'unchecked',\n\tfn: (arg: Input) => MaybePromise<Output>\n): RemoteQueryFunction<Input, Output>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction query<Schema extends StandardSchemaV1, Output>(\n\tschema: Schema,\n\tfn: (\n\t\targ: StandardSchemaV1.InferOutput<Schema>\n\t) => MaybePromise<Output>\n): RemoteQueryFunction<\n\tStandardSchemaV1.InferInput<Schema>,\n\tOutput\n>;\n```\n\n</div>\n\n\n\n## read\n\n<blockquote class=\"since note\">\n\nAvailable since 2.4.0\n\n</blockquote>\n\nRead the contents of an imported asset from the filesystem\n\n```js\n// @errors: 7031\nimport { read } from '$app/server';\nimport somefile from './somefile.txt';\n\nconst asset = read(somefile);\nconst text = await asset.text();\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction read(asset: string): Response;\n```\n\n</div>\n\n\n\n## query\n\n<div class=\"ts-block\">\n\n```dts\nnamespace query {\n\t/**\n\t * Creates a batch query function that collects multiple calls and executes them in a single request\n\t *\n\t * See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.batch) for full documentation.\n\t *\n\t * @since 2.35\n\t */\n\tfunction batch<Input, Output>(\n\t\tvalidate: 'unchecked',\n\t\tfn: (\n\t\t\targs: Input[]\n\t\t) => MaybePromise<(arg: Input, idx: number) => Output>\n\t): RemoteQueryFunction<Input, Output>;\n\t/**\n\t * Creates a batch query function that collects multiple calls and executes them in a single request\n\t *\n\t * See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.batch) for full documentation.\n\t *\n\t * @since 2.35\n\t */\n\tfunction batch<Schema extends StandardSchemaV1, Output>(\n\t\tschema: Schema,\n\t\tfn: (\n\t\t\targs: StandardSchemaV1.InferOutput<Schema>[]\n\t\t) => MaybePromise<\n\t\t\t(\n\t\t\t\targ: StandardSchemaV1.InferOutput<Schema>,\n\t\t\t\tidx: number\n\t\t\t) => Output\n\t\t>\n\t): RemoteQueryFunction<\n\t\tStandardSchemaV1.InferInput<Schema>,\n\t\tOutput\n\t>;\n}\n```\n\n</div>","size_bytes":6040,"metadata":{"title":"$app/server"},"created_at":"2025-07-18T15:47:38.874Z","updated_at":"2025-11-21T14:00:03.860Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/20-$app-state.md","title":"$app/state","filename":"20-$app-state.md","content":"SvelteKit makes three read-only state objects available via the `$app/state` module — `page`, `navigating` and `updated`.\n\n> This module was added in 2.12. If you're using an earlier version of SvelteKit, use [`$app/stores`]($app-stores) instead.\n\n\n\n```js\n// @noErrors\nimport { navigating, page, updated } from '$app/state';\n```\n\n## navigating\n\nA read-only object representing an in-progress navigation, with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties.\nValues are `null` when no navigation is occurring, or during server rendering.\n\n<div class=\"ts-block\">\n\n```dts\nconst navigating:\n\t| import('@sveltejs/kit').Navigation\n\t| {\n\t\t\tfrom: null;\n\t\t\tto: null;\n\t\t\ttype: null;\n\t\t\twillUnload: null;\n\t\t\tdelta: null;\n\t\t\tcomplete: null;\n\t  };\n```\n\n</div>\n\n\n\n## page\n\nA read-only reactive object with information about the current page, serving several use cases:\n- retrieving the combined `data` of all pages/layouts anywhere in your component tree (also see [loading data](/docs/kit/load))\n- retrieving the current value of the `form` prop anywhere in your component tree (also see [form actions](/docs/kit/form-actions))\n- retrieving the page state that was set through `goto`, `pushState` or `replaceState` (also see [goto](/docs/kit/$app-navigation#goto) and [shallow routing](/docs/kit/shallow-routing))\n- retrieving metadata such as the URL you're on, the current route and its parameters, and whether or not there was an error\n\n```svelte\n<!file: +layout.svelte>\n<script>\n\timport { page } from '$app/state';\n</script>\n\n<p>Currently at {page.url.pathname}</p>\n\n{#if page.error}\n\t<span class=\"red\">Problem detected</span>\n{:else}\n\t<span class=\"small\">All systems operational</span>\n{/if}\n```\n\nChanges to `page` are available exclusively with runes. (The legacy reactivity syntax will not reflect any changes)\n\n```svelte\n<!file: +page.svelte>\n<script>\n\timport { page } from '$app/state';\n\tconst id = $derived(page.params.id); // This will correctly update id for usage on this page\n\t$: badId = page.params.id; // Do not use; will never update after initial load\n</script>\n```\n\nOn the server, values can only be read during rendering (in other words _not_ in e.g. `load` functions). In the browser, the values can be read at any time.\n\n<div class=\"ts-block\">\n\n```dts\nconst page: import('@sveltejs/kit').Page;\n```\n\n</div>\n\n\n\n## updated\n\nA read-only reactive value that's initially `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update `current` to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling.\n\n<div class=\"ts-block\">\n\n```dts\nconst updated: {\n\tget current(): boolean;\n\tcheck(): Promise<boolean>;\n};\n```\n\n</div>","size_bytes":2806,"metadata":{"title":"$app/state"},"created_at":"2025-07-18T15:47:38.875Z","updated_at":"2025-07-18T15:47:40.138Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/20-$app-stores.md","title":"$app/stores","filename":"20-$app-stores.md","content":"This module contains store-based equivalents of the exports from [`$app/state`]($app-state). If you're using SvelteKit 2.12 or later, use that module instead.\n\n\n\n```js\n// @noErrors\nimport { getStores, navigating, page, updated } from '$app/stores';\n```\n\n## getStores\n\n<div class=\"ts-block\">\n\n```dts\nfunction getStores(): {\n\tpage: typeof page;\n\n\tnavigating: typeof navigating;\n\n\tupdated: typeof updated;\n};\n```\n\n</div>\n\n\n\n## navigating\n\n<blockquote class=\"tag deprecated note\">\n\nUse `navigating` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))\n\n</blockquote>\n\nA readable store.\nWhen navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties.\nWhen navigating finishes, its value reverts to `null`.\n\nOn the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.\n\n<div class=\"ts-block\">\n\n```dts\nconst navigating: import('svelte/store').Readable<\n\timport('@sveltejs/kit').Navigation | null\n>;\n```\n\n</div>\n\n\n\n## page\n\n<blockquote class=\"tag deprecated note\">\n\nUse `page` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))\n\n</blockquote>\n\nA readable store whose value contains page data.\n\nOn the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.\n\n<div class=\"ts-block\">\n\n```dts\nconst page: import('svelte/store').Readable<\n\timport('@sveltejs/kit').Page\n>;\n```\n\n</div>\n\n\n\n## updated\n\n<blockquote class=\"tag deprecated note\">\n\nUse `updated` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))\n\n</blockquote>\n\nA readable store whose initial value is `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling.\n\nOn the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.\n\n<div class=\"ts-block\">\n\n```dts\nconst updated: import('svelte/store').Readable<boolean> & {\n\tcheck(): Promise<boolean>;\n};\n```\n\n</div>","size_bytes":2530,"metadata":{"title":"$app/stores"},"created_at":"2025-07-18T15:47:38.877Z","updated_at":"2025-07-18T15:47:40.145Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/20-$app-types.md","title":"$app/types","filename":"20-$app-types.md","content":"This module contains generated types for the routes in your app.\n\n<blockquote class=\"since note\">\n\t<p>Available since 2.26</p>\n</blockquote>\n\n```js\n// @noErrors\nimport type { RouteId, RouteParams, LayoutParams } from '$app/types';\n```\n\n## Asset\n\nA union of all the filenames of assets contained in your `static` directory, plus a `string` wildcard for asset paths generated from `import` declarations.\n\n<div class=\"ts-block\">\n\n```dts\ntype Asset = '/favicon.png' | '/robots.txt' | (string & {});\n```\n\n</div>\n\n## RouteId\n\nA union of all the route IDs in your app. Used for `page.route.id` and `event.route.id`.\n\n<div class=\"ts-block\">\n\n```dts\ntype RouteId = '/' | '/my-route' | '/my-other-route/[param]';\n```\n\n</div>\n\n## Pathname\n\nA union of all valid pathnames in your app.\n\n<div class=\"ts-block\">\n\n```dts\ntype Pathname = '/' | '/my-route' | `/my-other-route/${string}` & {};\n```\n\n</div>\n\n## ResolvedPathname\n\nSimilar to `Pathname`, but possibly prefixed with a [base path](configuration#paths). Used for `page.url.pathname`.\n\n<div class=\"ts-block\">\n\n```dts\ntype ResolvedPathname = `${'' | `/${string}`}/` | `${'' | `/${string}`}/my-route` | `${'' | `/${string}`}/my-other-route/${string}` | {};\n```\n\n</div>\n\n## RouteParams\n\nA utility for getting the parameters associated with a given route.\n\n```ts\n// @errors: 2552\ntype BlogParams = RouteParams<'/blog/[slug]'>; // { slug: string }\n```\n\n<div class=\"ts-block\">\n\n```dts\ntype RouteParams<T extends RouteId> = { /* generated */ } | Record<string, never>;\n```\n\n</div>\n\n## LayoutParams\n\nA utility for getting the parameters associated with a given layout, which is similar to `RouteParams` but also includes optional parameters for any child route.\n\n<div class=\"ts-block\">\n\n```dts\ntype RouteParams<T extends RouteId> = { /* generated */ } | Record<string, never>;\n```\n\n</div>","size_bytes":1848,"metadata":{"title":"$app/types"},"created_at":"2025-07-25T02:00:04.077Z","updated_at":"2025-08-20T14:00:05.538Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-private.md","title":"$env/dynamic/private","filename":"25-$env-dynamic-private.md","content":"This module provides access to environment variables set _dynamically_ at runtime and that are limited to _private_ access.\n\n|         | Runtime                                                                    | Build time                                                               |\n| ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |\n| Private | [`$env/dynamic/private`](/docs/kit/$env-dynamic-private) | [`$env/static/private`](/docs/kit/$env-static-private) |\n| Public  | [`$env/dynamic/public`](/docs/kit/$env-dynamic-public)   | [`$env/static/public`](/docs/kit/$env-static-public)   |\n\nDynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](/docs/kit/cli)), this is equivalent to `process.env`.\n\n**_Private_ access:**\n\n- This module cannot be imported into client-side code\n- This module includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) (if configured)\n\n\n>\n> ```env\n> MY_FEATURE_FLAG=\n> ```\n>\n> You can override `.env` values from the command line like so:\n>\n> ```sh\n> MY_FEATURE_FLAG=\"enabled\" npm run dev\n> ```\n\nFor example, given the following runtime environment:\n\n```env\nENVIRONMENT=production\nPUBLIC_BASE_URL=http://site.com\n```\n\nWith the default `publicPrefix` and `privatePrefix`:\n\n```ts\nimport { env } from '$env/dynamic/private';\n\nconsole.log(env.ENVIRONMENT); // => \"production\"\nconsole.log(env.PUBLIC_BASE_URL); // => undefined\n```","size_bytes":1804,"metadata":{"title":"$env/dynamic/private"},"created_at":"2025-07-18T15:47:38.878Z","updated_at":"2026-02-26T02:00:03.922Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-public.md","title":"$env/dynamic/public","filename":"25-$env-dynamic-public.md","content":"This module provides access to environment variables set _dynamically_ at runtime and that are _publicly_ accessible.\n\n|         | Runtime                                                                    | Build time                                                               |\n| ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |\n| Private | [`$env/dynamic/private`](/docs/kit/$env-dynamic-private) | [`$env/static/private`](/docs/kit/$env-static-private) |\n| Public  | [`$env/dynamic/public`](/docs/kit/$env-dynamic-public)   | [`$env/static/public`](/docs/kit/$env-static-public)   |\n\nDynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](/docs/kit/cli)), this is equivalent to `process.env`.\n\n**_Public_ access:**\n\n- This module _can_ be imported into client-side code\n- **Only** variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included\n\n\n>\n> ```env\n> MY_FEATURE_FLAG=\n> ```\n>\n> You can override `.env` values from the command line like so:\n>\n> ```sh\n> MY_FEATURE_FLAG=\"enabled\" npm run dev\n> ```\n\nFor example, given the following runtime environment:\n\n```env\nENVIRONMENT=production\nPUBLIC_BASE_URL=http://example.com\n```\n\nWith the default `publicPrefix` and `privatePrefix`:\n\n```ts\nimport { env } from '$env/dynamic/public';\nconsole.log(env.ENVIRONMENT); // => undefined, not public\nconsole.log(env.PUBLIC_BASE_URL); // => \"http://example.com\"\n```\n\n```\n\n```","size_bytes":1750,"metadata":{"title":"$env/dynamic/public"},"created_at":"2025-07-18T15:47:38.880Z","updated_at":"2026-02-26T02:00:03.916Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-private.md","title":"$env/static/private","filename":"25-$env-static-private.md","content":"This module provides access to environment variables that are injected _statically_ into your bundle at build time and are limited to _private_ access.\n\n|         | Runtime                                                                    | Build time                                                               |\n| ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |\n| Private | [`$env/dynamic/private`](/docs/kit/$env-dynamic-private) | [`$env/static/private`](/docs/kit/$env-static-private) |\n| Public  | [`$env/dynamic/public`](/docs/kit/$env-dynamic-public)   | [`$env/static/public`](/docs/kit/$env-static-public)   |\n\nStatic environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination.\n\n**_Private_ access:**\n\n- This module cannot be imported into client-side code\n- This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) (if configured)\n\nFor example, given the following build time environment:\n\n```env\nENVIRONMENT=production\nPUBLIC_BASE_URL=http://site.com\n```\n\nWith the default `publicPrefix` and `privatePrefix`:\n\n```ts\nimport { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/private';\n\nconsole.log(ENVIRONMENT); // => \"production\"\nconsole.log(PUBLIC_BASE_URL); // => throws error during build\n```\n\nThe above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values.","size_bytes":1903,"metadata":{"title":"$env/static/private"},"created_at":"2025-07-18T15:47:38.881Z","updated_at":"2026-02-26T02:00:03.918Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-public.md","title":"$env/static/public","filename":"25-$env-static-public.md","content":"This module provides access to environment variables that are injected _statically_ into your bundle at build time and are _publicly_ accessible.\n\n|         | Runtime                                                                    | Build time                                                               |\n| ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |\n| Private | [`$env/dynamic/private`](/docs/kit/$env-dynamic-private) | [`$env/static/private`](/docs/kit/$env-static-private) |\n| Public  | [`$env/dynamic/public`](/docs/kit/$env-dynamic-public)   | [`$env/static/public`](/docs/kit/$env-static-public)   |\n\nStatic environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination.\n\n**_Public_ access:**\n\n- This module _can_ be imported into client-side code\n- **Only** variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included\n\nFor example, given the following build time environment:\n\n```env\nENVIRONMENT=production\nPUBLIC_BASE_URL=http://site.com\n```\n\nWith the default `publicPrefix` and `privatePrefix`:\n\n```ts\nimport { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/public';\n\nconsole.log(ENVIRONMENT); // => throws error during build\nconsole.log(PUBLIC_BASE_URL); // => \"http://site.com\"\n```\n\nThe above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values.","size_bytes":1817,"metadata":{"title":"$env/static/public"},"created_at":"2025-07-18T15:47:38.883Z","updated_at":"2026-02-26T02:00:03.915Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/26-$lib.md","title":"$lib","filename":"26-$lib.md","content":"SvelteKit automatically makes files under `src/lib` available using the `$lib` import alias.\n\n```svelte\n<!file: src/lib/Component.svelte>\nA reusable component\n```\n\n```svelte\n<!file: src/routes/+page.svelte>\n<script>\n    import Component from '$lib/Component.svelte';\n</script>\n\n<Component />\n```","size_bytes":317,"metadata":{"title":"$lib"},"created_at":"2025-07-18T15:47:38.884Z","updated_at":"2026-01-06T14:00:05.979Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/27-$service-worker.md","title":"$service-worker","filename":"27-$service-worker.md","content":"```js\n// @noErrors\nimport { base, build, files, prerendered, version } from '$service-worker';\n```\n\nThis module is only available to [service workers](/docs/kit/service-workers).\n\n## base\n\nThe `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory.\nNote that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified.\n\n<div class=\"ts-block\">\n\n```dts\nconst base: string;\n```\n\n</div>\n\n\n\n## build\n\nAn array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`.\nDuring development, this is an empty array.\n\n<div class=\"ts-block\">\n\n```dts\nconst build: string[];\n```\n\n</div>\n\n\n\n## files\n\nAn array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](/docs/kit/configuration#serviceWorker)\n\n<div class=\"ts-block\">\n\n```dts\nconst files: string[];\n```\n\n</div>\n\n\n\n## prerendered\n\nAn array of pathnames corresponding to prerendered pages and endpoints.\nDuring development, this is an empty array.\n\n<div class=\"ts-block\">\n\n```dts\nconst prerendered: string[];\n```\n\n</div>\n\n\n\n## version\n\nSee [`config.kit.version`](/docs/kit/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches.\n\n<div class=\"ts-block\">\n\n```dts\nconst version: string;\n```\n\n</div>","size_bytes":1736,"metadata":{"title":"$service-worker"},"created_at":"2025-07-18T15:47:38.886Z","updated_at":"2025-08-27T14:00:04.688Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md","title":"Configuration","filename":"50-configuration.md","content":"Your project's configuration lives in a `svelte.config.js` file at the root of your project. As well as SvelteKit, this config object is used by other tooling that integrates with Svelte such as editor extensions.\n\n```js\n/// file: svelte.config.js\n// @filename: ambient.d.ts\ndeclare module '@sveltejs/adapter-auto' {\n\tconst plugin: () => import('@sveltejs/kit').Adapter;\n\texport default plugin;\n}\n\n// @filename: index.js\n//cut\nimport adapter from '@sveltejs/adapter-auto';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tadapter: adapter()\n\t}\n};\n\nexport default config;\n```\n\n## Config\n\nAn extension of [`vite-plugin-svelte`'s options](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#svelte-options).\n\n<div class=\"ts-block\">\n\n```dts\ninterface Config extends SvelteConfig {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nkit?: KitConfig;\n```\n\n<div class=\"ts-block-property-details\">\n\nSvelteKit options.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n[key: string]: any;\n```\n\n<div class=\"ts-block-property-details\">\n\nAny additional options required by tooling that integrates with Svelte.\n\n</div>\n</div></div>\n\n\n\n## KitConfig\n\nThe `kit` property configures SvelteKit, and can have the following properties:\n\n## adapter\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `undefined`\n\n</div>\n\nYour [adapter](/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms.\n\n<div class=\"ts-block-property-children\">\n\n\n\n</div>\n\n## alias\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `{}`\n\n</div>\n\nAn object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript.\n\n```js\n// @errors: 7031\n/// file: svelte.config.js\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\talias: {\n\t\t\t// this will match a file\n\t\t\t'my-file': 'path/to/my-file.js',\n\n\t\t\t// this will match a directory and its contents\n\t\t\t// (`my-directory/x` resolves to `path/to/my-directory/x`)\n\t\t\t'my-directory': 'path/to/my-directory',\n\n\t\t\t// an alias ending /* will only match\n\t\t\t// the contents of a directory, not the directory itself\n\t\t\t'my-directory/*': 'path/to/my-directory/*'\n\t\t}\n\t}\n};\n```\n\n\n<div class=\"ts-block-property-children\">\n\n\n\n</div>\n\n## appDir\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"_app\"`\n\n</div>\n\nThe directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.\n\nIf `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`.\n\n<div class=\"ts-block-property-children\">\n\n\n\n</div>\n\n## csp\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\n[Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this...\n\n```js\n// @errors: 7031\n/// file: svelte.config.js\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tcsp: {\n\t\t\tdirectives: {\n\t\t\t\t'script-src': ['self']\n\t\t\t},\n\t\t\t// must be specified with either the `report-uri` or `report-to` directives, or both\n\t\t\treportOnly: {\n\t\t\t\t'script-src': ['self'],\n\t\t\t\t'report-uri': ['/']\n\t\t\t}\n\t\t}\n\t}\n};\n\nexport default config;\n```\n\n...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates.\n\nTo add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example `<script nonce=\"%sveltekit.nonce%\">`).\n\nWhen pages are prerendered, the CSP header is added via a `<meta http-equiv>` tag (note that in this case, `frame-ancestors`, `report-uri` and `sandbox` directives will be ignored).\n\n\n\nIf this level of configuration is insufficient and you have more dynamic requirements, you can use the [`handle` hook](/docs/kit/hooks#Server-hooks-handle) to roll your own CSP.\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nmode?: 'hash' | 'nonce' | 'auto';\n```\n\n<div class=\"ts-block-property-details\">\n\nWhether to use hashes or nonces to restrict `<script>` and `<style>` elements. `'auto'` will use hashes for prerendered pages, and nonces for dynamically rendered pages.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\ndirectives?: CspDirectives;\n```\n\n<div class=\"ts-block-property-details\">\n\nDirectives that will be added to `Content-Security-Policy` headers.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nreportOnly?: CspDirectives;\n```\n\n<div class=\"ts-block-property-details\">\n\nDirectives that will be added to `Content-Security-Policy-Report-Only` headers.\n\n</div>\n</div>\n\n</div>\n\n## csrf\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\nProtection against [cross-site request forgery (CSRF)](https://owasp.org/www-community/attacks/csrf) attacks.\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\ncheckOrigin?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `true`\n- <span class=\"tag deprecated\">deprecated</span> Use `trustedOrigins: ['*']` instead\n\n</div>\n\nWhether to check the incoming `origin` header for `POST`, `PUT`, `PATCH`, or `DELETE` form submissions and verify that it matches the server's origin.\n\nTo allow people to make `POST`, `PUT`, `PATCH`, or `DELETE` requests with a `Content-Type` of `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain` to your app from other origins, you will need to disable this option. Be careful!\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\ntrustedOrigins?: string[];\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `[]`\n\n</div>\n\nAn array of origins that are allowed to make cross-origin form submissions to your app.\n\nEach origin should be a complete origin including protocol (e.g., `https://payment-gateway.com`).\nThis is useful for allowing trusted third-party services like payment gateways or authentication providers to submit forms to your app.\n\nIf the array contains `'*'`, all origins will be trusted. This is generally not recommended!\n\n\nCSRF checks only apply in production, not in local development.\n\n</div>\n</div>\n\n</div>\n\n## embedded\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nWhether or not the app is embedded inside a larger app. If `true`, SvelteKit will add its event listeners related to navigation etc on the parent of `%sveltekit.body%` instead of `window`, and will pass `params` from the server rather than inferring them from `location.pathname`.\nNote that it is generally not supported to embed multiple SvelteKit apps on the same page and use client-side SvelteKit features within them (things such as pushing to the history state assume a single instance).\n\n<div class=\"ts-block-property-children\">\n\n\n\n</div>\n\n## env\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\nEnvironment variable configuration\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\ndir?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\".\"`\n\n</div>\n\nThe directory to search for `.env` files.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\npublicPrefix?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"PUBLIC_\"`\n\n</div>\n\nA prefix that signals that an environment variable is safe to expose to client-side code. See [`$env/static/public`](/docs/kit/$env-static-public) and [`$env/dynamic/public`](/docs/kit/$env-dynamic-public). Note that Vite's [`envPrefix`](https://vitejs.dev/config/shared-options.html#envprefix) must be set separately if you are using Vite's environment variable handling - though use of that feature should generally be unnecessary.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nprivatePrefix?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"\"`\n- <span class=\"tag since\">available since</span> v1.21.0\n\n</div>\n\nA prefix that signals that an environment variable is unsafe to expose to client-side code. Environment variables matching neither the public nor the private prefix will be discarded completely. See [`$env/static/private`](/docs/kit/$env-static-private) and [`$env/dynamic/private`](/docs/kit/$env-dynamic-private).\n\n</div>\n</div>\n\n</div>\n\n## experimental\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\nExperimental features. Here be dragons. These are not subject to semantic versioning, so breaking changes or removal can happen in any release.\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\ntracing?: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `{ server: false, serverFile: false }`\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nOptions for enabling server-side [OpenTelemetry](https://opentelemetry.io/) tracing for SvelteKit operations including the [`handle` hook](/docs/kit/hooks#Server-hooks-handle), [`load` functions](/docs/kit/load), [form actions](/docs/kit/form-actions), and [remote functions](/docs/kit/remote-functions).\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nserver?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nEnables server-side [OpenTelemetry](https://opentelemetry.io/) span emission for SvelteKit operations including the [`handle` hook](/docs/kit/hooks#Server-hooks-handle), [`load` functions](/docs/kit/load), [form actions](/docs/kit/form-actions), and [remote functions](/docs/kit/remote-functions).\n\n</div>\n</div></div>\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\ninstrumentation?: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nserver?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n- <span class=\"tag since\">available since</span> v2.31.0\n\n</div>\n\nEnables `instrumentation.server.js` for tracing and observability instrumentation.\n\n</div>\n</div></div>\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nremoteFunctions?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nWhether to enable the experimental remote functions feature. This feature is not yet stable and may be changed or removed at any time.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nforkPreloads?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nWhether to enable the experimental forked preloading feature using Svelte's fork API.\n\n</div>\n</div>\n\n</div>\n\n## files\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n\n</div>\n\nWhere to find various files within your project.\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nsrc?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src\"`\n- <span class=\"tag since\">available since</span> v2.28\n\n</div>\n\nthe location of your source code\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nassets?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"static\"`\n\n</div>\n\na place to put static files that should have stable URLs and undergo no processing, such as `favicon.ico` or `manifest.json`\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nhooks?: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nclient?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/hooks.client\"`\n\n</div>\n\nThe location of your client [hooks](/docs/kit/hooks).\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nserver?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/hooks.server\"`\n\n</div>\n\nThe location of your server [hooks](/docs/kit/hooks).\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nuniversal?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/hooks\"`\n- <span class=\"tag since\">available since</span> v2.3.0\n\n</div>\n\nThe location of your universal [hooks](/docs/kit/hooks).\n\n</div>\n</div></div>\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nlib?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/lib\"`\n\n</div>\n\nyour app's internal library, accessible throughout the codebase as `$lib`\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nparams?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/params\"`\n\n</div>\n\na directory containing [parameter matchers](/docs/kit/advanced-routing#Matching)\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nroutes?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/routes\"`\n\n</div>\n\nthe files that define the structure of your app (see [Routing](/docs/kit/routing))\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nserviceWorker?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/service-worker\"`\n\n</div>\n\nthe location of your service worker's entry point (see [Service workers](/docs/kit/service-workers))\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nappTemplate?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/app.html\"`\n\n</div>\n\nthe location of the template for HTML responses\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nerrorTemplate?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> \n- <span class=\"tag\">default</span> `\"src/error.html\"`\n\n</div>\n\nthe location of the template for fallback error responses\n\n</div>\n</div>\n\n</div>\n\n## inlineStyleThreshold\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `0`\n\n</div>\n\nInline CSS inside a `<style>` block at the head of the HTML. This option is a number that specifies the maximum length of a CSS file in UTF-16 code units, as specified by the [String.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) property, to be inlined. All CSS files needed for the page that are smaller than this value are merged and inlined in a `<style>` block.\n\n\n<div class=\"ts-block-property-children\">\n\n\n\n</div>\n\n## moduleExtensions\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `[\".js\", \".ts\"]`\n\n</div>\n\nAn array of file extensions that SvelteKit will treat as modules. Files with extensions that match neither `config.extensions` nor `config.kit.moduleExtensions` will be ignored by the router.\n\n<div class=\"ts-block-property-children\">\n\n\n\n</div>\n\n## outDir\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\".svelte-kit\"`\n\n</div>\n\nThe directory that SvelteKit writes files to during `dev` and `build`. You should exclude this directory from version control.\n\n<div class=\"ts-block-property-children\">\n\n\n\n</div>\n\n## output\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\nOptions related to the build output format\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\npreloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"modulepreload\"`\n- <span class=\"tag since\">available since</span> v1.8.4\n\n</div>\n\nSvelteKit will preload the JavaScript modules needed for the initial page to avoid import 'waterfalls', resulting in faster application startup. There\nare three strategies with different trade-offs:\n- `modulepreload` - uses `<link rel=\"modulepreload\">`. This delivers the best results in Chromium-based browsers, in Firefox 115+, and Safari 17+. It is ignored in older browsers.\n- `preload-js` - uses `<link rel=\"preload\">`. Prevents waterfalls in Chromium and Safari, but Chromium will parse each module twice (once as a script, once as a module). Causes modules to be requested twice in Firefox. This is a good setting if you want to maximise performance for users on iOS devices at the cost of a very slight degradation for Chromium users.\n- `preload-mjs` - uses `<link rel=\"preload\">` but with the `.mjs` extension which prevents double-parsing in Chromium. Some static webservers will fail to serve .mjs files with a `Content-Type: application/javascript` header, which will cause your application to break. If that doesn't apply to you, this is the option that will deliver the best performance for the largest number of users, until `modulepreload` is more widely supported.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nbundleStrategy?: 'split' | 'single' | 'inline';\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `'split'`\n- <span class=\"tag since\">available since</span> v2.13.0\n\n</div>\n\nThe bundle strategy option affects how your app's JavaScript and CSS files are loaded.\n- If `'split'`, splits the app up into multiple .js/.css files so that they are loaded lazily as the user navigates around the app. This is the default, and is recommended for most scenarios.\n- If `'single'`, creates just one .js bundle and one .css file containing code for the entire app.\n- If `'inline'`, inlines all JavaScript and CSS of the entire app into the HTML. The result is usable without a server (i.e. you can just open the file in your browser).\n\nWhen using `'split'`, you can also adjust the bundling behaviour by setting [`output.experimentalMinChunkSize`](https://rollupjs.org/configuration-options/#output-experimentalminchunksize) and [`output.manualChunks`](https://rollupjs.org/configuration-options/#output-manualchunks) inside your Vite config's [`build.rollupOptions`](https://vite.dev/config/build-options.html#build-rollupoptions).\n\nIf you want to inline your assets, you'll need to set Vite's [`build.assetsInlineLimit`](https://vite.dev/config/build-options.html#build-assetsinlinelimit) option to an appropriate size then import your assets through Vite.\n\n```js\n// @errors: 7031\n/// file: vite.config.js\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n\tplugins: [sveltekit()],\n\tbuild: {\n\t\t// inline all imported assets\n\t\tassetsInlineLimit: Infinity\n\t}\n});\n```\n\n```svelte\n/// file: src/routes/+layout.svelte\n<script>\n\t// import the asset through Vite\n\timport favicon from './favicon.png';\n</script>\n\n<svelte:head>\n\t<!-- this asset will be inlined as a base64 URL -->\n\t<link rel=\"icon\" href={favicon} />\n</svelte:head>\n```\n\n</div>\n</div>\n\n</div>\n\n## paths\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\n\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nassets?: '' | `http://${string}` | `https://${string}`;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"\"`\n\n</div>\n\nAn absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nbase?: '' | `/${string}`;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"\"`\n\n</div>\n\nA root-relative path that must start, but not end with `/` (e.g. `/base-path`), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your `base` (this is how the browser works). You can use [`base` from `$app/paths`](/docs/kit/$app-paths#base) for that: `<a href=\"{base}/your-page\">Link</a>`. If you find yourself writing this often, it may make sense to extract this into a reusable component.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nrelative?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `true`\n- <span class=\"tag since\">available since</span> v1.9.0\n\n</div>\n\nWhether to use relative asset paths.\n\nIf `true`, `base` and `assets` imported from `$app/paths` will be replaced with relative asset paths during server-side rendering, resulting in more portable HTML.\nIf `false`, `%sveltekit.assets%` and references to build artifacts will always be root-relative paths, unless `paths.assets` is an external URL\n\n[Single-page app](/docs/kit/single-page-apps) fallback pages will always use absolute paths, regardless of this setting.\n\nIf your app uses a `<base>` element, you should set this to `false`, otherwise asset URLs will incorrectly be resolved against the `<base>` URL rather than the current page.\n\nIn 1.0, `undefined` was a valid value, which was set by default. In that case, if `paths.assets` was not external, SvelteKit would replace `%sveltekit.assets%` with a relative path and use relative paths to reference build artifacts, but `base` and `assets` imported from `$app/paths` would be as specified in your config.\n\n</div>\n</div>\n\n</div>\n\n## prerender\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\nSee [Prerendering](/docs/kit/page-options#prerender).\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nconcurrency?: number;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `1`\n\n</div>\n\nHow many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\ncrawl?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `true`\n\n</div>\n\nWhether SvelteKit should find pages to prerender by following links from `entries`.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nentries?: Array<'*' | `/${string}`>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `[\"*\"]`\n\n</div>\n\nAn array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all routes containing no required `[parameters]`  with optional parameters included as being empty (since SvelteKit doesn't know what value any parameters should have).\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nhandleHttpError?: PrerenderHttpErrorHandlerValue;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"fail\"`\n- <span class=\"tag since\">available since</span> v1.15.7\n\n</div>\n\nHow to respond to HTTP errors encountered while prerendering the app.\n\n- `'fail'` — fail the build\n- `'ignore'` - silently ignore the failure and continue\n- `'warn'` — continue, but print a warning\n- `(details) => void` — a custom error handler that takes a `details` object with `status`, `path`, `referrer`, `referenceType` and `message` properties. If you `throw` from this function, the build will fail\n\n```js\n// @errors: 7031\n/// file: svelte.config.js\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n\tkit: {\n\t\tprerender: {\n\t\t\thandleHttpError: ({ path, referrer, message }) => {\n\t\t\t\t// ignore deliberate link to shiny 404 page\n\t\t\t\tif (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// otherwise fail the build\n\t\t\t\tthrow new Error(message);\n\t\t\t}\n\t\t}\n\t}\n};\n```\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nhandleMissingId?: PrerenderMissingIdHandlerValue;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"fail\"`\n- <span class=\"tag since\">available since</span> v1.15.7\n\n</div>\n\nHow to respond when hash links from one prerendered page to another don't correspond to an `id` on the destination page.\n\n- `'fail'` — fail the build\n- `'ignore'` - silently ignore the failure and continue\n- `'warn'` — continue, but print a warning\n- `(details) => void` — a custom error handler that takes a `details` object with `path`, `id`, `referrers` and `message` properties. If you `throw` from this function, the build will fail\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nhandleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"fail\"`\n- <span class=\"tag since\">available since</span> v1.16.0\n\n</div>\n\nHow to respond when an entry generated by the `entries` export doesn't match the route it was generated from.\n\n- `'fail'` — fail the build\n- `'ignore'` - silently ignore the failure and continue\n- `'warn'` — continue, but print a warning\n- `(details) => void` — a custom error handler that takes a `details` object with `generatedFromId`, `entry`, `matchedId` and `message` properties. If you `throw` from this function, the build will fail\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nhandleUnseenRoutes?: PrerenderUnseenRoutesHandlerValue;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"fail\"`\n- <span class=\"tag since\">available since</span> v2.16.0\n\n</div>\n\nHow to respond when a route is marked as prerenderable but has not been prerendered.\n\n- `'fail'` — fail the build\n- `'ignore'` - silently ignore the failure and continue\n- `'warn'` — continue, but print a warning\n- `(details) => void` — a custom error handler that takes a `details` object with a `routes` property which contains all routes that haven't been prerendered. If you `throw` from this function, the build will fail\n\nThe default behavior is to fail the build. This may be undesirable when you know that some of your routes may never be reached under certain\ncircumstances such as a CMS not returning data for a specific area, resulting in certain routes never being reached.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\norigin?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"http://sveltekit-prerender\"`\n\n</div>\n\nThe value of `url.origin` during prerendering; useful if it is included in rendered content.\n\n</div>\n</div>\n\n</div>\n\n## router\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\n\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\ntype?: 'pathname' | 'hash';\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"pathname\"`\n- <span class=\"tag since\">available since</span> v2.14.0\n\n</div>\n\nWhat type of client-side router to use.\n- `'pathname'` is the default and means the current URL pathname determines the route\n- `'hash'` means the route is determined by `location.hash`. In this case, SSR and prerendering are disabled. This is only recommended if `pathname` is not an option, for example because you don't control the webserver where your app is deployed.\n\tIt comes with some caveats: you can't use server-side rendering (or indeed any server logic), and you have to make sure that the links in your app all start with #/, or they won't work. Beyond that, everything works exactly like a normal SvelteKit app.\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nresolution?: 'client' | 'server';\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `\"client\"`\n- <span class=\"tag since\">available since</span> v2.17.0\n\n</div>\n\nHow to determine which route to load when navigating to a new page.\n\nBy default, SvelteKit will serve a route manifest to the browser.\nWhen navigating, this manifest is used (along with the `reroute` hook, if it exists) to determine which components to load and which `load` functions to run.\nBecause everything happens on the client, this decision can be made immediately. The drawback is that the manifest needs to be\nloaded and parsed before the first navigation can happen, which may have an impact if your app contains many routes.\n\nAlternatively, SvelteKit can determine the route on the server. This means that for every navigation to a path that has not yet been visited, the server will be asked to determine the route.\nThis has several advantages:\n- The client does not need to load the routing manifest upfront, which can lead to faster initial page loads\n- The list of routes is hidden from public view\n- The server has an opportunity to intercept each navigation (for example through a middleware), enabling (for example) A/B testing opaque to SvelteKit\n\nThe drawback is that for unvisited paths, resolution will take slightly longer (though this is mitigated by [preloading](/docs/kit/link-options#data-sveltekit-preload-data)).\n\n\n</div>\n</div>\n\n</div>\n\n## serviceWorker\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\n\n\n<div class=\"ts-block-property-children\">\n\n\n\n</div>\n\n## typescript\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\n\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nconfig?: (config: Record<string, any>) => Record<string, any> | void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `(config) => config`\n- <span class=\"tag since\">available since</span> v1.3.0\n\n</div>\n\nA function that allows you to edit the generated `tsconfig.json`. You can mutate the config (recommended) or return a new one.\nThis is useful for extending a shared `tsconfig.json` in a monorepo root, for example.\n\nNote that any paths configured here should be relative to the generated config file, which is written to `.svelte-kit/tsconfig.json`.\n\n</div>\n</div>\n\n</div>\n\n## version\n\n<div class=\"ts-block-property-bullets\">\n\n\n\n</div>\n\nClient-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists.\nSvelteKit helps you solve this problem through version management.\nIf SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the `name` specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation.\nNot all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use techniques such as setting the `pollInterval` and then using `beforeNavigate`:\n```html\n/// file: +layout.svelte\n<script>\n\timport { beforeNavigate } from '$app/navigation';\n\timport { updated } from '$app/state';\n\n\tbeforeNavigate(({ willUnload, to }) => {\n\t\tif (updated.current && !willUnload && to?.url) {\n\t\t\tlocation.href = to.url.href;\n\t\t}\n\t});\n</script>\n```\n\nIf you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of [`updated.current`](/docs/kit/$app-state#updated) `true` when it detects one.\n\n<div class=\"ts-block-property-children\">\n\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\nname?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build.\n\nFor example, to use the current commit hash, you could do use `git rev-parse HEAD`:\n\n```js\n// @errors: 7031\n/// file: svelte.config.js\nimport * as child_process from 'node:child_process';\n\nexport default {\n\tkit: {\n\t\tversion: {\n\t\t\tname: child_process.execSync('git rev-parse HEAD').toString().trim()\n\t\t}\n\t}\n};\n```\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```ts\n// @noErrors\npollInterval?: number;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `0`\n\n</div>\n\nThe interval in milliseconds to poll for version changes. If this is `0`, no polling occurs.\n\n</div>\n</div>\n\n</div>","size_bytes":35273,"metadata":{"title":"Configuration"},"created_at":"2025-07-18T15:47:38.888Z","updated_at":"2026-01-10T14:00:07.322Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/52-cli.md","title":"Command Line Interface","filename":"52-cli.md","content":"SvelteKit projects use [Vite](https://vitejs.dev), meaning you'll mostly use its CLI (albeit via `npm run dev/build/preview` scripts):\n\n- `vite dev` — start a development server\n- `vite build` — build a production version of your app\n- `vite preview` — run the production version locally\n\nHowever SvelteKit includes its own CLI for initialising your project:\n\n## svelte-kit sync\n\n`svelte-kit sync` creates the `tsconfig.json` and all generated types (which you can import as `./$types` inside routing files) for your project. When you create a new project, it is listed as the `prepare` script and will be run automatically as part of the npm lifecycle, so you should not ordinarily have to run this command.","size_bytes":754,"metadata":{"title":"Command Line Interface"},"created_at":"2025-07-18T15:47:38.890Z","updated_at":"2025-07-18T15:47:40.170Z"},{"path":"apps/svelte.dev/content/docs/kit/98-reference/54-types.md","title":"Types","filename":"54-types.md","content":"## Generated types\n\nThe `RequestHandler` and `Load` types both accept a `Params` argument allowing you to type the `params` object. For example this endpoint expects `foo`, `bar` and `baz` params:\n\n```js\n/// file: src/routes/[foo]/[bar]/[baz]/+server.js\n// @errors: 2355 2322 1360\n/** @type {import('@sveltejs/kit').RequestHandler<{\n    foo: string;\n    bar: string;\n    baz: string\n  }>} */\nexport async function GET({ params }) {\n\t// ...\n}\n```\n\nNeedless to say, this is cumbersome to write out, and less portable (if you were to rename the `[foo]` directory to `[qux]`, the type would no longer reflect reality).\n\nTo solve this problem, SvelteKit generates `.d.ts` files for each of your endpoints and pages:\n\n```ts\n/// file: .svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d.ts\n/// link: true\nimport type * as Kit from '@sveltejs/kit';\n\ntype RouteParams = {\n\tfoo: string;\n\tbar: string;\n\tbaz: string;\n};\n\nexport type RequestHandler = Kit.RequestHandler<RouteParams>;\nexport type PageLoad = Kit.Load<RouteParams>;\n```\n\nThese files can be imported into your endpoints and pages as siblings, thanks to the [`rootDirs`](https://www.typescriptlang.org/tsconfig#rootDirs) option in your TypeScript configuration:\n\n```js\n/// file: src/routes/[foo]/[bar]/[baz]/+server.js\n// @filename: $types.d.ts\nimport type * as Kit from '@sveltejs/kit';\n\ntype RouteParams = {\n\tfoo: string;\n\tbar: string;\n\tbaz: string;\n}\n\nexport type RequestHandler = Kit.RequestHandler<RouteParams>;\n\n// @filename: index.js\n// @errors: 2355 2322\n//cut\n/** @type {import('./$types').RequestHandler} */\nexport async function GET({ params }) {\n\t// ...\n}\n```\n\n```js\n/// file: src/routes/[foo]/[bar]/[baz]/+page.js\n// @filename: $types.d.ts\nimport type * as Kit from '@sveltejs/kit';\n\ntype RouteParams = {\n\tfoo: string;\n\tbar: string;\n\tbaz: string;\n}\n\nexport type PageLoad = Kit.Load<RouteParams>;\n\n// @filename: index.js\n// @errors: 2355\n//cut\n/** @type {import('./$types').PageLoad} */\nexport async function load({ params, fetch }) {\n\t// ...\n}\n```\n\nThe return types of the load functions are then available through the `$types` module as `PageData` and `LayoutData` respectively, while the union of the return values of all `Actions` is available as `ActionData`.\n\nStarting with version 2.16.0, two additional helper types are provided: `PageProps` defines `data: PageData`, as well as `form: ActionData`, when there are actions defined, while `LayoutProps` defines `data: LayoutData`, as well as `children: Snippet`.\n\n```svelte\n<!file: src/routes/+page.svelte>\n<script>\n\t/** @type {import('./$types').PageProps} */\n\tlet { data, form } = $props();\n</script>\n```\n\n> [!LEGACY]\n> Before 2.16.0:\n> ```svelte\n> <!--- file: src/routes/+page.svelte --->\n> <script>\n> \t/** @type {{ data: import('./$types').PageData, form: import('./$types').ActionData }} */\n> \tlet { data, form } = $props();\n> </script>\n> ```\n>\n> Using Svelte 4:\n> ```svelte\n> <!--- file: src/routes/+page.svelte --->\n> <script>\n>   /** @type {import('./$types').PageData} */\n>   export let data;\n>   /** @type {import('./$types').ActionData} */\n>   export let form;\n> </script>\n> ```\n\n>\n> `{ \"extends\": \"./.svelte-kit/tsconfig.json\" }`\n\n### Default tsconfig.json\n\nThe generated `.svelte-kit/tsconfig.json` file contains a mixture of options. Some are generated programmatically based on your project configuration, and should generally not be overridden without good reason:\n\n```json\n/// file: .svelte-kit/tsconfig.json\n{\n\t\"compilerOptions\": {\n\t\t\"paths\": {\n\t\t\t\"$lib\": [\"../src/lib\"],\n\t\t\t\"$lib/*\": [\"../src/lib/*\"]\n\t\t},\n\t\t\"rootDirs\": [\"..\", \"./types\"]\n\t},\n\t\"include\": [\n\t\t\"ambient.d.ts\",\n\t\t\"non-ambient.d.ts\",\n\t\t\"./types/**/$types.d.ts\",\n\t\t\"../vite.config.js\",\n\t\t\"../vite.config.ts\",\n\t\t\"../src/**/*.js\",\n\t\t\"../src/**/*.ts\",\n\t\t\"../src/**/*.svelte\",\n\t\t\"../tests/**/*.js\",\n\t\t\"../tests/**/*.ts\",\n\t\t\"../tests/**/*.svelte\"\n\t],\n\t\"exclude\": [\n\t\t\"../node_modules/**\",\n\t\t\"../src/service-worker.js\",\n\t\t\"../src/service-worker/**/*.js\",\n\t\t\"../src/service-worker.ts\",\n\t\t\"../src/service-worker/**/*.ts\",\n\t\t\"../src/service-worker.d.ts\",\n\t\t\"../src/service-worker/**/*.d.ts\"\n\t]\n}\n```\n\nOthers are required for SvelteKit to work properly, and should also be left untouched unless you know what you're doing:\n\n```json\n/// file: .svelte-kit/tsconfig.json\n{\n\t\"compilerOptions\": {\n\t\t// this ensures that types are explicitly\n\t\t// imported with `import type`, which is\n\t\t// necessary as Svelte/Vite cannot\n\t\t// otherwise compile components correctly\n\t\t\"verbatimModuleSyntax\": true,\n\n\t\t// Vite compiles one TypeScript module\n\t\t// at a time, rather than compiling\n\t\t// the entire module graph\n\t\t\"isolatedModules\": true,\n\n\t\t// Tell TS it's used only for type-checking\n\t\t\"noEmit\": true,\n\n\t\t// This ensures both `vite build`\n\t\t// and `svelte-package` work correctly\n\t\t\"lib\": [\"esnext\", \"DOM\", \"DOM.Iterable\"],\n\t\t\"moduleResolution\": \"bundler\",\n\t\t\"module\": \"esnext\",\n\t\t\"target\": \"esnext\"\n\t}\n}\n```\n\nUse the [`typescript.config` setting](configuration#typescript) in `svelte.config.js` to extend or modify the generated `tsconfig.json`.\n\n## $lib\n\nThis is a simple alias to `src/lib`. It allows you to access common components and utility modules without `../../../../` nonsense.\n\n### $lib/server\n\nA subdirectory of `$lib`. SvelteKit will prevent you from importing any modules in `$lib/server` into client-side code. See [server-only modules](server-only-modules).\n\n## app.d.ts\n\nThe `app.d.ts` file is home to the ambient types of your apps, i.e. types that are available without explicitly importing them.\n\nAlways part of this file is the `App` namespace. This namespace contains several types that influence the shape of certain SvelteKit features you interact with.\n\n## Error\n\nDefines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Error {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nmessage: string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## Locals\n\nThe interface that defines `event.locals`, which can be accessed in server [hooks](/docs/kit/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Locals {}\n```\n\n</div>\n\n## PageData\n\nDefines the common shape of the [page.data state](/docs/kit/$app-state#page) and [$page.data store](/docs/kit/$app-stores#page) - that is, the data that is shared between all pages.\nThe `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly.\nUse optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`).\n\n<div class=\"ts-block\">\n\n```dts\ninterface PageData {}\n```\n\n</div>\n\n## PageState\n\nThe shape of the `page.state` object, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.\n\n<div class=\"ts-block\">\n\n```dts\ninterface PageState {}\n```\n\n</div>\n\n## Platform\n\nIf your adapter provides [platform-specific context](/docs/kit/adapters#Platform-specific-context) via `event.platform`, you can specify it here.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Platform {}\n```\n\n</div>","size_bytes":7341,"metadata":{"title":"Types"},"created_at":"2025-07-18T15:47:38.893Z","updated_at":"2026-02-21T14:00:04.071Z"},{"path":"apps/svelte.dev/content/docs/svelte/01-introduction/01-overview.md","title":"Overview","filename":"01-overview.md","content":"Svelte is a framework for building user interfaces on the web. It uses a compiler to turn declarative components written in HTML, CSS and JavaScript...\n\n```svelte\n<!file: App.svelte>\n<script>\n\tfunction greet() {\n\t\talert('Welcome to Svelte!');\n\t}\n</script>\n\n<button onclick={greet}>click me</button>\n\n<style>\n\tbutton {\n\t\tfont-size: 2em;\n\t}\n</style>\n```\n\n...into lean, tightly optimized JavaScript.\n\nYou can use it to build anything on the web, from standalone components to ambitious full stack apps (using Svelte's companion application framework, [SvelteKit](../kit)) and everything in between.\n\nThese pages serve as reference documentation. If you're new to Svelte, we recommend starting with the [interactive tutorial](/tutorial) and coming back here when you have questions.\n\nYou can also try Svelte online in the [playground](/playground) or, if you need a more fully-featured environment, on [StackBlitz](https://sveltekit.new).","size_bytes":960,"metadata":{"title":"Overview"},"created_at":"2025-07-18T15:47:38.897Z","updated_at":"2025-07-18T15:47:40.180Z"},{"path":"apps/svelte.dev/content/docs/svelte/01-introduction/02-getting-started.md","title":"Getting started","filename":"02-getting-started.md","content":"We recommend using [SvelteKit](../kit), which lets you [build almost anything](../kit/project-types). It's the official application framework from the Svelte team and powered by [Vite](https://vite.dev/). Create a new project with:\n\n```sh\nnpx sv create myapp\ncd myapp\nnpm install\nnpm run dev\n```\n\nDon't worry if you don't know Svelte yet! You can ignore all the nice features SvelteKit brings on top for now and dive into it later.\n\n## Alternatives to SvelteKit\n\nYou can also use Svelte directly with Vite via [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte) by running `npm create vite@latest` and selecting the `svelte` option (or, if working with an existing project, adding the plugin to your `vite.config.js` file). With this, `npm run build` will generate HTML, JS, and CSS files inside the `dist` directory. In most cases, you will probably need to [choose a routing library](/packages#routing) as well.\n\n>[!NOTE] Vite is often used in standalone mode to build [single page apps (SPAs)](../kit/glossary#SPA), which you can also [build with SvelteKit](../kit/single-page-apps).\n\nThere are also [plugins for other bundlers](/packages#bundler-plugins), but we recommend Vite.\n\n## Editor tooling\n\nThe Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode), and there are integrations with various other [editors](https://sveltesociety.dev/collection/editor-support-c85c080efc292a34) and tools as well.\n\nYou can also check your code from the command line using [`npx sv check`](https://svelte.dev/docs/cli/sv-check).\n\n\n## Getting help\n\nDon't be shy about asking for help in the [Discord chatroom](/chat)! You can also find answers on [Stack Overflow](https://stackoverflow.com/questions/tagged/svelte).","size_bytes":1820,"metadata":{"title":"Getting started"},"created_at":"2025-07-18T15:47:38.899Z","updated_at":"2026-02-14T01:33:24.866Z"},{"path":"apps/svelte.dev/content/docs/svelte/01-introduction/03-svelte-files.md","title":".svelte files","filename":"03-svelte-files.md","content":"Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML.\n\nAll three sections — script, styles and markup — are optional.\n\n```svelte\n/// file: MyComponent.svelte\n<script module>\n\t// module-level logic goes here\n\t// (you will rarely use this)\n</script>\n\n<script>\n\t// instance-level logic goes here\n</script>\n\n<!-- markup (zero or more items) goes here -->\n\n<style>\n\t/* styles go here */\n</style>\n```\n\n## `<script>`\n\nA `<script>` block contains JavaScript (or TypeScript, when adding the `lang=\"ts\"` attribute) that runs when a component instance is created. Variables declared (or imported) at the top level can be referenced in the component's markup.\n\nIn addition to normal JavaScript, you can use _runes_ to declare [component props]($props) and add reactivity to your component. Runes are covered in the next section.\n\n<!-- TODO describe behaviour of `export` -->\n\n## `<script module>`\n\nA `<script>` tag with a `module` attribute runs once when the module first evaluates, rather than for each component instance. Variables declared in this block can be referenced elsewhere in the component, but not vice versa.\n\n```svelte\n<script module>\n\tlet total = 0;\n</script>\n\n<script>\n\ttotal += 1;\n\tconsole.log(`instantiated ${total} times`);\n</script>\n```\n\nYou can `export` bindings from this block, and they will become exports of the compiled module. You cannot `export default`, since the default export is the component itself.\n\n\n> [!LEGACY]\n> In Svelte 4, this script tag was created using `<script context=\"module\">`\n\n## `<style>`\n\nCSS inside a `<style>` block will be scoped to that component.\n\n```svelte\n<style>\n\tp {\n\t\t/* this will only affect <p> elements in this component */\n\t\tcolor: burlywood;\n\t}\n</style>\n```\n\nFor more information, head to the section on [styling](scoped-styles).","size_bytes":1889,"metadata":{"title":".svelte files"},"created_at":"2025-07-18T15:47:38.900Z","updated_at":"2025-07-18T15:47:40.185Z"},{"path":"apps/svelte.dev/content/docs/svelte/01-introduction/04-svelte-js-files.md","title":".svelte.js and .svelte.ts files","filename":"04-svelte-js-files.md","content":"Besides `.svelte` files, Svelte also operates on `.svelte.js` and `.svelte.ts` files.\n\nThese behave like any other `.js` or `.ts` module, except that you can use runes. This is useful for creating reusable reactive logic, or sharing reactive state across your app (though note that you [cannot export reassigned state]($state#Passing-state-across-modules)).\n\n> [!LEGACY]\n> This is a concept that didn't exist prior to Svelte 5","size_bytes":475,"metadata":{"title":".svelte.js and .svelte.ts files"},"created_at":"2025-07-18T15:47:38.902Z","updated_at":"2025-07-18T15:47:40.186Z"},{"path":"apps/svelte.dev/content/docs/svelte/02-runes/01-what-are-runes.md","title":"What are runes?","filename":"01-what-are-runes.md","content":">\n> A letter or mark used as a mystical or magic symbol.\n\nRunes are symbols that you use in `.svelte` and `.svelte.js`/`.svelte.ts` files to control the Svelte compiler. If you think of Svelte as a language, runes are part of the syntax — they are _keywords_.\n\nRunes have a `$` prefix and look like functions:\n\n```js\nlet message = $state('hello');\n```\n\nThey differ from normal JavaScript functions in important ways, however:\n\n- You don't need to import them — they are part of the language\n- They're not values — you can't assign them to a variable or pass them as arguments to a function\n- Just like JavaScript keywords, they are only valid in certain positions (the compiler will help you if you put them in the wrong place)\n\n> [!LEGACY]\n> Runes didn't exist prior to Svelte 5.","size_bytes":819,"metadata":{"title":"What are runes?"},"created_at":"2025-07-18T15:47:38.905Z","updated_at":"2025-07-18T15:47:40.190Z"},{"path":"apps/svelte.dev/content/docs/svelte/02-runes/02-$state.md","title":"$state","filename":"02-$state.md","content":"The `$state` rune allows you to create _reactive state_, which means that your UI _reacts_ when it changes.\n\n```svelte\n<script>\n\tlet count = $state(0);\n</script>\n\n<button onclick={() => count++}>\n\tclicks: {count}\n</button>\n```\n\nUnlike other frameworks you may have encountered, there is no API for interacting with state — `count` is just a number, rather than an object or a function, and you can update it like you would update any other variable.\n\n### Deep state\n\nIf `$state` is used with an array or a simple object, the result is a deeply reactive _state proxy_. [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allow Svelte to run code when you read or write properties, including via methods like `array.push(...)`, triggering granular updates.\n\nState is proxified recursively until Svelte finds something other than an array or simple object (like a class or an object created with `Object.create`). In a case like this...\n\n```js\nlet todos = $state([\n\t{\n\t\tdone: false,\n\t\ttext: 'add more todos'\n\t}\n]);\n```\n\n...modifying an individual todo's property will trigger updates to anything in your UI that depends on that specific property:\n\n```js\nlet todos = [{ done: false, text: 'add more todos' }];\n//cut\ntodos[0].done = !todos[0].done;\n```\n\nIf you push a new object to the array, it will also be proxified:\n\n```js\nlet todos = [{ done: false, text: 'add more todos' }];\n//cut\ntodos.push({\n\tdone: false,\n\ttext: 'eat lunch'\n});\n```\n\n\nNote that if you destructure a reactive value, the references are not reactive — as in normal JavaScript, they are evaluated at the point of destructuring:\n\n```js\nlet todos = [{ done: false, text: 'add more todos' }];\n//cut\nlet { done, text } = todos[0];\n\n// this will not affect the value of `done`\ntodos[0].done = !todos[0].done;\n```\n\n### Classes\n\nClass instances are not proxied. Instead, you can use `$state` in class fields (whether public or private), or as the first assignment to a property immediately inside the `constructor`:\n\n```js\n// @errors: 7006 2554\nclass Todo {\n\tdone = $state(false);\n\n\tconstructor(text) {\n\t\tthis.text = $state(text);\n\t}\n\n\treset() {\n\t\tthis.text = '';\n\t\tthis.done = false;\n\t}\n}\n```\n\n\nWhen calling methods in JavaScript, the value of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) matters. This won't work, because `this` inside the `reset` method will be the `<button>` rather than the `Todo`:\n\n```svelte\n<button onclick={todo.reset}>\n\treset\n</button>\n```\n\nYou can either use an inline function...\n\n```svelte\n<button onclick={() => todo.reset()}>\n\treset\n</button>\n```\n\n...or use an arrow function in the class definition:\n\n```js\n// @errors: 7006 2554\nclass Todo {\n\tdone = $state(false);\n\n\tconstructor(text) {\n\t\tthis.text = $state(text);\n\t}\n\n\treset = () => {\n\t\tthis.text = '';\n\t\tthis.done = false;\n\t}\n}\n```\n\n### Built-in classes\n\nSvelte provides reactive implementations of built-in classes like `Set`, `Map`, `Date` and `URL` that can be imported from [`svelte/reactivity`](svelte-reactivity).\n\n## `$state.raw`\n\nIn cases where you don't want objects and arrays to be deeply reactive you can use `$state.raw`.\n\nState declared with `$state.raw` cannot be mutated; it can only be _reassigned_. In other words, rather than assigning to a property of an object, or using an array method like `push`, replace the object or array altogether if you'd like to update it:\n\n```js\nlet person = $state.raw({\n\tname: 'Heraclitus',\n\tage: 49\n});\n\n// this will have no effect\nperson.age += 1;\n\n// this will work, because we're creating a new person\nperson = {\n\tname: 'Heraclitus',\n\tage: 50\n};\n```\n\nThis can improve performance with large arrays and objects that you weren't planning to mutate anyway, since it avoids the cost of making them reactive. Note that raw state can _contain_ reactive state (for example, a raw array of reactive objects).\n\nAs with `$state`, you can declare class fields using `$state.raw`.\n\n## `$state.snapshot`\n\nTo take a static snapshot of a deeply reactive `$state` proxy, use `$state.snapshot`:\n\n```svelte\n<script>\n\tlet counter = $state({ count: 0 });\n\n\tfunction onclick() {\n\t\t// Will log `{ count: ... }` rather than `Proxy { ... }`\n\t\tconsole.log($state.snapshot(counter));\n\t}\n</script>\n```\n\nThis is handy when you want to pass some state to an external library or API that doesn't expect a proxy, such as `structuredClone`.\n\n## `$state.eager`\n\nWhen state changes, it may not be reflected in the UI immediately if it is used by an `await` expression, because [updates are synchronized](await-expressions#Synchronized-updates).\n\nIn some cases, you may want to update the UI as soon as the state changes. For example, you might want to update a navigation bar when the user clicks on a link, so that they get visual feedback while waiting for the new page to load. To do this, use `$state.eager(value)`:\n\n```svelte\n<nav>\n\t<a href=\"/\" aria-current={$state.eager(pathname) === '/' ? 'page' : null}>home</a>\n\t<a href=\"/about\" aria-current={$state.eager(pathname) === '/about' ? 'page' : null}>about</a>\n</nav>\n```\n\nUse this feature sparingly, and only to provide feedback in response to user action — in general, allowing Svelte to coordinate updates will provide a better user experience.\n\n## Passing state into functions\n\nJavaScript is a _pass-by-value_ language — when you call a function, the arguments are the _values_ rather than the _variables_. In other words:\n\n```js\n/// file: index.js\n// @filename: index.js\n//cut\n/**\n * @param {number} a\n * @param {number} b\n */\nfunction add(a, b) {\n\treturn a + b;\n}\n\nlet a = 1;\nlet b = 2;\nlet total = add(a, b);\nconsole.log(total); // 3\n\na = 3;\nb = 4;\nconsole.log(total); // still 3!\n```\n\nIf `add` wanted to have access to the _current_ values of `a` and `b`, and to return the current `total` value, you would need to use functions instead:\n\n```js\n/// file: index.js\n// @filename: index.js\n//cut\n/**\n * @param {() => number} getA\n * @param {() => number} getB\n */\nfunction add(getA, getB) {\n\treturn() => getA() + getB();\n}\n\nlet a = 1;\nlet b = 2;\nlet total = add(() => a, () => b);\nconsole.log(total()); // 3\n\na = 3;\nb = 4;\nconsole.log(total()); // 7\n```\n\nState in Svelte is no different — when you reference something declared with the `$state` rune...\n\n```js\nlet a =$state(1);\nlet b =$state(2);\n```\n\n...you're accessing its _current value_.\n\nNote that 'functions' is broad — it encompasses properties of proxies and [`get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/[`set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) properties...\n\n```js\n/// file: index.js\n// @filename: index.js\n//cut\n/**\n * @param {{ a: number, b: number }} input\n */\nfunction add(input) {\n\treturn {\n\t\tget value() {\n\t\t\treturn input.a + input.b;\n\t\t}\n\t};\n}\n\nlet input = $state({ a: 1, b: 2 });\nlet total = add(input);\nconsole.log(total.value); // 3\n\ninput.a = 3;\ninput.b = 4;\nconsole.log(total.value); // 7\n```\n\n...though if you find yourself writing code like that, consider using [classes](#Classes) instead.\n\n## Passing state across modules\n\nYou can declare state in `.svelte.js` and `.svelte.ts` files, but you can only _export_ that state if it's not directly reassigned. In other words you can't do this:\n\n```js\n/// file: state.svelte.js\nexport let count = $state(0);\n\nexport function increment() {\n\tcount += 1;\n}\n```\n\nThat's because every reference to `count` is transformed by the Svelte compiler — the code above is roughly equivalent to this:\n\n```js\n/// file: state.svelte.js (compiler output)\n// @filename: index.ts\ninterface Signal<T> {\n\tvalue: T;\n}\n\ninterface Svelte {\n\tstate<T>(value?: T): Signal<T>;\n\tget<T>(source: Signal<T>): T;\n\tset<T>(source: Signal<T>, value: T): void;\n}\ndeclare const $: Svelte;\n//cut\nexport let count = $.state(0);\n\nexport function increment() {\n\t$.set(count, $.get(count) + 1);\n}\n```\n\n\nSince the compiler only operates on one file at a time, if another file imports `count` Svelte doesn't know that it needs to wrap each reference in `$.get` and `$.set`:\n\n```js\n// @filename: state.svelte.js\nexport let count = 0;\n\n// @filename: index.js\n//cut\nimport { count } from './state.svelte.js';\n\nconsole.log(typeof count); // 'object', not 'number'\n```\n\nThis leaves you with two options for sharing state between modules — either don't reassign it...\n\n```js\n// This is allowed — since we're updating\n// `counter.count` rather than `counter`,\n// Svelte doesn't wrap it in `$.state`\nexport const counter = $state({\n\tcount: 0\n});\n\nexport function increment() {\n\tcounter.count += 1;\n}\n```\n\n...or don't directly export it:\n\n```js\nlet count = $state(0);\n\nexport function getCount() {\n\treturn count;\n}\n\nexport function increment() {\n\tcount += 1;\n}\n```","size_bytes":8798,"metadata":{"tags":"rune-state","title":"$state"},"created_at":"2025-07-18T15:47:38.907Z","updated_at":"2026-02-14T01:33:24.867Z"},{"path":"apps/svelte.dev/content/docs/svelte/02-runes/03-$derived.md","title":"$derived","filename":"03-$derived.md","content":"Derived state is declared with the `$derived` rune:\n\n```svelte\n<script>\n\tlet count = $state(0);\n\tlet doubled = $derived(count * 2);\n</script>\n\n<button onclick={() => count++}>\n\t{doubled}\n</button>\n\n<p>{count} doubled is {doubled}</p>\n```\n\nThe expression inside `$derived(...)` should be free of side-effects. Svelte will disallow state changes (e.g. `count++`) inside derived expressions.\n\nAs with `$state`, you can mark class fields as `$derived`.\n\n\n## `$derived.by`\n\nSometimes you need to create complex derivations that don't fit inside a short expression. In these cases, you can use `$derived.by` which accepts a function as its argument.\n\n```svelte\n<script>\n\tlet numbers = $state([1, 2, 3]);\n\tlet total = $derived.by(() => {\n\t\tlet total = 0;\n\t\tfor (const n of numbers) {\n\t\t\ttotal += n;\n\t\t}\n\t\treturn total;\n\t});\n</script>\n\n<button onclick={() => numbers.push(numbers.length + 1)}>\n\t{numbers.join(' + ')} = {total}\n</button>\n```\n\nIn essence, `$derived(expression)` is equivalent to `$derived.by(() => expression)`.\n\n## Understanding dependencies\n\nAnything read synchronously inside the `$derived` expression (or `$derived.by` function body) is considered a _dependency_ of the derived state. When the state changes, the derived will be marked as _dirty_ and recalculated when it is next read.\n\nTo exempt a piece of state from being treated as a dependency, use [`untrack`](svelte#untrack).\n\n## Overriding derived values\n\nDerived expressions are recalculated when their dependencies change, but you can temporarily override their values by reassigning them (unless they are declared with `const`). This can be useful for things like _optimistic UI_, where a value is derived from the 'source of truth' (such as data from your server) but you'd like to show immediate feedback to the user:\n\n```svelte\n<script>\n\tlet { post, like } = $props();\n\n\tlet likes = $derived(post.likes);\n\n\tasync function onclick() {\n\t\t// increment the `likes` count immediately...\n\t\tlikes += 1;\n\n\t\t// and tell the server, which will eventually update `post`\n\t\ttry {\n\t\t\tawait like();\n\t\t} catch {\n\t\t\t// failed! roll back the change\n\t\t\tlikes -= 1;\n\t\t}\n\t}\n</script>\n\n<button {onclick}>🧡 {likes}</button>\n```\n\n\n## Deriveds and reactivity\n\nUnlike `$state`, which converts objects and arrays to [deeply reactive proxies]($state#Deep-state), `$derived` values are left as-is. For example, [in a case like this](/playground/untitled#H4sIAAAAAAAAE4VU22rjMBD9lUHd3aaQi9PdstS1A3t5XvpQ2Ic4D7I1iUUV2UjjNMX431eS7TRdSosxgjMzZ45mjt0yzffIYibvy0ojFJWqDKCQVBk2ZVup0LJ43TJ6rn2aBxw-FP2o67k9oCKP5dziW3hRaUJNjoYltjCyplWmM1JIIAn3FlL4ZIkTTtYez6jtj4w8WwyXv9GiIXiQxLVs9pfTMR7EuoSLIuLFbX7Z4930bZo_nBrD1bs834tlfvsBz9_SyX6PZXu9XaL4gOWn4sXjeyzftv4ZWfyxubpzxzg6LfD4MrooxELEosKCUPigQCMPKCZh0OtQE1iSxcsmdHuBvCiHZXALLXiN08EL3RRkaJ_kDVGle0HcSD5TPEeVtj67O4Nrg9aiSNtBY5oODJkrL5QsHtN2cgXp6nSJMWzpWWGasdlsGEMbzi5jPr5KFr0Ep7pdeM2-TCelCddIhDxAobi1jqF3cMaC1RKp64bAW9iFAmXGIHfd4wNXDabtOLN53w8W53VvJoZLh7xk4Rr3CoL-UNoLhWHrT1JQGcM17u96oES5K-kc2XOzkzqGCKL5De79OUTyyrg1zgwXsrEx3ESfx4Bz0M5UjVMHB24mw9SuXtXFoN13fYKOM1tyUT3FbvbWmSWCZX2Er-41u5xPoml45svRahl9Wb9aasbINJixDZwcPTbyTLZSUsAvrg_cPuCR7s782_WU8343Y72Qtlb8OYatwuOQvuN13M_hJKNfxann1v1U_B1KZ_D_mzhzhz24fw85CSz2irtN9w9HshBK7AQAAA==)...\n\n```js\n// @errors: 7005\nlet items = $state([ /*...*/ ]);\n\nlet index = $state(0);\nlet selected = $derived(items[index]);\n```\n\n...you can change (or `bind:` to) properties of `selected` and it will affect the underlying `items` array. If `items` was _not_ deeply reactive, mutating `selected` would have no effect.\n\n## Destructuring\n\nIf you use destructuring with a `$derived` declaration, the resulting variables will all be reactive — this...\n\n```js\nfunction stuff() { return { a: 1, b: 2, c: 3 } }\n//cut\nlet { a, b, c } = $derived(stuff());\n```\n\n...is roughly equivalent to this:\n\n```js\nfunction stuff() { return { a: 1, b: 2, c: 3 } }\n//cut\nlet _stuff = $derived(stuff());\nlet a = $derived(_stuff.a);\nlet b = $derived(_stuff.b);\nlet c = $derived(_stuff.c);\n```\n\n## Update propagation\n\nSvelte uses something called _push-pull reactivity_ — when state is updated, everything that depends on the state (whether directly or indirectly) is immediately notified of the change (the 'push'), but derived values are not re-evaluated until they are actually read (the 'pull').\n\nIf the new value of a derived is referentially identical to its previous value, downstream updates will be skipped. In other words, Svelte will only update the text inside the button when `large` changes, not when `count` changes, even though `large` depends on `count`:\n\n```svelte\n<script>\n\tlet count = $state(0);\n\tlet large = $derived(count > 10);\n</script>\n\n<button onclick={() => count++}>\n\t{large}\n</button>\n```","size_bytes":4752,"metadata":{"tags":"rune-derived","title":"$derived"},"created_at":"2025-07-18T15:47:38.907Z","updated_at":"2026-02-14T01:33:24.869Z"},{"path":"apps/svelte.dev/content/docs/svelte/02-runes/04-$effect.md","title":"$effect","filename":"04-$effect.md","content":"Effects are functions that run when state updates, and can be used for things like calling third-party libraries, drawing on `<canvas>` elements, or making network requests. They only run in the browser, not during server-side rendering.\n\nGenerally speaking, you should _not_ update state inside effects, as it will make code more convoluted and will often lead to never-ending update cycles. If you find yourself doing so, see [when not to use `$effect`](#When-not-to-use-$effect) to learn about alternative approaches.\n\nYou can create an effect with the `$effect` rune ([demo](/playground/untitled#H4sIAAAAAAAAE31S246bMBD9lZF3pSRSAqTVvrCAVPUP2sdSKY4ZwJJjkD0hSVH-vbINuWxXfQH5zMyZc2ZmZLVUaFn6a2R06ZGlHmBrpvnBvb71fWQHVOSwPbf4GS46TajJspRlVhjZU1HqkhQSWPkHIYdXS5xw-Zas3ueI6FRn7qHFS11_xSRZhIxbFtcDtw7SJb1iXaOg5XIFeQGjzyPRaevYNOGZIJ8qogbpe8CWiy_VzEpTXiQUcvPDkSVrSNZz1UlW1N5eLcqmpdXUvaQ4BmqlhZNUCgxuzFHDqUWNAxrYeUM76AzsnOsdiJbrBp_71lKpn3RRbii-4P3f-IMsRxS-wcDV_bL4PmSdBa2wl7pKnbp8DMgVvJm8ZNskKRkEM_OzyOKQFkgqOYBQ3Nq89Ns0nbIl81vMFN-jKoLMTOr-SOBOJS-Z8f5Y6D1wdcR8dFqvEBdetK-PHwj-z-cH8oHPY54wRJ8Ys7iSQ3Bg3VA9azQbmC9k35kKzYa6PoVtfwbbKVnBixBiGn7Pq0rqJoUtHiCZwAM3jdTPWCVtr_glhVrhecIa3vuksJ_b7TqFs4DPyriSjd5IwoNNQaAmNI-ESfR2p8zimzvN1swdCkvJHPH6-_oX8o1SgcIDAAA=)):\n\n```svelte\n<script>\n\tlet size = $state(50);\n\tlet color = $state('#ff3e00');\n\n\tlet canvas;\n\n\t$effect(() => {\n\t\tconst context = canvas.getContext('2d');\n\t\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n\n\t\t// this will re-run whenever `color` or `size` change\n\t\tcontext.fillStyle = color;\n\t\tcontext.fillRect(0, 0, size, size);\n\t});\n</script>\n\n<canvas bind:this={canvas} width=\"100\" height=\"100\"></canvas>\n```\n\nWhen Svelte runs an effect function, it tracks which pieces of state (and derived state) are accessed (unless accessed inside [`untrack`](svelte#untrack)), and re-runs the function when that state later changes.\n\n\n### Understanding lifecycle\n\nYour effects run after the component has been mounted to the DOM, and in a [microtask](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) after state changes. Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied.\n\nYou can use `$effect` anywhere, not just at the top level of a component, as long as it is called while a parent effect is running.\n\n\nAn effect can return a _teardown function_ which will run immediately before the effect re-runs ([demo](/playground/untitled#H4sIAAAAAAAAE42SQVODMBCF_8pOxkPRKq3HCsx49K4n64xpskjGkDDJ0tph-O8uINo6HjxB3u7HvrehE07WKDbiyZEhi1osRWksRrF57gQdm6E2CKx_dd43zU3co6VB28mIf-nKO0JH_BmRRRVMQ8XWbXkAgfKtI8jhIpIkXKySu7lSG2tNRGZ1_GlYr1ZTD3ddYFmiosUigbyAbpC2lKbwWJkIB8ZhhxBQBWRSw6FCh3sM8GrYTthL-wqqku4N44TyqEgwF3lmRHr4Op0PGXoH31c5rO8mqV-eOZ49bikgtcHBL55tmhIkEMqg_cFB2TpFxjtg703we6NRL8HQFCS07oSUCZi6Rm04lz1yytIHBKoQpo1w6Gsm4gmyS8b8Y5PydeMdX8gwS2Ok4I-ov5NZtvQde95GMsccn_1wzNKfu3RZtS66cSl9lvL7qO1aIk7knbJGvefdtIOzi73M4bYvovUHDFk6AcX_0HRESxnpBOW_jfCDxIZCi_1L_wm4xGQ60wIAAA==)).\n\n```svelte\n<script>\n\tlet count = $state(0);\n\tlet milliseconds = $state(1000);\n\n\t$effect(() => {\n\t\t// This will be recreated whenever `milliseconds` changes\n\t\tconst interval = setInterval(() => {\n\t\t\tcount += 1;\n\t\t}, milliseconds);\n\n\t\treturn () => {\n\t\t\t// if a teardown function is provided, it will run\n\t\t\t// a) immediately before the effect re-runs\n\t\t\t// b) when the component is destroyed\n\t\t\tclearInterval(interval);\n\t\t};\n\t});\n</script>\n\n<h1>{count}</h1>\n\n<button onclick={() => (milliseconds *= 2)}>slower</button>\n<button onclick={() => (milliseconds /= 2)}>faster</button>\n```\n\nTeardown functions also run when the effect is destroyed, which happens when its parent is destroyed (for example, a component is unmounted) or the parent effect re-runs.\n\n### Understanding dependencies\n\n`$effect` automatically picks up any reactive values (`$state`, `$derived`, `$props`) that are _synchronously_ read inside its function body (including indirectly, via function calls) and registers them as dependencies. When those dependencies change, the `$effect` schedules a re-run.\n\nIf `$state` and `$derived` are used directly inside the `$effect` (for example, during creation of a [reactive class](https://svelte.dev/docs/svelte/$state#Classes)), those values will _not_ be treated as dependencies.\n\nValues that are read _asynchronously_ — after an `await` or inside a `setTimeout`, for example — will not be tracked. Here, the canvas will be repainted when `color` changes, but not when `size` changes ([demo](/playground/untitled#H4sIAAAAAAAAE31T246bMBD9lZF3pWSlBEirfaEQqdo_2PatVIpjBrDkGGQPJGnEv1e2IZfVal-wfHzmzJyZ4cIqqdCy9M-F0blDlnqArZjmB3f72XWRHVCRw_bc4me4aDWhJstSlllhZEfbQhekkMDKfwg5PFvihMvX5OXH_CJa1Zrb0-Kpqr5jkiwC48rieuDWQbqgZ6wqFLRcvkC-hYvnkWi1dWqa8ESQTxFRjfQWsOXiWzmr0sSLhEJu3p1YsoJkNUcdZUnN9dagrBu6FVRQHAM10sJRKgUG16bXcGxQ44AGdt7SDkTDdY02iqLHnJVU6hedlWuIp94JW6Tf8oBt_8GdTxlF0b4n0C35ZLBzXb3mmYn3ae6cOW74zj0YVzDNYXRHFt9mprNgHfZSl6mzml8CMoLvTV6wTZIUDEJv5us2iwMtiJRyAKG4tXnhl8O0yhbML0Wm-B7VNlSSSd31BG7z8oIZZ6dgIffAVY_5xdU9Qrz1Bnx8fCfwtZ7v8Qc9j3nB8PqgmMWlHIID6-bkVaPZwDySfWtKNGtquxQ23Qlsq2QJT0KIqb8dL0up6xQ2eIBkAg_c1FI_YqW0neLnFCqFpwmreedJYT7XX8FVOBfwWRhXstZrSXiwKQjUhOZeMIleb5JZfHWn2Yq5pWEpmR7Hv-N_wEqT8hEEAAA=)):\n\n```ts\n// @filename: index.ts\ndeclare let canvas: {\n\twidth: number;\n\theight: number;\n\tgetContext(type: '2d', options?: CanvasRenderingContext2DSettings): CanvasRenderingContext2D;\n};\ndeclare let color: string;\ndeclare let size: number;\n\n//cut\n$effect(() => {\n\tconst context = canvas.getContext('2d');\n\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n\n\t// this will re-run whenever `color` changes...\n\tcontext.fillStyle = color;\n\n\tsetTimeout(() => {\n\t\t// ...but not when `size` changes\n\t\tcontext.fillRect(0, 0, size, size);\n\t}, 0);\n});\n```\n\nAn effect only reruns when the object it reads changes, not when a property inside it changes. (If you want to observe changes _inside_ an object at dev time, you can use [`$inspect`]($inspect).)\n\n```svelte\n<script>\n\tlet state = $state({ value: 0 });\n\tlet derived = $derived({ value: state.value * 2 });\n\n\t// this will run once, because `state` is never reassigned (only mutated)\n\t$effect(() => {\n\t\tstate;\n\t});\n\n\t// this will run whenever `state.value` changes...\n\t$effect(() => {\n\t\tstate.value;\n\t});\n\n\t// ...and so will this, because `derived` is a new object each time\n\t$effect(() => {\n\t\tderived;\n\t});\n</script>\n\n<button onclick={() => (state.value += 1)}>\n\t{state.value}\n</button>\n\n<p>{state.value} doubled is {derived.value}</p>\n```\n\nAn effect only depends on the values that it read the last time it ran. This has interesting implications for effects that have conditional code.\n\nFor instance, if `condition` is `true` in the code snippet below, the code inside the `if` block will run and `color` will be evaluated. This means that changes to either `condition` or `color` [will cause the effect to re-run](/playground/untitled#H4sIAAAAAAAAE21RQW6DMBD8ytaNBJHaJFLViwNIVZ8RcnBgXVk1xsILTYT4e20TQg89IOPZ2fHM7siMaJBx9tmaWpFqjQNlAKXEihx7YVJpdIyfRkY3G4gB8Pi97cPanRtQU8AuwuF_eNUaQuPlOMtc1SlLRWlKUo1tOwJflUikQHZtA0klzCDc64Imx0ANn8bInV1CDhtHgjClrsftcSXotluLybOUb3g4JJHhOZs5WZpuIS9gjNqkJKQP5e2ClrR4SMdZ13E4xZ8zTPOTJU2A2uE_PQ9COCI926_hTVarIU4hu_REPlBrKq2q73ycrf1N-vS4TMUsulaVg3EtR8H9rFgsg8uUsT1B2F9eshigZHBRpuaD0D3mY8Qm2BfB5N2YyRzdNEYVDy0Ja-WsFjcOUuP1HvFLWA6H3XuHTUSmmDV2--0TXonxsKbp7G9C6R__NONS-MFNvxj_d6mBAgAA).\n\nConversely, if `condition` is `false`, `color` will not be evaluated, and the effect will _only_ re-run again when `condition` changes.\n\n```ts\n// @filename: ambient.d.ts\ndeclare module 'canvas-confetti' {\n\tinterface ConfettiOptions {\n\t\tcolors: string[];\n\t}\n\n\tfunction confetti(opts?: ConfettiOptions): void;\n\texport default confetti;\n}\n\n// @filename: index.js\n//cut\nimport confetti from 'canvas-confetti';\n\nlet condition = $state(true);\nlet color = $state('#ff3e00');\n\n$effect(() => {\n\tif (condition) {\n\t\tconfetti({ colors: [color] });\n\t} else {\n\t\tconfetti();\n\t}\n});\n```\n\n## `$effect.pre`\n\nIn rare cases, you may need to run code _before_ the DOM updates. For this we can use the `$effect.pre` rune:\n\n```svelte\n<script>\n\timport { tick } from 'svelte';\n\n\tlet div = $state();\n\tlet messages = $state([]);\n\n\t// ...\n\n\t$effect.pre(() => {\n\t\tif (!div) return; // not yet mounted\n\n\t\t// reference `messages` array length so that this code re-runs whenever it changes\n\t\tmessages.length;\n\n\t\t// autoscroll when new messages are added\n\t\tif (div.offsetHeight + div.scrollTop > div.scrollHeight - 20) {\n\t\t\ttick().then(() => {\n\t\t\t\tdiv.scrollTo(0, div.scrollHeight);\n\t\t\t});\n\t\t}\n\t});\n</script>\n\n<div bind:this={div}>\n\t{#each messages as message}\n\t\t<p>{message}</p>\n\t{/each}\n</div>\n```\n\nApart from the timing, `$effect.pre` works exactly like `$effect`.\n\n## `$effect.tracking`\n\nThe `$effect.tracking` rune is an advanced feature that tells you whether or not the code is running inside a tracking context, such as an effect or inside your template ([demo](/playground/untitled#H4sIAAAAAAAACn3PwYrCMBDG8VeZDYIt2PYeY8Dn2HrIhqkU08nQjItS-u6buAt7UDzmz8ePyaKGMWBS-nNRcmdU-hHUTpGbyuvI3KZvDFLal0v4qvtIgiSZUSb5eWSxPfWSc4oB2xDP1XYk8HHiSHkICeXKeruDDQ4Demlldv4y0rmq6z10HQwuJMxGVv4mVVXDwcJS0jP9u3knynwtoKz1vifT_Z9Jhm0WBCcOTlDD8kyspmML5qNpHg40jc3fFryJ0iWsp_UHgz3180oBAAA=)):\n\n```svelte\n<script>\n\tconsole.log('in component setup:', $effect.tracking()); // false\n\n\t$effect(() => {\n\t\tconsole.log('in effect:', $effect.tracking()); // true\n\t});\n</script>\n\n<p>in template: {$effect.tracking()}</p> <!-- true -->\n```\n\nIt is used to implement abstractions like [`createSubscriber`](/docs/svelte/svelte-reactivity#createSubscriber), which will create listeners to update reactive values but _only_ if those values are being tracked (rather than, for example, read inside an event handler).\n\n## `$effect.pending`\n\nWhen using [`await`](await-expressions) in components, the `$effect.pending()` rune tells you how many promises are pending in the current [boundary](svelte-boundary), not including child boundaries ([demo](/playground/untitled#H4sIAAAAAAAAE3WRMU_DMBCF_8rJdHDUqilILGkaiY2RgY0yOPYZWbiOFV8IleX_jpMUEAIWS_7u-d27c2ROnJBV7B6t7WDsequAozKEqmAbpo3FwKqnyOjsJ90EMr-8uvN-G97Q0sRaEfAvLjtH6CjbsDrI3nhqju5IFgkEHGAVSBDy62L_SdtvejPTzEU4Owl6cJJM50AoxcUG2gLiVM31URgChyM89N3JBORcF3BoICA9mhN2A3G9gdvdrij2UJYgejLaSCMsKLTivNj0SEOf7WEN7ZwnHV1dfqd2dTsQ5QCdk9bI10PkcxexXqcmH3W51Jt_le2kbH8os9Y3UaTcNLYpDx-Xab6GTHXpZ128MhpWqDVK2np0yrgXXqQpaLa4APDLBkIF8bd2sYql0Sn_DeE7sYr6AdNzvgljR-MUq7SwAdMHeUtgHR4CAAA=)):\n\n```svelte\n<button onclick={() => a++}>a++</button>\n<button onclick={() => b++}>b++</button>\n\n<p>{a} + {b} = {await add(a, b)}</p>\n\n{#if $effect.pending()}\n\t<p>pending promises: {$effect.pending()}</p>\n{/if}\n```\n\n## `$effect.root`\n\nThe `$effect.root` rune is an advanced feature that creates a non-tracked scope that doesn't auto-cleanup. This is useful for nested effects that you want to manually control. This rune also allows for the creation of effects outside of the component initialisation phase.\n\n```js\nconst destroy = $effect.root(() => {\n\t$effect(() => {\n\t\t// setup\n\t});\n\n\treturn () => {\n\t\t// cleanup\n\t};\n});\n\n// later...\ndestroy();\n```\n\n## When not to use `$effect`\n\nIn general, `$effect` is best considered something of an escape hatch — useful for things like analytics and direct DOM manipulation — rather than a tool you should use frequently. In particular, avoid using it to synchronise state. Instead of this...\n\n```svelte\n<script>\n\tlet count = $state(0);\n\tlet doubled = $state();\n\n\t// don't do this!\n\t$effect(() => {\n\t\tdoubled = count * 2;\n\t});\n</script>\n```\n\n...do this:\n\n```svelte\n<script>\n\tlet count = $state(0);\n\tlet doubled = $derived(count * 2);\n</script>\n```\n\n\nIf you're using an effect because you want to be able to reassign the derived value (to build an optimistic UI, for example) note that [deriveds can be directly overridden]($derived#Overriding-derived-values) as of Svelte 5.25.\n\nYou might be tempted to do something convoluted with effects to link one value to another. The following example shows two inputs for \"money spent\" and \"money left\" that are connected to each other. If you update one, the other should update accordingly. Don't use effects for this ([demo](/playground/untitled#H4sIAAAAAAAAE5WRTWrDMBCFryKGLBJoY3fRjWIHeoiu6i6UZBwEY0VE49TB-O6VxrFTSih0qe_Ne_OjHpxpEDS8O7ZMeIAnqC1hAP3RA1990hKI_Fb55v06XJA4sZ0J-IjvT47RcYyBIuzP1vO2chVHHFjxiQ2pUr3k-SZRQlbBx_LIFoEN4zJfzQph_UMQr4hRXmBd456Xy5Uqt6pPKHmkfmzyPAZL2PCnbRpg8qWYu63I7lu4gswOSRYqrPNt3CgeqqzgbNwRK1A76w76YqjFspfcQTWmK3vJHlQm1puSTVSeqdOc_r9GaeCHfUSY26TXry6Br4RSK3C6yMEGT-aqVU3YbUZ2NF6rfP2KzXgbuYzY46czdgyazy0On_FlLH3F-UDXhgIO35UGlA1rAgAA)):\n\n```svelte\n<script>\n\tconst total = 100;\n\tlet spent = $state(0);\n\tlet left = $state(total);\n\n\t$effect(() => {\n\t\tleft = total - spent;\n\t});\n\n\t$effect(() => {\n\t\tspent = total - left;\n\t});\n</script>\n\n<label>\n\t<input type=\"range\" bind:value={spent} max={total} />\n\t{spent}/{total} spent\n</label>\n\n<label>\n\t<input type=\"range\" bind:value={left} max={total} />\n\t{left}/{total} left\n</label>\n```\n\nInstead, use `oninput` callbacks or — better still — [function bindings](bind#Function-bindings) where possible ([demo](/playground/untitled#H4sIAAAAAAAAE5VRvW7CMBB-FcvqECQK6dDFJEgsnfoGTQdDLsjSxVjxhYKivHvPBwFUsXS8774_nwftbQva6I_e78gdvNo6Xzu_j3quG4cQtfkaNJ1DIiWA8atkE8IiHgEpYVsb4Rm-O3gCT2yji7jrXKB15StiOJKiA1lUpXrL81VCEUjFwHTGXiJZgiyf3TYIjSxq6NwR6uyifr0ohMbEZnpHH2rWf7ImS8KZGtK6osl_UqelRIyVL5b3ir5AuwWUtoXzoee6fIWy0p31e6i0XMocLfZQDuI6qtaeykGcR7UU6XWznFAZU9LN_X9B2UyVayk9f3ji0-REugen6U9upDOCcAWcLlS7GNCejWoQTqsLtrfBqHzxDu3DrUTOf0xwIm2o62H85sk6_OHG2jQWI4y_3byXXGMCAAA=)):\n\n```svelte\n<script>\n\tconst total = 100;\n\tlet spent = $state(0);\n\tlet left = $derived(total - spent);\n\nfunction updateLeft(left) {\n\t\tspent = total - left;\n\t}\n</script>\n\n<label>\n\t<input type=\"range\" bind:value={spent} max={total} />\n\t{spent}/{total} spent\n</label>\n\n<label>\n\t<input type=\"range\"bind:value={() => left, updateLeft}max={total} />\n\t{left}/{total} left\n</label>\n```\n\nIf you absolutely have to update `$state` within an effect and run into an infinite loop because you read and write to the same `$state`, use [untrack](svelte#untrack).","size_bytes":14156,"metadata":{"tags":"rune-effect","title":"$effect"},"created_at":"2025-07-18T15:47:38.909Z","updated_at":"2026-02-14T01:33:24.873Z"},{"path":"apps/svelte.dev/content/docs/svelte/02-runes/05-$props.md","title":"$props","filename":"05-$props.md","content":"The inputs to a component are referred to as _props_, which is short for _properties_. You pass props to components just like you pass attributes to elements:\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport MyComponent from './MyComponent.svelte';\n</script>\n\n<MyComponent adjective=\"cool\" />\n```\n\nOn the other side, inside `MyComponent.svelte`, we can receive props with the `$props` rune...\n\n```svelte\n<!file: MyComponent.svelte>\n<script>\n\tlet props = $props();\n</script>\n\n<p>this component is {props.adjective}</p>\n```\n\n...though more commonly, you'll [_destructure_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) your props:\n\n```svelte\n<!file: MyComponent.svelte>\n<script>\n\tlet{ adjective }= $props();\n</script>\n\n<p>this component is {adjective}</p>\n```\n\n## Fallback values\n\nDestructuring allows us to declare fallback values, which are used if the parent component does not set a given prop (or the value is `undefined`):\n\n```js\nlet { adjective = 'happy' } = $props();\n```\n\n\n## Renaming props\n\nWe can also use the destructuring assignment to rename props, which is necessary if they're invalid identifiers, or a JavaScript keyword like `super`:\n\n```js\nlet { super: trouper = 'lights are gonna find me' } = $props();\n```\n\n## Rest props\n\nFinally, we can use a _rest property_ to get, well, the rest of the props:\n\n```js\nlet { a, b, c, ...others } = $props();\n```\n\n## Updating props\n\nReferences to a prop inside a component update when the prop itself updates — when `count` changes in `App.svelte`, it will also change inside `Child.svelte`. But the child component is able to temporarily override the prop value, which can be useful for unsaved ephemeral state ([demo](/playground/untitled#H4sIAAAAAAAAE6WQ0WrDMAxFf0WIQR0Wmu3VTQJln7HsIfVcZubIxlbGRvC_DzuBraN92qPula50tODZWB1RPi_IX16jLALWSOOUq6P3-_ihLWftNEZ9TVeOWBNHlNhGFYznfqCBzeRdYHh6M_YVzsFNsNs3pdpGd4eBcqPVDMrNxNDBXeSRtXioDgO1zU8ataeZ2RE4Utao924RFXQ9iHXwvoPHKpW1xY4g_Bg0cSVhKS0p560Za95612ZC02ONrD8ZJYdZp_rGQ37ff_mSP86Np2TWZaNNmdcH56P4P67K66_SXoK9pG-5dF5Z9QEAAA==)):\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Child from './Child.svelte';\n\n\tlet count = $state(0);\n</script>\n\n<button onclick={() => (count += 1)}>\n\tclicks (parent): {count}\n</button>\n\n<Child {count} />\n```\n\n```svelte\n<!file: Child.svelte>\n<script>\n\tlet { count } = $props();\n</script>\n\n<button onclick={() => (count += 1)}>\n\tclicks (child): {count}\n</button>\n```\n\nWhile you can temporarily _reassign_ props, you should not _mutate_ props unless they are [bindable]($bindable).\n\nIf the prop is a regular object, the mutation will have no effect ([demo](/playground/untitled#H4sIAAAAAAAAE3WQwU7DMBBEf2W1QmorQgJXk0RC3PkBwiExG9WQrC17U4Es_ztKUkQp9OjxzM7bjcjtSKjwyfKNp1aLORA4b13ADHszUED1HFE-3eyaBcy-Mw_O5eFAg8xa1wb6T9eWhVgCKiyD9sZJ3XAjZnTWCzzuzfAKvbcjbPJieR2jm_uGy-InweXqtd0baaliBG0nFgW3kBIUNWYo9CGoxE-UsgvIpw2_oc9-LmAPJBCPDJCggqvlVtvdH9puErEMlvVg9HsVtzuoaojzkKKAfRuALVDfk5ZZW0fmy05wXcFdwyktlUs-KIinljTXrRVnm7-kL9dYLVbUAQAA)):\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Child from './Child.svelte';\n</script>\n\n<Child object={{ count: 0 }} />\n```\n\n```svelte\n<!file: Child.svelte>\n<script>\n\tlet { object } = $props();\n</script>\n\n<button onclick={() => {\n\t// has no effect\n\tobject.count += 1\n}}>\n\tclicks: {object.count}\n</button>\n```\n\nIf the prop is a reactive state proxy, however, then mutations _will_ have an effect but you will see an [`ownership_invalid_mutation`](runtime-warnings#Client-warnings-ownership_invalid_mutation) warning, because the component is mutating state that does not 'belong' to it ([demo](/playground/untitled#H4sIAAAAAAAAE3WR0U7DMAxFf8VESBuiauG1WycheOEbKA9p67FA6kSNszJV-XeUZhMw2GN8r-1znUmQ7FGU4pn2UqsOes-SlSGRia3S6ET5Mgk-2OiJBZGdOh6szd0eNcdaIx3-V28NMRI7UYq1awdleVNTzaq3ZmB43CndwXYwPSzyYn4dWxermqJRI4Np3rFlqODasWRcTtAaT1zCHYSbVU3r4nsyrdPMKTUFKDYiE4yfLEoePIbsQpqfy3_nOVMuJIqg0wk1RFg7GOuWfwEbz2wIDLVatR_VtLyBagNTHFIUMCqtoZXeIfAOU1JoUJsR2IC3nWTMjt7GM4yKdyBhlAMpesvhydCC0y_i0ZagHByMh26WzUhXUUxKnpbcVnBfUwhznJnNlac7JkuIURL-2VVfwxflyrWcSQIAAA==)):\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Child from './Child.svelte';\n\n\tlet object = $state({count: 0});\n</script>\n\n<Child {object} />\n```\n\n```svelte\n<!file: Child.svelte>\n<script>\n\tlet { object } = $props();\n</script>\n\n<button onclick={() => {\n\t// will cause the count below to update,\n\t// but with a warning. Don't mutate\n\t// objects you don't own!\n\tobject.count += 1\n}}>\n\tclicks: {object.count}\n</button>\n```\n\nThe fallback value of a prop not declared with `$bindable` is left untouched — it is not turned into a reactive state proxy — meaning mutations will not cause updates ([demo](/playground/untitled#H4sIAAAAAAAAE3WQwU7DMBBEf2VkIbUVoYFraCIh7vwA4eC4G9Wta1vxpgJZ_nfkBEQp9OjxzOzTRGHlkUQlXpy9G0gq1idCL43ppDrAD84HUYheGwqieo2CP3y2Z0EU3-En79fhRIaz1slA_-nKWSbLQVRiE9SgPTetbVkfvRsYzztttugHd8RiXU6vr-jisbWb8idhN7O3bEQhmN5ZVDyMlIorcOddv_Eufq4AGmJEuG5PilEjQrnRcoV7JCTUuJlGWq7-YHYjs7NwVhmtDnVcrlA3iLmzLLGTAdaB-j736h68Oxv-JM1I0AFjoG1OzPfX023c1nhobUoT39QeKsRzS8owM8DFTG_pE6dcVl70AQAA))\n\n```svelte\n<!file: Child.svelte>\n<script>\n\tlet { object = { count: 0 } } = $props();\n</script>\n\n<button onclick={() => {\n\t// has no effect if the fallback value is used\n\tobject.count += 1\n}}>\n\tclicks: {object.count}\n</button>\n```\n\nIn summary: don't mutate props. Either use callback props to communicate changes, or — if parent and child should share the same object — use the [`$bindable`]($bindable) rune.\n\n## Type safety\n\nYou can add type safety to your components by annotating your props, as you would with any other variable declaration. In TypeScript that might look like this...\n\n```svelte\n<script lang=\"ts\">\n\tlet { adjective }: { adjective: string } = $props();\n</script>\n```\n\n...while in JSDoc you can do this:\n\n```svelte\n<script>\n\t/** @type {{ adjective: string }} */\n\tlet { adjective } = $props();\n</script>\n```\n\nYou can, of course, separate the type declaration from the annotation:\n\n```svelte\n<script lang=\"ts\">\n\tinterface Props {\n\t\tadjective: string;\n\t}\n\n\tlet { adjective }: Props = $props();\n</script>\n```\n\n\nIf your component exposes [snippet](snippet) props like `children`, these should be typed using the `Snippet` interface imported from `'svelte'` — see [Typing snippets](snippet#Typing-snippets) for examples.\n\nAdding types is recommended, as it ensures that people using your component can easily discover which props they should provide.\n\n\n## `$props.id()`\n\nThis rune, added in version 5.20.0, generates an ID that is unique to the current component instance. When hydrating a server-rendered component, the value will be consistent between server and client.\n\nThis is useful for linking elements via attributes like `for` and `aria-labelledby`.\n\n```svelte\n<script>\n\tconst uid = $props.id();\n</script>\n\n<form>\n\t<label for=\"{uid}-firstname\">First Name: </label>\n\t<input id=\"{uid}-firstname\" type=\"text\" />\n\n\t<label for=\"{uid}-lastname\">Last Name: </label>\n\t<input id=\"{uid}-lastname\" type=\"text\" />\n</form>\n```","size_bytes":7021,"metadata":{"tags":"rune-props","title":"$props"},"created_at":"2025-07-18T15:47:38.910Z","updated_at":"2026-02-14T01:33:24.871Z"},{"path":"apps/svelte.dev/content/docs/svelte/02-runes/06-$bindable.md","title":"$bindable","filename":"06-$bindable.md","content":"Ordinarily, props go one way, from parent to child. This makes it easy to understand how data flows around your app.\n\nIn Svelte, component props can be _bound_, which means that data can also flow _up_ from child to parent. This isn't something you should do often — overuse can make your data flow unpredictable and your components harder to maintain — but it can simplify your code if used sparingly and carefully.\n\nIt also means that a state proxy can be _mutated_ in the child.\n\n\nTo mark a prop as bindable, we use the `$bindable` rune:\n\n```svelte\n/// file: FancyInput.svelte\n<script>\n\tlet { value = $bindable(), ...props } = $props();\n</script>\n\n<input bind:value={value} {...props} />\n\n<style>\n\tinput {\n\t\tfont-family: 'Comic Sans MS';\n\t\tcolor: deeppink;\n\t}\n</style>\n```\n\nNow, a component that uses `<FancyInput>` can add the [`bind:`](bind) directive ([demo](/playground/untitled#H4sIAAAAAAAAE3WQwWrDMBBEf2URBSfg2nfFMZRCoYeecqx6UJx1IyqvhLUONcb_XqSkTUOSk1az7DBvJtEai0HI90nw6FHIJIhckO7i78n7IhzQctS2OuAtvXHESByEFFVoeuO5VqTYdN71DC-amvGV_MDQ9q6DrCjP0skkWymKJxYZOgxBfyKs4SGwZlxke7TWZcuVoqo8-1P1z3lraCcP2g64nk4GM5S1osrXf0JV-lrkgvGbheR-wDm_g30V8JL-1vpOCZFogpQsEsWcemtxscyhKArfOx9gjps0Lq4hzRVfemaYfu-PoIqqwKPFY_XpaIqj4tYRP7a6M3aUkD27zjSw0RTgbZN6Z8WNs66XsEP03tBXUueUJFlelvYx_wCuI3leNwIAAA==)):\n\n```svelte\n/// file: App.svelte\n<script>\n\timport FancyInput from './FancyInput.svelte';\n\n\tlet message = $state('hello');\n</script>\n\n<FancyInput bind:value={message} />\n<p>{message}</p>\n```\n\nThe parent component doesn't _have_ to use `bind:` — it can just pass a normal prop. Some parents don't want to listen to what their children have to say.\n\nIn this case, you can specify a fallback value for when no prop is passed at all:\n\n```js\n/// file: FancyInput.svelte\nlet { value = $bindable('fallback'), ...props } = $props();\n```","size_bytes":1849,"metadata":{"title":"$bindable"},"created_at":"2025-07-18T15:47:38.914Z","updated_at":"2025-12-09T02:00:05.826Z"},{"path":"apps/svelte.dev/content/docs/svelte/02-runes/07-$inspect.md","title":"$inspect","filename":"07-$inspect.md","content":"The `$inspect` rune is roughly equivalent to `console.log`, with the exception that it will re-run whenever its argument changes. `$inspect` tracks reactive state deeply, meaning that updating something inside an object or array using fine-grained reactivity will cause it to re-fire ([demo](/playground/untitled#H4sIAAAAAAAACkWQ0YqDQAxFfyUMhSotdZ-tCvu431AXtGOqQ2NmmMm0LOK_r7Utfby5JzeXTOpiCIPKT5PidkSVq2_n1F7Jn3uIcEMSXHSw0evHpAjaGydVzbUQCmgbWaCETZBWMPlKj29nxBDaHj_edkAiu12JhdkYDg61JGvE_s2nR8gyuBuiJZuDJTyQ7eE-IEOzog1YD80Lb0APLfdYc5F9qnFxjiKWwbImo6_llKRQVs-2u91c_bD2OCJLkT3JZasw7KLA2XCX31qKWE6vIzNk1fKE0XbmYrBTufiI8-_8D2cUWBA_AQAA)):\n\n```svelte\n<script>\n\tlet count = $state(0);\n\tlet message = $state('hello');\n\n\t$inspect(count, message); // will console.log when `count` or `message` change\n</script>\n\n<button onclick={() => count++}>Increment</button>\n<input bind:value={message} />\n```\n\nOn updates, a stack trace will be printed, making it easy to find the origin of a state change (unless you're in the playground, due to technical limitations).\n\n## $inspect(...).with\n\n`$inspect` returns a property `with`, which you can invoke with a callback, which will then be invoked instead of `console.log`. The first argument to the callback is either `\"init\"` or `\"update\"`; subsequent arguments are the values passed to `$inspect` ([demo](/playground/untitled#H4sIAAAAAAAACkVQ24qDMBD9lSEUqlTqPlsj7ON-w7pQG8c2VCchmVSK-O-bKMs-DefKYRYx6BG9qL4XQd2EohKf1opC8Nsm4F84MkbsTXAqMbVXTltuWmp5RAZlAjFIOHjuGLOP_BKVqB00eYuKs82Qn2fNjyxLtcWeyUE2sCRry3qATQIpJRyD7WPVMf9TW-7xFu53dBcoSzAOrsqQNyOe2XUKr0Xi5kcMvdDB2wSYO-I9vKazplV1-T-d6ltgNgSG1KjVUy7ZtmdbdjqtzRcphxMS1-XubOITJtPrQWMvKnYB15_1F7KKadA_AQAA)):\n\n```svelte\n<script>\n\tlet count = $state(0);\n\n\t$inspect(count).with((type, count) => {\n\t\tif (type === 'update') {\n\t\t\tdebugger; // or `console.trace`, or whatever you want\n\t\t}\n\t});\n</script>\n\n<button onclick={() => count++}>Increment</button>\n```\n\n## $inspect.trace(...)\n\nThis rune, added in 5.14, causes the surrounding function to be _traced_ in development. Any time the function re-runs as part of an [effect]($effect) or a [derived]($derived), information will be printed to the console about which pieces of reactive state caused the effect to fire.\n\n```svelte\n<script>\n\timport { doSomeWork } from './elsewhere';\n\n\t$effect(() => {\n\t\t// $inspect.trace must be the first statement of a function body\n\t\t$inspect.trace();\n\t\tdoSomeWork();\n\t});\n</script>\n```\n\n`$inspect.trace` takes an optional first argument which will be used as the label.","size_bytes":2566,"metadata":{"tags":"rune-inspect","title":"$inspect"},"created_at":"2025-07-18T15:47:38.914Z","updated_at":"2026-02-14T01:33:24.872Z"},{"path":"apps/svelte.dev/content/docs/svelte/02-runes/08-$host.md","title":"$host","filename":"08-$host.md","content":"When compiling a component as a [custom element](custom-elements), the `$host` rune provides access to the host element, allowing you to (for example) dispatch custom events ([demo](/playground/untitled#H4sIAAAAAAAAE41Ry2rDMBD8FSECtqkTt1fHFpSSL-ix7sFRNkTEXglrnTYY_3uRlDgxTaEHIfYxs7szA9-rBizPPwZOZwM89wmecqxbF70as7InaMjltrWFR3mpkQDJ8pwXVnbKkKiwItUa3RGLVtk7gTHQXRDR2lXda4CY1D0SK9nCUk0QPyfrCovsRoNFe17aQOAwGncgO2gBqRzihJXiQrEs2csYOhQ-7HgKHaLIbpRhhBG-I2eD_8ciM4KnnOCbeE5dD2P6h0Dz0-Yi_arNhPLJXBtSGi2TvSXdbpqwdsXvjuYsC1veabvvUTog2ylrapKH2G2XsMFLS4uDthQnq2t1cwKkGOGLvYU5PvaQxLsxOkPmsm97Io1Mo2yUPF6VnOZFkw1RMoopKLKAE_9gmGxyDFMwMcwN-Bx_ABXQWmOtAgAA)):\n\n```svelte\n/// file: Stepper.svelte\n<svelte:options customElement=\"my-stepper\" />\n\n<script>\n\tfunction dispatch(type) {\n\t\t$host().dispatchEvent(new CustomEvent(type));\n\t}\n</script>\n\n<button onclick={() => dispatch('decrement')}>decrement</button>\n<button onclick={() => dispatch('increment')}>increment</button>\n```\n\n```svelte\n/// file: App.svelte\n<script>\n\timport './Stepper.svelte';\n\n\tlet count = $state(0);\n</script>\n\n<my-stepper\n\tondecrement={() => count -= 1}\n\tonincrement={() => count += 1}\n></my-stepper>\n\n<p>count: {count}</p>\n```","size_bytes":1203,"metadata":{"title":"$host"},"created_at":"2025-07-18T15:47:38.916Z","updated_at":"2025-07-18T15:47:40.212Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/01-basic-markup.md","title":"Basic markup","filename":"01-basic-markup.md","content":"Markup inside a Svelte component can be thought of as HTML++.\n\n## Tags\n\nA lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag or a tag that uses dot notation, such as `<Widget>` or `<my.stuff>`, indicates a _component_.\n\n```svelte\n<script>\n\timport Widget from './Widget.svelte';\n</script>\n\n<div>\n\t<Widget />\n</div>\n```\n\n## Element attributes\n\nBy default, attributes work exactly like their HTML counterparts.\n\n```svelte\n<div class=\"foo\">\n\t<button disabled>can't touch this</button>\n</div>\n```\n\nAs in HTML, values may be unquoted.\n\n```svelte\n<input type=checkbox />\n```\n\nAttribute values can contain JavaScript expressions.\n\n```svelte\n<a href=\"page/{p}\">page {p}</a>\n```\n\nOr they can _be_ JavaScript expressions.\n\n```svelte\n<button disabled={!clickable}>...</button>\n```\n\nBoolean attributes are included on the element if their value is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and excluded if it's [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).\n\nAll other attributes are included unless their value is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`).\n\n```svelte\n<input required={false} placeholder=\"This input field is not required\" />\n<div title={null}>This div has no title attribute</div>\n```\n\n>\n> <!-- prettier-ignore -->\n> ```svelte\n> <button disabled=\"{number !== 42}\">...</button>\n> ```\n\nWhen the attribute name and value match (`name={name}`), they can be replaced with `{name}`.\n\n```svelte\n<button {disabled}>...</button>\n<!-- equivalent to\n<button disabled={disabled}>...</button>\n-->\n```\n\n## Component props\n\nBy convention, values passed to components are referred to as _properties_ or _props_ rather than _attributes_, which are a feature of the DOM.\n\nAs with elements, `name={name}` can be replaced with the `{name}` shorthand.\n\n```svelte\n<Widget foo={bar} answer={42} text=\"hello\" />\n```\n\n## Spread attributes\n\n_Spread attributes_ allow many attributes or properties to be passed to an element or component at once.\n\nAn element or component can have multiple spread attributes, interspersed with regular ones. Order matters — if `things.a` exists it will take precedence over `a=\"b\"`, while `c=\"d\"` would take precedence over `things.c`:\n\n```svelte\n<Widget a=\"b\" {...things} c=\"d\" />\n```\n\n## Events\n\nListening to DOM events is possible by adding attributes to the element that start with `on`. For example, to listen to the `click` event, add the `onclick` attribute to a button:\n\n```svelte\n<button onclick={() => console.log('clicked')}>click me</button>\n```\n\nEvent attributes are case sensitive. `onclick` listens to the `click` event, `onClick` listens to the `Click` event, which is different. This ensures you can listen to custom events that have uppercase characters in them.\n\nBecause events are just attributes, the same rules as for attributes apply:\n\n- you can use the shorthand form: `<button {onclick}>click me</button>`\n- you can spread them: `<button {...thisSpreadContainsEventAttributes}>click me</button>`\n\nTiming-wise, event attributes always fire after events from bindings (e.g. `oninput` always fires after an update to `bind:value`). Under the hood, some event handlers are attached directly with `addEventListener`, while others are _delegated_.\n\nWhen using `ontouchstart` and `ontouchmove` event attributes, the handlers are [passive](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#using_passive_listeners) for better performance. This greatly improves responsiveness by allowing the browser to scroll the document immediately, rather than waiting to see if the event handler calls `event.preventDefault()`.\n\nIn the very rare cases that you need to prevent these event defaults, you should use [`on`](svelte-events#on) instead (for example inside an action).\n\n### Event delegation\n\nTo reduce memory footprint and increase performance, Svelte uses a technique called event delegation. This means that for certain events — see the list below — a single event listener at the application root takes responsibility for running any handlers on the event's path.\n\nThere are a few gotchas to be aware of:\n\n- when you manually dispatch an event with a delegated listener, make sure to set the `{ bubbles: true }` option or it won't reach the application root\n- when using `addEventListener` directly, avoid calling `stopPropagation` or the event won't reach the application root and handlers won't be invoked. Similarly, handlers added manually inside the application root will run _before_ handlers added declaratively deeper in the DOM (with e.g. `onclick={...}`), in both capturing and bubbling phases. For these reasons it's better to use the `on` function imported from `svelte/events` rather than `addEventListener`, as it will ensure that order is preserved and `stopPropagation` is handled correctly.\n\nThe following event handlers are delegated:\n\n- `beforeinput`\n- `click`\n- `change`\n- `dblclick`\n- `contextmenu`\n- `focusin`\n- `focusout`\n- `input`\n- `keydown`\n- `keyup`\n- `mousedown`\n- `mousemove`\n- `mouseout`\n- `mouseover`\n- `mouseup`\n- `pointerdown`\n- `pointermove`\n- `pointerout`\n- `pointerover`\n- `pointerup`\n- `touchend`\n- `touchmove`\n- `touchstart`\n\n## Text expressions\n\nA JavaScript expression can be included as text by surrounding it with curly braces.\n\n```svelte\n{expression}\n```\n\nExpressions that are `null` or `undefined` will be omitted; all others are [coerced to strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion).\n\nCurly braces can be included in a Svelte template by using their [HTML entity](https://developer.mozilla.org/docs/Glossary/Entity) strings: `&lbrace;`, `&lcub;`, or `&#123;` for `{` and `&rbrace;`, `&rcub;`, or `&#125;` for `}`.\n\nIf you're using a regular expression (`RegExp`) [literal notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#literal_notation_and_constructor), you'll need to wrap it in parentheses.\n\n```svelte\n<h1>Hello {name}!</h1>\n<p>{a} + {b} = {a + b}.</p>\n\n<div>{(/^[A-Za-z ]+$/).test(value) ? x : y}</div>\n```\n\nThe expression will be stringified and escaped to prevent code injections. If you want to render HTML, use the `{@html}` tag instead.\n\n```svelte\n{@html potentiallyUnsafeHtmlString}\n```\n\n\n## Comments\n\nYou can use HTML comments inside components.\n\n```svelte\n<!-- this is a comment! --><h1>Hello world</h1>\n```\n\nComments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually, these are accessibility warnings; make sure that you're disabling them for a good reason.\n\n```svelte\n<!-- svelte-ignore a11y_autofocus -->\n<input bind:value={name} autofocus />\n```\n\nYou can add a special comment starting with `@component` that will show up when hovering over the component name in other files.\n\n````svelte\n<!--\n@component\nYou can use markdown here.\nYou can also use code blocks here.\nUsage:\n  ```html\n  <Main name=\"Arethra\">\n  ```\n-->\n<script>\n\tlet { name } = $props();\n</script>\n\n<main>\n\t<h1>\n\t\tHello, {name}\n\t</h1>\n</main>\n````","size_bytes":7146,"metadata":{"title":"Basic markup"},"created_at":"2025-07-18T15:47:38.929Z","updated_at":"2025-07-18T15:47:40.215Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/02-if.md","title":"{#if ...}","filename":"02-if.md","content":"```svelte\n<!copy: false>\n{#if expression}...{/if}\n```\n\n```svelte\n<!copy: false>\n{#if expression}...{:else if expression}...{/if}\n```\n\n```svelte\n<!copy: false>\n{#if expression}...{:else}...{/if}\n```\n\nContent that is conditionally rendered can be wrapped in an if block.\n\n```svelte\n{#if answer === 42}\n\t<p>what was the question?</p>\n{/if}\n```\n\nAdditional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause.\n\n```svelte\n{#if porridge.temperature > 100}\n\t<p>too hot!</p>\n{:else if 80 > porridge.temperature}\n\t<p>too cold!</p>\n{:else}\n\t<p>just right!</p>\n{/if}\n```\n\n(Blocks don't have to wrap elements, they can also wrap text within elements.)","size_bytes":727,"metadata":{"tags":"template-if","title":"{#if ...}"},"created_at":"2025-07-18T15:47:38.931Z","updated_at":"2026-02-14T01:33:24.873Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/03-each.md","title":"{#each ...}","filename":"03-each.md","content":"```svelte\n<!copy: false>\n{#each expression as name}...{/each}\n```\n\n```svelte\n<!copy: false>\n{#each expression as name, index}...{/each}\n```\n\nIterating over values can be done with an each block. The values in question can be arrays, array-like objects (i.e. anything with a `length` property), or iterables like `Map` and `Set`. (Internally, they are converted to arrays with [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from).)\n\nIf the value is `null` or `undefined`, it is treated the same as an empty array (which will cause [else blocks](#Else-blocks) to be rendered, where applicable).\n\n```svelte\n<h1>Shopping list</h1>\n<ul>\n\t{#each items as item}\n\t\t<li>{item.name} x {item.qty}</li>\n\t{/each}\n</ul>\n```\n\nAn each block can also specify an _index_, equivalent to the second argument in an `array.map(...)` callback:\n\n```svelte\n{#each items as item, i}\n\t<li>{i + 1}: {item.name} x {item.qty}</li>\n{/each}\n```\n\n## Keyed each blocks\n\n```svelte\n<!copy: false>\n{#each expression as name (key)}...{/each}\n```\n\n```svelte\n<!copy: false>\n{#each expression as name, index (key)}...{/each}\n```\n\nIf a _key_ expression is provided — which must uniquely identify each list item — Svelte will use it to intelligently update the list when data changes by inserting, moving and deleting items, rather than adding or removing items at the end and updating the state in the middle.\n\nThe key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.\n\n```svelte\n{#each items as item (item.id)}\n\t<li>{item.name} x {item.qty}</li>\n{/each}\n\n<!-- or with additional index value -->\n{#each items as item, i (item.id)}\n\t<li>{i + 1}: {item.name} x {item.qty}</li>\n{/each}\n```\n\nYou can freely use destructuring and rest patterns in each blocks.\n\n```svelte\n{#each items as { id, name, qty }, i (id)}\n\t<li>{i + 1}: {name} x {qty}</li>\n{/each}\n\n{#each objects as { id, ...rest }}\n\t<li><span>{id}</span><MyComponent {...rest} /></li>\n{/each}\n\n{#each items as [id, ...rest]}\n\t<li><span>{id}</span><MyComponent values={rest} /></li>\n{/each}\n```\n\n## Each blocks without an item\n\n```svelte\n<!copy: false>\n{#each expression}...{/each}\n```\n\n```svelte\n<!copy: false>\n{#each expression, index}...{/each}\n```\n\nIn case you just want to render something `n` times, you can omit the `as` part ([demo](/playground/untitled#H4sIAAAAAAAAE3WR0W7CMAxFf8XKNAk0WsSeUEaRpn3Guoc0MbQiJFHiMlDVf18SOrZJ48259_jaVgZmxBEZZ28thgCNFV6xBdt1GgPj7wOji0t2EqI-wa_OleGEmpLWiID_6dIaQkMxhm1UdwKpRQhVzWSaVORJNdvWpqbhAYVsYQCNZk8thzWMC_DCHMZk3wPSThNQ088I3mghD9UwSwHwlLE5PMIzVFUFq3G7WUZ2OyUvU3JOuZU332wCXTRmtPy1NgzXZtUFp8WFw9536uWqpbIgPEaDsJBW90cTOHh0KGi2XsBq5-cT6-3nPauxXqHnsHJnCFZ3CvJVkyuCQ0mFF9TZyCQ162WGvteLKfG197Y3iv_pz_fmS68Hxt8iPBPj5HscP8YvCNX7uhYCAAA=)):\n\n```svelte\n<div class=\"chess-board\">\n\t{#each { length: 8 }, rank}\n\t\t{#each { length: 8 }, file}\n\t\t\t<div class:black={(rank + file) % 2 === 1}></div>\n\t\t{/each}\n\t{/each}\n</div>\n```\n\n## Else blocks\n\n```svelte\n<!copy: false>\n{#each expression as name}...{:else}...{/each}\n```\n\nAn each block can also have an `{:else}` clause, which is rendered if the list is empty.\n\n```svelte\n{#each todos as todo}\n\t<p>{todo.text}</p>\n{:else}\n\t<p>No tasks today!</p>\n{/each}\n```","size_bytes":3334,"metadata":{"tags":"template-each","title":"{#each ...}"},"created_at":"2025-07-18T15:47:38.932Z","updated_at":"2026-02-14T01:33:24.874Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/04-key.md","title":"{#key ...}","filename":"04-key.md","content":"```svelte\n<!copy: false>\n{#key expression}...{/key}\n```\n\nKey blocks destroy and recreate their contents when the value of an expression changes. When used around components, this will cause them to be reinstantiated and reinitialised:\n\n```svelte\n{#key value}\n\t<Component />\n{/key}\n```\n\nIt's also useful if you want a transition to play whenever a value changes:\n\n```svelte\n{#key value}\n\t<div transition:fade>{value}</div>\n{/key}\n```","size_bytes":479,"metadata":{"tags":"template-key","title":"{#key ...}"},"created_at":"2025-07-18T15:47:38.934Z","updated_at":"2026-02-14T01:33:24.873Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/05-await.md","title":"{#await ...}","filename":"05-await.md","content":"```svelte\n<!copy: false>\n{#await expression}...{:then name}...{:catch name}...{/await}\n```\n\n```svelte\n<!copy: false>\n{#await expression}...{:then name}...{/await}\n```\n\n```svelte\n<!copy: false>\n{#await expression then name}...{/await}\n```\n\n```svelte\n<!copy: false>\n{#await expression catch name}...{/await}\n```\n\nAwait blocks allow you to branch on the three possible states of a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — pending, fulfilled or rejected.\n\n```svelte\n{#await promise}\n\t<!-- promise is pending -->\n\t<p>waiting for the promise to resolve...</p>\n{:then value}\n\t<!-- promise was fulfilled or not a Promise -->\n\t<p>The value is {value}</p>\n{:catch error}\n\t<!-- promise was rejected -->\n\t<p>Something went wrong: {error.message}</p>\n{/await}\n```\n\n>\n> If the provided expression is not a `Promise`, only the `:then` branch will be rendered, including during server-side rendering.\n\nThe `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible).\n\n```svelte\n{#await promise}\n\t<!-- promise is pending -->\n\t<p>waiting for the promise to resolve...</p>\n{:then value}\n\t<!-- promise was fulfilled -->\n\t<p>The value is {value}</p>\n{/await}\n```\n\nIf you don't care about the pending state, you can also omit the initial block.\n\n```svelte\n{#await promise then value}\n\t<p>The value is {value}</p>\n{/await}\n```\n\nSimilarly, if you only want to show the error state, you can omit the `then` block.\n\n```svelte\n{#await promise catch error}\n\t<p>The error is {error}</p>\n{/await}\n```\n\n>\n> ```svelte\n> {#await import('./Component.svelte') then { default: Component }}\n> \t<Component />\n> {/await}\n> ```","size_bytes":1760,"metadata":{"tags":"template-await","title":"{#await ...}"},"created_at":"2025-07-18T15:47:38.942Z","updated_at":"2026-02-14T01:33:24.874Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/06-snippet.md","title":"{#snippet ...}","filename":"06-snippet.md","content":"```svelte\n<!copy: false>\n{#snippet name()}...{/snippet}\n```\n\n```svelte\n<!copy: false>\n{#snippet name(param1, param2, paramN)}...{/snippet}\n```\n\nSnippets, and [render tags](@render), are a way to create reusable chunks of markup inside your components. Instead of writing duplicative code like [this](/playground/untitled#H4sIAAAAAAAAE5VUYW-kIBD9K8Tmsm2yXXRzvQ-s3eR-R-0HqqOQKhAZb9sz_vdDkV1t000vRmHewMx7w2AflbIGG7GnPlK8gYhFv42JthG-m9Gwf6BGcLbVXZuPSGrzVho8ZirDGpDIhldgySN5GpEMez9kaNuckY1ANJZRamRuu2ZnhEZt6a84pvs43mzD4pMsUDDi8DMkQFYCGdkvsJwblFq5uCik9bmJ4JZwUkv1eoknWigX2eGNN6aGXa6bjV8ybP-X7sM36T58SVcrIIV2xVIaA41xeD5kKqWXuqpUJEefOqVuOkL9DfBchGrzWfu0vb-RpTd3o-zBR045Ga3HfuE5BmJpKauuhbPtENlUF2sqR9jqpsPSxWsMrlngyj3VJiyYjJXb1-lMa7IWC-iSk2M5Zzh-SJjShe-siq5kpZRPs55BbSGU5YPyte4vVV_VfFXxVb10dSLf17pS2lM5HnpPxw4Zpv6x-F57p0jI3OKlVnhv5V9wPQrNYQQ9D_f6aGHlC89fq1Z3qmDkJCTCweOGF4VUFSPJvD_DhreVdA0eu8ehJJ5x91dBaBkpWm3ureCFPt3uzRv56d4kdp-2euG38XZ6dsnd3ZmPG9yRBCrzRUvi-MccOdwz3qE-fOZ7AwAhlrtTUx3c76vRhSwlFBHDtoPhefgHX3dM0PkEAAA=)...\n\n```svelte\n{#each images as image}\n\t{#if image.href}\n\t\t<a href={image.href}>\n\t\t\t<figure>\n\t\t\t\t<img src={image.src} alt={image.caption} width={image.width} height={image.height} />\n\t\t\t\t<figcaption>{image.caption}</figcaption>\n\t\t\t</figure>\n\t\t</a>\n\t{:else}\n\t\t<figure>\n\t\t\t<img src={image.src} alt={image.caption} width={image.width} height={image.height} />\n\t\t\t<figcaption>{image.caption}</figcaption>\n\t\t</figure>\n\t{/if}\n{/each}\n```\n\n...you can write [this](/playground/untitled#H4sIAAAAAAAAE5VUYW-bMBD9KxbRlERKY4jWfSA02n5H6QcXDmwVbMs-lnaI_z6D7TTt1moTAnPvzvfenQ_GpBEd2CS_HxPJekjy5IfWyS7BFz0b9id0CM62ajDVjBS2MkLjqZQldoBE9KwFS-7I_YyUOPqlRGuqnKw5orY5pVpUduj3mitUln5LU3pI0_UuBp9FjTwnDr9AHETLMSeHK6xiGoWSLi9yYT034cwSRjohn17zcQPNFTs8s153sK9Uv_Yh0-5_5d7-o9zbD-UqCaRWrllSYZQxLw_HUhb0ta-y4NnJUxfUvc7QuLJSaO0a3oh2MLBZat8u-wsPnXzKQvTtVVF34xK5d69ThFmHEQ4SpzeVRediTG8rjD5vBSeN3E5JyHh6R1DQK9-iml5kjzQUN_lSgVU8DhYLx7wwjSvRkMDvTjiwF4zM1kXZ7DlF1eN3A7IG85e-zRrYEjjm0FkI4Cc7Ripm0pHOChexhcWXzreeZyRMU6Mk3ljxC9w4QH-cQZ_b3T5pjHxk1VNr1CDrnJy5QDh6XLO6FrLNSRb2l9gz0wo3S6m7HErSgLsPGMHkpDZK31jOanXeHPQz-eruLHUP0z6yTbpbrn223V70uMXNSpQSZjpL0y8hcxxpNqA6_ql3BQAxlxvfpQ_uT9GrWjQC6iRHM8D0MP0GQsIi92QEAAA=):\n\n```svelte\n{#snippet figure(image)}\n\t<figure>\n\t\t<img src={image.src} alt={image.caption} width={image.width} height={image.height} />\n\t\t<figcaption>{image.caption}</figcaption>\n\t</figure>\n{/snippet}\n\n{#each images as image}\n\t{#if image.href}\n\t\t<a href={image.href}>\n\t\t\t{@render figure(image)}\n\t\t</a>\n\t{:else}\n\t\t{@render figure(image)}\n\t{/if}\n{/each}\n```\n\nLike function declarations, snippets can have an arbitrary number of parameters, which can have default values, and you can destructure each parameter. You cannot use rest parameters, however.\n\n## Snippet scope\n\nSnippets can be declared anywhere inside your component. They can reference values declared outside themselves, for example in the `<script>` tag or in `{#each ...}` blocks ([demo](/playground/untitled#H4sIAAAAAAAAE12P0QrCMAxFfyWrwhSEvc8p-h1OcG5RC10bmkyQ0n-3HQPBx3vCPUmCemiDrOpLULYbUdXqTKR2Sj6UA7_RCKbMbvJ9Jg33XpMcW9uKQYEAIzJ3T4QD3LSUDE-PnYA4YET4uOkGMc3W5B3xZrtvbVP9HDas2GqiZHqhMW6Tr9jGbG_oOCMImcUCwrIpFk1FqRyqpRpn0cmjHdAvnrIzuscyq_4nd3dPPD01ukE_NA6qFj9hvMYvGjJADw8BAAA=))...\n\n```svelte\n<script>\n\tlet { message = `it's great to see you!` } = $props();\n</script>\n\n{#snippet hello(name)}\n\t<p>hello {name}! {message}!</p>\n{/snippet}\n\n{@render hello('alice')}\n{@render hello('bob')}\n```\n\n...and they are 'visible' to everything in the same lexical scope (i.e. siblings, and children of those siblings):\n\n```svelte\n<div>\n\t{#snippet x()}\n\t\t{#snippet y()}...{/snippet}\n\n\t\t<!-- this is fine -->\n\t\t{@render y()}\n\t{/snippet}\n\n\t<!-- this will error, as `y` is not in scope -->\n\t{@render y()}\n</div>\n\n<!-- this will also error, as `x` is not in scope -->\n{@render x()}\n```\n\nSnippets can reference themselves and each other ([demo](/playground/untitled#H4sIAAAAAAAAE2WPTQqDMBCFrxLiRqH1Zysi7TlqF1YnENBJSGJLCYGeo5tesUeosfYH3c2bee_jjaWMd6BpfrAU6x5oTvdS0g01V-mFPkNnYNRaDKrxGxto5FKCIaeu1kYwFkauwsoUWtZYPh_3W5FMY4U2mb3egL9kIwY0rbhgiO-sDTgjSEqSTvIDs-jiOP7i_MHuFGAL6p9BtiSbOTl0GtzCuihqE87cqtyam6WRGz_vRcsZh5bmRg3gju4Fptq_kzQBAAA=)):\n\n```svelte\n{#snippet blastoff()}\n\t<span>🚀</span>\n{/snippet}\n\n{#snippet countdown(n)}\n\t{#if n > 0}\n\t\t<span>{n}...</span>\n\t\t{@render countdown(n - 1)}\n\t{:else}\n\t\t{@render blastoff()}\n\t{/if}\n{/snippet}\n\n{@render countdown(10)}\n```\n\n## Passing snippets to components\n\n### Explicit props\n\nWithin the template, snippets are values just like any other. As such, they can be passed to components as props ([demo](/playground/untitled#H4sIAAAAAAAAE3VS247aMBD9lZGpBGwDASRegonaPvQL2qdlH5zYEKvBNvbQLbL875VzAcKyj3PmzJnLGU8UOwqSkd8KJdaCk4TsZS0cyV49wYuJuQiQpGd-N2bu_ooaI1YwJ57hpVYoFDqSEepKKw3mO7VDeTTaIvxiRS1gb_URxvO0ibrS8WanIrHUyiHs7Vmigy28RmyHHmKvDMbMmFq4cQInvGSwTsBYWYoMVhCSB2rBFFPsyl0uruTlR3JZCWvlTXl1Yy_mawiR_rbZKZrellJ-5JQ0RiBUgnFhJ9OGR7HKmwVoilXeIye8DOJGfYCgRlZ3iE876TBsZPX7hPdteO75PC4QaIo8vwNPePmANQ2fMeEFHrLD7rR1jTNkW986E8C3KwfwVr8HSHOSEBT_kGRozyIkn_zQveXDL3rIfPJHtUDwzShJd_Qk3gQCbOGLsdq4yfTRJopRuin3I7nv6kL7ARRjmLdBDG3uv1mhuLA3V2mKtqNEf_oCn8p9aN-WYqH5peP4kWBl1UwJzAEPT9U7K--0fRrrWnPTXpCm1_EVdXjpNmlA8G1hPPyM1fKgMqjFHjctXGjLhZ05w0qpDhksGrybuNEHtJnCalZWsuaTlfq6nPaaBSv_HKw-K57BjzOiVj9ZKQYKzQjZodYFqydYTRN4gPhVzTDO2xnma3HsVWjaLjT8nbfwHy7Q5f2dBAAA)):\n\n```svelte\n<script>\n\timport Table from './Table.svelte';\n\n\tconst fruits = [\n\t\t{ name: 'apples', qty: 5, price: 2 },\n\t\t{ name: 'bananas', qty: 10, price: 1 },\n\t\t{ name: 'cherries', qty: 20, price: 0.5 }\n\t];\n</script>\n\n{#snippet header()}\n\t<th>fruit</th>\n\t<th>qty</th>\n\t<th>price</th>\n\t<th>total</th>\n{/snippet}\n\n{#snippet row(d)}\n\t<td>{d.name}</td>\n\t<td>{d.qty}</td>\n\t<td>{d.price}</td>\n\t<td>{d.qty * d.price}</td>\n{/snippet}\n\n<Table data={fruits} {header} {row} />\n```\n\nThink about it like passing content instead of data to a component. The concept is similar to slots in web components.\n\n### Implicit props\n\nAs an authoring convenience, snippets declared directly _inside_ a component implicitly become props _on_ the component ([demo](/playground/untitled#H4sIAAAAAAAAE3VSTa_aMBD8Kyu_SkAbCA-JSzBR20N_QXt6vIMTO8SqsY29tI2s_PcqTiB8vaPHs7MzuxuIZgdBMvJLo0QlOElIJZXwJHsLBBvb_XUASc7Mb9Yu_B-hsMMK5sUzvDQahUZPMkJ96aTFfKd3KA_WOISfrFACKmcOMFmk8TWUTjY73RFLoz1C5U4SPWzhrcN2GKDrlcGEWauEnyRwxCaDdQLWyVJksII2uaMWTDPNLtzX5YX8-kgua-GcHJVXI3u5WEPb0d83O03TMZSmfRzOkG1Db7mNacOL19JagVALxoWbztq-H8U6j0SaYp2P2BGbOyQ2v8PQIFMXLKRDk177pq0zf6d8bMrzwBdd0pamyPMb-IjNEzS2f86Gz_Dwf-2F9nvNSUJQ_EOSoTuJNvngqK5v4Pas7n4-OCwlEEJcQTIMO-nSQwtb-GSdsX46e9gbRoP9yGQ11I0rEuycunu6PHx1QnPhxm3SFN15MOlYEFJZtf0dUywMbwZOeBGsrKNLYB54-1R9WNqVdki7usim6VmQphf7mnpshiQRhNAXdoOfMyX3OgMlKtz0cGEcF27uLSul3mewjPjgOOoDukxjPS9rqfh0pb-8zs6aBSt_7505aZ7B9xOi0T9YKW4UooVsr0zB1BTrWQJ3EL-oWcZ572GxFoezCk37QLe3897-B2i2U62uBAAA)):\n\n```svelte\n<!-- this is semantically the same as the above -->\n<Table data={fruits}>\n\t{#snippet header()}\n\t\t<th>fruit</th>\n\t\t<th>qty</th>\n\t\t<th>price</th>\n\t\t<th>total</th>\n\t{/snippet}\n\n\t{#snippet row(d)}\n\t\t<td>{d.name}</td>\n\t\t<td>{d.qty}</td>\n\t\t<td>{d.price}</td>\n\t\t<td>{d.qty * d.price}</td>\n\t{/snippet}\n</Table>\n```\n\n### Implicit `children` snippet\n\nAny content inside the component tags that is _not_ a snippet declaration implicitly becomes part of the `children` snippet ([demo](/playground/untitled#H4sIAAAAAAAAE3WOQQrCMBBFrzIMggql3ddY1Du4si5sOmIwnYRkFKX07lKqglqX8_7_w2uRDw1hjlsWI5ZqTPBoLEXMdy3K3fdZDzB5Ndfep_FKVnpWHSKNce1YiCVijirqYLwUJQOYxrsgsLmIOIZjcA1M02w4n-PpomSVvTclqyEutDX6DA2pZ7_ABIVugrmEC3XJH92P55_G39GodCmWBFrQJ2PrQAwdLGHig_NxNv9xrQa1dhWIawrv1Wzeqawa8953D-8QOmaEAQAA)):\n\n```svelte\n<!file: App.svelte>\n<Button>click me</Button>\n```\n\n```svelte\n<!file: Button.svelte>\n<script>\n\tlet { children } = $props();\n</script>\n\n<!-- result will be <button>click me</button> -->\n<button>{@render children()}</button>\n```\n\n\n### Optional snippet props\n\nYou can declare snippet props as being optional. You can either use optional chaining to not render anything if the snippet isn't set...\n\n```svelte\n<script>\n    let { children } = $props();\n</script>\n\n{@render children?.()}\n```\n\n...or use an `#if` block to render fallback content:\n\n```svelte\n<script>\n    let { children } = $props();\n</script>\n\n{#if children}\n    {@render children()}\n{:else}\n    fallback content\n{/if}\n```\n\n## Typing snippets\n\nSnippets implement the `Snippet` interface imported from `'svelte'`:\n\n```svelte\n<script lang=\"ts\">\n\timport type { Snippet } from 'svelte';\n\n\tinterface Props {\n\t\tdata: any[];\n\t\tchildren: Snippet;\n\t\trow: Snippet<[any]>;\n\t}\n\n\tlet { data, children, row }: Props = $props();\n</script>\n```\n\nWith this change, red squigglies will appear if you try and use the component without providing a `data` prop and a `row` snippet. Notice that the type argument provided to `Snippet` is a tuple, since snippets can have multiple parameters.\n\nWe can tighten things up further by declaring a generic, so that `data` and `row` refer to the same type:\n\n```svelte\n<script lang=\"ts\" generics=\"T\">\n\timport type { Snippet } from 'svelte';\n\n\tlet {\n\t\tdata,\n\t\tchildren,\n\t\trow\n\t}: {\n\t\tdata: T[];\n\t\tchildren: Snippet;\n\t\trow: Snippet<[T]>;\n\t} = $props();\n</script>\n```\n\n## Exporting snippets\n\nSnippets declared at the top level of a `.svelte` file can be exported from a `<script module>` for use in other components, provided they don't reference any declarations in a non-module `<script>` (whether directly or indirectly, via other snippets) ([demo](/playground/untitled#H4sIAAAAAAAAE3WPwY7CMAxEf8UyB1hRgdhjl13Bga8gHFJipEqtGyUGFUX5dxJUtEB3b9bYM_MckHVLWOKut50TMuC5tpbEY4GnuiGP5T6gXG0-ykLSB8vW2oW_UCNZq7Snv_Rjx0Kc4kpc-6OrrfwoVlK3uQ4CaGMgwsl1LUwXy0f54J9-KV4vf20cNo7YkMu22aqAz4-oOLUI9YKluDPF4h_at-hX5PFyzA1tZ84N3fGpf8YfUU6GvDumLqDKmEqCjjCHUEX4hqDTWCU5PJ6Or38c4g1cPu9tnAEAAA==)):\n\n```svelte\n<script module>\n\texport { add };\n</script>\n\n{#snippet add(a, b)}\n\t{a} + {b} = {a + b}\n{/snippet}\n```\n\n> This requires Svelte 5.5.0 or newer\n\n## Programmatic snippets\n\nSnippets can be created programmatically with the [`createRawSnippet`](svelte#createRawSnippet) API. This is intended for advanced use cases.\n\n## Snippets and slots\n\nIn Svelte 4, content can be passed to components using [slots](legacy-slots). Snippets are more powerful and flexible, and so slots have been deprecated in Svelte 5.","size_bytes":10261,"metadata":{"title":"{#snippet ...}"},"created_at":"2025-07-18T15:47:38.944Z","updated_at":"2025-08-06T14:00:06.375Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/07-@render.md","title":"{@render ...}","filename":"07-@render.md","content":"To render a [snippet](snippet), use a `{@render ...}` tag.\n\n```svelte\n{#snippet sum(a, b)}\n\t<p>{a} + {b} = {a + b}</p>\n{/snippet}\n\n{@render sum(1, 2)}\n{@render sum(3, 4)}\n{@render sum(5, 6)}\n```\n\nThe expression can be an identifier like `sum`, or an arbitrary JavaScript expression:\n\n```svelte\n{@render (cool ? coolSnippet : lameSnippet)()}\n```\n\n## Optional snippets\n\nIf the snippet is potentially undefined — for example, because it's an incoming prop — then you can use optional chaining to only render it when it _is_ defined:\n\n```svelte\n{@render children?.()}\n```\n\nAlternatively, use an [`{#if ...}`](if) block with an `:else` clause to render fallback content:\n\n```svelte\n{#if children}\n\t{@render children()}\n{:else}\n\t<p>fallback content</p>\n{/if}\n```","size_bytes":791,"metadata":{"title":"{@render ...}"},"created_at":"2025-07-18T15:47:38.945Z","updated_at":"2025-07-18T15:47:40.225Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/08-@html.md","title":"{@html ...}","filename":"08-@html.md","content":"To inject raw HTML into your component, use the `{@html ...}` tag:\n\n```svelte\n<article>\n\t{@html content}\n</article>\n```\n\n\nThe expression should be valid standalone HTML — this will not work, because `</div>` is not valid HTML:\n\n```svelte\n{@html '<div>'}content{@html '</div>'}\n```\n\nIt also will not compile Svelte code.\n\n## Styling\n\nContent rendered this way is 'invisible' to Svelte and as such will not receive [scoped styles](scoped-styles). In other words, this will not work, and the `a` and `img` styles will be regarded as unused:\n\n```svelte\n<article>\n\t{@html content}\n</article>\n\n<style>\n\tarticle {\n\t\ta { color: hotpink }\n\t\timg { width: 100% }\n\t}\n</style>\n```\n\nInstead, use the `:global` modifier to target everything inside the `<article>`:\n\n```svelte\n<style>\n\tarticle:global{\n\t\ta { color: hotpink }\n\t\timg { width: 100% }\n\t}\n</style>\n```","size_bytes":897,"metadata":{"tags":"template-html","title":"{@html ...}"},"created_at":"2025-07-18T15:47:38.948Z","updated_at":"2026-02-14T01:33:24.879Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/09-@attach.md","title":"{@attach ...}","filename":"09-@attach.md","content":"Attachments are functions that run in an [effect]($effect) when an element is mounted to the DOM or when [state]($state) read inside the function updates.\n\nOptionally, they can return a function that is called before the attachment re-runs, or after the element is later removed from the DOM.\n\n> Attachments are available in Svelte 5.29 and newer.\n\n```svelte\n<!file: App.svelte>\n<script>\n\t/** @type {import('svelte/attachments').Attachment} */\n\tfunction myAttachment(element) {\n\t\tconsole.log(element.nodeName); // 'DIV'\n\n\t\treturn () => {\n\t\t\tconsole.log('cleaning up');\n\t\t};\n\t}\n</script>\n\n<div {@attach myAttachment}>...</div>\n```\n\nAn element can have any number of attachments.\n\n## Attachment factories\n\nA useful pattern is for a function, such as `tooltip` in this example, to _return_ an attachment ([demo](/playground/untitled#H4sIAAAAAAAAE3VT0XLaMBD8lavbDiaNCUlbHhTItG_5h5AH2T5ArdBppDOEMv73SkbGJGnH47F9t3un3TsfMyO3mInsh2SW1Sa7zlZKo8_E0zHjg42pGAjxBPxp7cTvUHOMldLjv-IVGUbDoUw295VTlh-WZslqa8kxsLL2ACtHWxh175NffnQfAAGikSGxYQGfPEvGfPSIWtOH0TiBVo2pWJEBJtKhQp4YYzjG9JIdcuMM5IZqHMPioY8vOSA997zQoevf4a7heO7cdp34olRiTGr07OhwH1IdoO2A7dLMbwahZq6MbRhKZWqxk7rBxTGVbuHmhCgb5qDgmIx_J6XtHHukHTrYYqx_YpzYng8aO4RYayql7hU-1ZJl0akqHBE_D9KLolwL-Dibzc7iSln9XjtqTF1UpMkJ2EmXR-BgQErsN4pxIJKr0RVO1qrxAqaTO4fbc9bKulZm3cfDY3aZDgvFGErWjmzhN7KmfX5rXyDeX8Pt1mU-hXjdBOrtuB97vK4GPUtmJ41XcRMEGDLD8do0nJ73zhUhSlyRw0t3vPqD8cjfLs-axiFgNBrkUd9Ulp50c-GLxlXAVlJX-ffpZyiSn7H0eLCUySZQcQdXlxj4El0Yv_FZvIKElqqGTruVLhzu7VRKCh22_5toOyxsWqLwwzK-cCbYNdg-hy-p9D7sbiZWUnts_wLUOF3CJgQAAA==)):\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport tippy from 'tippy.js';\n\n\tlet content = $state('Hello!');\n\n\t/**\n\t * @param {string} content\n\t * @returns {import('svelte/attachments').Attachment}\n\t */\n\tfunction tooltip(content) {\n\t\treturn (element) => {\n\t\t\tconst tooltip = tippy(element, { content });\n\t\t\treturn tooltip.destroy;\n\t\t};\n\t}\n</script>\n\n<input bind:value={content} />\n\n<button {@attach tooltip(content)}>\n\tHover me\n</button>\n```\n\nSince the `tooltip(content)` expression runs inside an [effect]($effect), the attachment will be destroyed and recreated whenever `content` changes. The same thing would happen for any state read _inside_ the attachment function when it first runs. (If this isn't what you want, see [Controlling when attachments re-run](#Controlling-when-attachments-re-run).)\n\n## Inline attachments\n\nAttachments can also be created inline ([demo](/playground/untitled#H4sIAAAAAAAAE71Wf3OaWBT9KoyTTnW3MS-I3dYmnWXVtnRAazRJzbozRSQEApiRhwKO333vuY8m225m_9yZGOT9OPfcc84D943UTfxGr_G7K6Xr3TVeNW7D2M8avT_3DVk-YAoDNF4vNB8e2tnWjyXGlm7mPzfurVPpp5JgGmeZtwkf5PtFupCxLzVvHa832rl2lElX-s2Xm2DZFNqp_hs-rZetd4v07ORpT3qmQHu7MF2td0BZp8k6z_xkvfXP902_pZ2_1_aYWEiqm0kN8I4r79qbdZ6umnq3q_2iNf22F4dE6qt2oimwdpim_uY6XMm7Fuo-IQT_iTD_CeGTHwZ38ieIJUFQRxirR1Xf39Dw0X5z0I72Af4tD61vvPNwWKQnqmfPTbduhsEd2J3vO_oBd3dc6fF2X7umNdWGf0vBRhSS6qoV7cCXfTXWfKmvWG61_si_vfU92Wz-E4RhsLhNIYinsox9QKGVd8-tuACCeKXRX12P-T_eKf7fhTq0Hvt-f3ailtSeoxJHRo1-58NoPe1UiBc1hkL8Yeh45y_vQ3mcuNl9T8s3cXPRWLnS7YWJG_gn2Tb4tUjid8jua-PVl08j_ab8I14mH8Llx0s5Tz5Err4ql52r_GYg0mVy1bEGZuD0ze64b5TWYFiM-16wSuJ4JT5vfVpDcztrcG_YkRU4s6HxufzDWF4XuVeJ1P10IbzBemt3Vp1V2e04ZXfrJd7Wicyd039brRIv_RIVu_nXi7X1cfL2sy66ztToUp1TO7qJ7NlwZ0f30pld5qNSVE5o6PbMojFHjgZB7oSicPpGteyLclQap7SvY0dXtM_LR1NT2JFHey3aaxa0VxCeYJ7RMHemoiCcgPZV9pR7o7kgcOjeGliYk9hjDZx8FAq6enwlTPSZj_vYPw9Il64dXdIY8ZmapzwfEd8-1ZyaxWhqkIZOibXUd-6Upqi1pD4uMicCV1GA_7zi73UN8BaF4sC8peJtMjfmjbHZBFwq5ov50qRaE0l96NZggnW4KqypYRAW-uhSz9ADvklwJF2J-5W0Z5fQPBhDX92R6I_0IFxRgDftge4l4dP-gH1hjD7uqU6fsOEZ9UNrCdPB-nys6uXgY6O3ZMd9sy5T9PghqrWHdjo4jB51CgLiKJaDYYA-7WgYONf1FbjkI-mE3EAfUY_rijfuJ_CVPaR50oe9JF7Q0pI8Dw3osxxYHdYPGbp2CnwHF8KvwJv2wEv0Z3ilQI6U9uwbZxbYJXvEmjjQjjCHkvNLvNg3yhzXQd1olamsT4IRrZmX0MUDpwL7R8zzHj7pSh9hPHFSHjLezKqAST51uC5zmtQ87skDUaneLokT5RbXkPWSYz53Abgjc8_o4KFGUZ-Hgv2Z1l5OTYM9D-HfUD0L-EwxH5wRnIG61gS-khfgY1bq7IAP_DA4l5xRuh9xlm8yGjutc8t-wHtkhWv3hc7aqGwiK5KzgvM5xRkZYn193uEln-su55j1GaIv7oM4iPrsVHiG0Dx7TR9-1lBfqFdwfvSd5LNL5xyZVp5NoHFZ57FkfiF6vKs4k5zvIfrX5xX6MXmt0gM5MTu8DjnhukrHHzTRd3jm0dma0_f_x5cxP9f4jBdqHvmbq2fUjzqcKh2Cp-yWj9ntcHanXmBXxhu7Q--eyjhfNFpaV7zgz4nWEUb7zUOhpevjjf_gu_KZ99pxFlZ-T3sttkmYqrco_26q35v0Ewzv5EZPbnL_8BfduWGMnyyN3q0bZ_7hb_7KG_L4CQAA)):\n\n```svelte\n<!file: App.svelte>\n<canvas\n\twidth={32}\n\theight={32}\n\t{@attach (canvas) => {\n\t\tconst context = canvas.getContext('2d');\n\n\t\t$effect(() => {\n\t\t\tcontext.fillStyle = color;\n\t\t\tcontext.fillRect(0, 0, canvas.width, canvas.height);\n\t\t});\n\t}}\n></canvas>\n```\n\n> The nested effect runs whenever `color` changes, while the outer effect (where `canvas.getContext(...)` is called) only runs once, since it doesn't read any reactive state.\n\n## Conditional attachments\n\nFalsy values like `false` or `undefined` are treated as no attachment, enabling conditional usage:\n\n```svelte\n<div {@attach enabled && myAttachment}>...</div>\n```\n\n## Passing attachments to components\n\nWhen used on a component, `{@attach ...}` will create a prop whose key is a [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol). If the component then [spreads](/tutorial/svelte/spread-props) props onto an element, the element will receive those attachments.\n\nThis allows you to create _wrapper components_ that augment elements ([demo](/playground/untitled#H4sIAAAAAAAAE3VUS3ObMBD-KxvajnFqsJM2PhA7TXrKob31FjITAbKtRkiMtDhJPfz3LiAMdpxhGJvdb1_fPnaeYjn3Iu-WIbJ04028lZDcetHDzsO3olbVApI74F1RhHbLJdayhFl-Sp5qhVwhufEWNjWiwJtYxSjyQhsEFEXxBiujcxg1_8O_dnQ9APwsEbVyiHDafjrvDZCgkiO4MLCEzxYZcn90z6XUZ6OxA61KlaIgV6i1pFC-sxjDrlbHaDiWRoGvdMbHsLzp5DES0mJnRxGaRBvcBHb7yFUTCQeunEWYcYtGv12TqgFUDbCK1WLaM6IWQhUlQiJUFm2ZLPly51xXMG0Rjoyd69C7UqqG2nu95QZyXvtvLVpri2-SN4hoLXXCZFfhQ8aQBU1VgdEaH_vSgyBZR_BpPp_vi0tY-rw2ulRZkGqpTQRbZvwa2BPgFC8bgbw31CbjJjAsE6WNYBZeGp7vtQXLMqHWnZx-5kM1TR5ycpkZXQR2wzL94l8Ur1C_3-g168SfQf1MyfRi3LW9fs77emJEw5QV9SREoLTq06tcczq7d6xEUcJX2vAhO1b843XK34e5unZEMBr15ekuKEusluWAF8lXhE2ZTP2r2RcIHJ-163FPKerCgYJLOB9i4GvNwviI5-gAQiFFBk3tBTOU3HFXEk0R8o86WvUD64aINhv5K3oRmpJXkw8uxMG6Hh6JY9X7OwGSqfUy9tDG3sHNoEi0d_d_fv9qndxRU0VClFqo3KVo3U655Hnt1PXB3Qra2Y2QGdEwgTAMCxopsoxOe6SD0gD8movDhT0LAnhqlE8gVCpLWnRoV7OJCkFAwEXitrYL1W7p7pbiE_P7XH6E_rihODm5s52XtiH9Ekaw0VgI9exadWL1uoEYjPtg2672k5szsxbKyWB2fdT0w5Y_0hcT8oXOlRetmLS8-g-6TLXXQgYAAA==)):\n\n```svelte\n<!file: Button.svelte>\n<script>\n\t/** @type {import('svelte/elements').HTMLButtonAttributes} */\n\tlet { children, ...props } = $props();\n</script>\n\n<!-- `props` includes attachments -->\n<button {...props}>\n\t{@render children?.()}\n</button>\n```\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport tippy from 'tippy.js';\n\timport Button from './Button.svelte';\n\n\tlet content = $state('Hello!');\n\n\t/**\n\t * @param {string} content\n\t * @returns {import('svelte/attachments').Attachment}\n\t */\n\tfunction tooltip(content) {\n\t\treturn (element) => {\n\t\t\tconst tooltip = tippy(element, { content });\n\t\t\treturn tooltip.destroy;\n\t\t};\n\t}\n</script>\n\n<input bind:value={content} />\n\n<Button {@attach tooltip(content)}>\n\tHover me\n</Button>\n```\n\n## Controlling when attachments re-run\n\nAttachments, unlike [actions](use), are fully reactive: `{@attach foo(bar)}` will re-run on changes to `foo` _or_ `bar` (or any state read inside `foo`):\n\n```js\n// @errors: 7006 2304 2552\nfunction foo(bar) {\n\treturn (node) => {\n\t\tveryExpensiveSetupWork(node);\n\t\tupdate(node, bar);\n\t};\n}\n```\n\nIn the rare case that this is a problem (for example, if `foo` does expensive and unavoidable setup work) consider passing the data inside a function and reading it in a child effect:\n\n```js\n// @errors: 7006 2304 2552\nfunction foo(getBar) {\n\treturn (node) => {\n\t\tveryExpensiveSetupWork(node);\n\n$effect(() => {\n\t\t\tupdate(node, getBar());\n\t\t});\n\t}\n}\n```\n\n## Creating attachments programmatically\n\nTo add attachments to an object that will be spread onto a component or element, use [`createAttachmentKey`](svelte-attachments#createAttachmentKey).\n\n## Converting actions to attachments\n\nIf you're using a library that only provides actions, you can convert them to attachments with [`fromAction`](svelte-attachments#fromAction), allowing you to (for example) use them with components.","size_bytes":8137,"metadata":{"tags":"attachments","title":"{@attach ...}"},"created_at":"2025-07-18T15:47:38.949Z","updated_at":"2026-02-14T01:33:24.876Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/10-@const.md","title":"{@const ...}","filename":"10-@const.md","content":"The `{@const ...}` tag defines a local constant.\n\n```svelte\n{#each boxes as box}\n\t{@const area = box.width * box.height}\n\t{box.width} * {box.height} = {area}\n{/each}\n```\n\n`{@const}` is only allowed as an immediate child of a block — `{#if ...}`, `{#each ...}`, `{#snippet ...}` and so on — a `<Component />` or a `<svelte:boundary>`.","size_bytes":367,"metadata":{"title":"{@const ...}"},"created_at":"2025-07-18T15:47:38.951Z","updated_at":"2025-07-18T15:47:40.230Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/11-@debug.md","title":"{@debug ...}","filename":"11-@debug.md","content":"The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open.\n\n```svelte\n<script>\n\tlet user = {\n\t\tfirstname: 'Ada',\n\t\tlastname: 'Lovelace'\n\t};\n</script>\n\n{@debug user}\n\n<h1>Hello {user.firstname}!</h1>\n```\n\n`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions).\n\n```svelte\n<!-- Compiles -->\n{@debug user}\n{@debug user1, user2, user3}\n\n<!-- WON'T compile -->\n{@debug user.firstname}\n{@debug myArray[0]}\n{@debug !isReady}\n{@debug typeof user === 'object'}\n```\n\nThe `{@debug}` tag without any arguments will insert a `debugger` statement that gets triggered when _any_ state changes, as opposed to the specified variables.","size_bytes":809,"metadata":{"title":"{@debug ...}"},"created_at":"2025-07-18T15:47:38.951Z","updated_at":"2025-07-18T15:47:40.232Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/12-bind.md","title":"bind:","filename":"12-bind.md","content":"Data ordinarily flows down, from parent to child. The `bind:` directive allows data to flow the other way, from child to parent.\n\nThe general syntax is `bind:property={expression}`, where `expression` is an [_lvalue_](https://press.rebus.community/programmingfundamentals/chapter/lvalue-and-rvalue/) (i.e. a variable or an object property). When the expression is an identifier with the same name as the property, we can omit the expression — in other words these are equivalent:\n\n```svelte\n<input bind:value={value} />\n<input bind:value />\n```\n\n\nSvelte creates an event listener that updates the bound value. If an element already has a listener for the same event, that listener will be fired before the bound value is updated.\n\nMost bindings are _two-way_, meaning that changes to the value will affect the element and vice versa. A few bindings are _readonly_, meaning that changing their value will have no effect on the element.\n\n## Function bindings\n\nYou can also use `bind:property={get, set}`, where `get` and `set` are functions, allowing you to perform validation and transformation:\n\n```svelte\n<input bind:value={\n\t() => value,\n\t(v) => value = v.toLowerCase()}\n/>\n```\n\nIn the case of readonly bindings like [dimension bindings](#Dimensions), the `get` value should be `null`:\n\n```svelte\n<div\n\tbind:clientWidth={null, redraw}\n\tbind:clientHeight={null, redraw}\n>...</div>\n```\n\n> Function bindings are available in Svelte 5.9.0 and newer.\n\n## `<input bind:value>`\n\nA `bind:value` directive on an `<input>` element binds the input's `value` property:\n\n```svelte\n<script>\n\tlet message = $state('hello');\n</script>\n\n<input bind:value={message} />\n<p>{message}</p>\n```\n\nIn the case of a numeric input (`type=\"number\"` or `type=\"range\"`), the value will be coerced to a number ([demo](/playground/untitled#H4sIAAAAAAAAE6WPwYoCMQxAfyWEPeyiOOqx2w74Hds9pBql0IllmhGXYf5dKqwiyILsLXnwwsuI-5i4oPkaUX8yo7kCnKNQV7dNzoty4qSVBSr8jG-Poixa0KAt2z5mbb14TaxA4OCtKCm_rz4-f2m403WltrlrYhMFTtcLNkoeFGqZ8yhDF7j3CCHKzpwoDexGmqCL4jwuPUJHZ-dxVcfmyYGe5MAv-La5pbxYFf5Z9Zf_UJXb-sEMquFgJJhBmGyTW5yj8lnRaD_w9D1dAKSSj7zqAQAA)):\n\n```svelte\n<script>\n\tlet a = $state(1);\n\tlet b = $state(2);\n</script>\n\n<label>\n\t<input type=\"number\" bind:value={a} min=\"0\" max=\"10\" />\n\t<input type=\"range\" bind:value={a} min=\"0\" max=\"10\" />\n</label>\n\n<label>\n\t<input type=\"number\" bind:value={b} min=\"0\" max=\"10\" />\n\t<input type=\"range\" bind:value={b} min=\"0\" max=\"10\" />\n</label>\n\n<p>{a} + {b} = {a + b}</p>\n```\n\nIf the input is empty or invalid (in the case of `type=\"number\"`), the value is `undefined`.\n\nSince 5.6.0, if an `<input>` has a `defaultValue` and is part of a form, it will revert to that value instead of the empty string when the form is reset. Note that for the initial render the value of the binding takes precedence unless it is `null` or `undefined`.\n\n```svelte\n<script>\n\tlet value = $state('');\n</script>\n\n<form>\n\t<input bind:value defaultValue=\"not the empty string\">\n\t<input type=\"reset\" value=\"Reset\">\n</form>\n```\n\n> Use reset buttons sparingly, and ensure that users won't accidentally click them while trying to submit the form.\n\n## `<input bind:checked>`\n\nCheckbox inputs can be bound with `bind:checked`:\n\n```svelte\n<label>\n\t<input type=\"checkbox\" bind:checked={accepted} />\n\tAccept terms and conditions\n</label>\n```\n\nSince 5.6.0, if an `<input>` has a `defaultChecked` attribute and is part of a form, it will revert to that value instead of `false` when the form is reset. Note that for the initial render the value of the binding takes precedence unless it is `null` or `undefined`.\n\n```svelte\n<script>\n\tlet checked = $state(true);\n</script>\n\n<form>\n\t<input type=\"checkbox\" bind:checked defaultChecked={true}>\n\t<input type=\"reset\" value=\"Reset\">\n</form>\n```\n\n\n## `<input bind:indeterminate>`\n\nCheckboxes can be in an [indeterminate](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/indeterminate) state, independently of whether they are checked or unchecked:\n\n```svelte\n<script>\n\tlet checked = $state(false);\n\tlet indeterminate = $state(true);\n</script>\n\n<form>\n\t<input type=\"checkbox\" bind:checked bind:indeterminate>\n\n\t{#if indeterminate}\n\t\twaiting...\n\t{:else if checked}\n\t\tchecked\n\t{:else}\n\t\tunchecked\n\t{/if}\n</form>\n```\n\n## `<input bind:group>`\n\nInputs that work together can use `bind:group` ([demo](/playground/untitled#H4sIAAAAAAAAE62T32_TMBDH_5XDQkpbrct7SCMGEvCEECDxsO7BSW6L2c227EvbKOv_jp0f6jYhQKJv5_P3PvdL1wstH1Bk4hMSGdgbRzUssFaM9VJciFtF6EV23QvubNRFR_BPUVfWXvodEkdfKT3-zl8Zzag5YETuK6csF1u9ZUIGNo4VkYQNvPYsGRfJF5JKJ8s3QRJE6WoFb2Nq6K-ck13u2Sl9Vxxhlc6QUBIFnz9Brm9ifJ6esun81XoNd860FmtwslYGlLYte5AO4aHlVhJ1gIeKWq92COt1iMtJlkhFPkgh1rHZiiF6K6BUus4G5KafGznCTlIbVUMfQZUWMJh5OrL-C_qjMYSwb1DyiH7iOEuCb1ZpWTUjfHqcwC_GWDVY3ZfmME_SGttSmD9IHaYatvWHIc6xLyqad3mq6KuqcCwnWn9p8p-p71BqP2IH81zc9w2in-od7XORP7ayCpd5YCeXI_-p59mObPF9WmwGpx3nqS2Gzw8TO3zOaS5_GqUXyQUkS3h8hOSz0ZhMESHGc0c4Hm3MAn00t1wrb0l2GZRkqvt4sXwczm6Qh8vnUJzI2LV4vAkvqWgfehTZrSSPx19WiVfFfAQAAA==)):\n\n```svelte\n<!file: BurritoChooser.svelte>\n<script>\n\tlet tortilla = $state('Plain');\n\n\t/** @type {string[]} */\n\tlet fillings = $state([]);\n</script>\n\n<!-- grouped radio inputs are mutually exclusive -->\n<label><input type=\"radio\" bind:group={tortilla} value=\"Plain\" /> Plain</label>\n<label><input type=\"radio\" bind:group={tortilla} value=\"Whole wheat\" /> Whole wheat</label>\n<label><input type=\"radio\" bind:group={tortilla} value=\"Spinach\" /> Spinach</label>\n\n<!-- grouped checkbox inputs populate an array -->\n<label><input type=\"checkbox\" bind:group={fillings} value=\"Rice\" /> Rice</label>\n<label><input type=\"checkbox\" bind:group={fillings} value=\"Beans\" /> Beans</label>\n<label><input type=\"checkbox\" bind:group={fillings} value=\"Cheese\" /> Cheese</label>\n<label><input type=\"checkbox\" bind:group={fillings} value=\"Guac (extra)\" /> Guac (extra)</label>\n```\n\n\n## `<input bind:files>`\n\nOn `<input>` elements with `type=\"file\"`, you can use `bind:files` to get the [`FileList` of selected files](https://developer.mozilla.org/en-US/docs/Web/API/FileList). When you want to update the files programmatically, you always need to use a `FileList` object. Currently `FileList` objects cannot be constructed directly, so you need to create a new [`DataTransfer`](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer) object and get `files` from there.\n\n```svelte\n<script>\n\tlet files = $state();\n\n\tfunction clear() {\n\t\tfiles = new DataTransfer().files; // null or undefined does not work\n\t}\n</script>\n\n<label for=\"avatar\">Upload a picture:</label>\n<input accept=\"image/png, image/jpeg\" bind:files id=\"avatar\" name=\"avatar\" type=\"file\" />\n<button onclick={clear}>clear</button>\n```\n\n`FileList` objects also cannot be modified, so if you want to e.g. delete a single file from the list, you need to create a new `DataTransfer` object and add the files you want to keep.\n\n\n## `<select bind:value>`\n\nA `<select>` value binding corresponds to the `value` property on the selected `<option>`, which can be any value (not just strings, as is normally the case in the DOM).\n\n```svelte\n<select bind:value={selected}>\n\t<option value={a}>a</option>\n\t<option value={b}>b</option>\n\t<option value={c}>c</option>\n</select>\n```\n\nA `<select multiple>` element behaves similarly to a checkbox group. The bound variable is an array with an entry corresponding to the `value` property of each selected `<option>`.\n\n```svelte\n<select multiple bind:value={fillings}>\n\t<option value=\"Rice\">Rice</option>\n\t<option value=\"Beans\">Beans</option>\n\t<option value=\"Cheese\">Cheese</option>\n\t<option value=\"Guac (extra)\">Guac (extra)</option>\n</select>\n```\n\nWhen the value of an `<option>` matches its text content, the attribute can be omitted.\n\n```svelte\n<select multiple bind:value={fillings}>\n\t<option>Rice</option>\n\t<option>Beans</option>\n\t<option>Cheese</option>\n\t<option>Guac (extra)</option>\n</select>\n```\n\nYou can give the `<select>` a default value by adding a `selected` attribute to the`<option>` (or options, in the case of `<select multiple>`) that should be initially selected. If the `<select>` is part of a form, it will revert to that selection when the form is reset. Note that for the initial render the value of the binding takes precedence if it's not `undefined`.\n\n```svelte\n<select bind:value={selected}>\n\t<option value={a}>a</option>\n\t<option value={b} selected>b</option>\n\t<option value={c}>c</option>\n</select>\n```\n\n## `<audio>`\n\n`<audio>` elements have their own set of bindings — five two-way ones...\n\n- [`currentTime`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/currentTime)\n- [`playbackRate`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playbackRate)\n- [`paused`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/paused)\n- [`volume`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/volume)\n- [`muted`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/muted)\n\n...and six readonly ones:\n\n- [`duration`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/duration)\n- [`buffered`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered)\n- [`seekable`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seekable)\n- [`seeking`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seeking_event)\n- [`ended`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended)\n- [`readyState`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState)\n- [`played`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/played)\n\n```svelte\n<audio src={clip} bind:duration bind:currentTime bind:paused></audio>\n```\n\n## `<video>`\n\n`<video>` elements have all the same bindings as [`<audio>`](#audio) elements, plus readonly [`videoWidth`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement/videoWidth) and [`videoHeight`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement/videoHeight) bindings.\n\n## `<img>`\n\n`<img>` elements have two readonly bindings:\n\n- [`naturalWidth`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth)\n- [`naturalHeight`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalHeight)\n\n## `<details bind:open>`\n\n`<details>` elements support binding to the `open` property.\n\n```svelte\n<details bind:open={isOpen}>\n\t<summary>How do you comfort a JavaScript bug?</summary>\n\t<p>You console it.</p>\n</details>\n```\n\n## `window` and `document`\n\nTo bind to properties of `window` and `document`, see [`<svelte:window>`](svelte-window) and [`<svelte:document>`](svelte-document).\n\n## Contenteditable bindings\n\nElements with the `contenteditable` attribute support the following bindings:\n\n- [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML)\n- [`innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText)\n- [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent)\n\n\n<!-- for some reason puts the comment and html on same line -->\n```svelte\n<div contenteditable=\"true\" bind:innerHTML={html}></div>\n```\n\n## Dimensions\n\nAll visible elements have the following readonly bindings, measured with a `ResizeObserver`:\n\n- [`clientWidth`](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth)\n- [`clientHeight`](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight)\n- [`offsetWidth`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth)\n- [`offsetHeight`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight)\n- [`contentRect`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentRect)\n- [`contentBoxSize`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize)\n- [`borderBoxSize`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/borderBoxSize)\n- [`devicePixelContentBoxSize`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/devicePixelContentBoxSize)\n\n```svelte\n<div bind:offsetWidth={width} bind:offsetHeight={height}>\n\t<Chart {width} {height} />\n</div>\n```\n\n\n## bind:this\n\n```svelte\n<!copy: false>\nbind:this={dom_node}\n```\n\nTo get a reference to a DOM node, use `bind:this`. The value will be `undefined` until the component is mounted — in other words, you should read it inside an effect or an event handler, but not during component initialisation:\n\n```svelte\n<script>\n\t/** @type {HTMLCanvasElement} */\n\tlet canvas;\n\n\t$effect(() => {\n\t\tconst ctx = canvas.getContext('2d');\n\t\tdrawStuff(ctx);\n\t});\n</script>\n\n<canvas bind:this={canvas}></canvas>\n```\n\nComponents also support `bind:this`, allowing you to interact with component instances programmatically.\n\n```svelte\n<!file: App.svelte>\n<ShoppingCart bind:this={cart} />\n\n<button onclick={() => cart.empty()}> Empty shopping cart </button>\n```\n\n```svelte\n<!file: ShoppingCart.svelte>\n<script>\n\t// All instance exports are available on the instance object\n\texport function empty() {\n\t\t// ...\n\t}\n</script>\n```\n\n\n## bind:_property_ for components\n\n```svelte\nbind:property={variable}\n```\n\nYou can bind to component props using the same syntax as for elements.\n\n```svelte\n<Keypad bind:value={pin} />\n```\n\nWhile Svelte props are reactive without binding, that reactivity only flows downward into the component by default. Using `bind:property` allows changes to the property from within the component to flow back up out of the component.\n\nTo mark a property as bindable, use the [`$bindable`]($bindable) rune:\n\n```svelte\n<script>\n\tlet { readonlyProperty, bindableProperty = $bindable() } = $props();\n</script>\n```\n\nDeclaring a property as bindable means it _can_ be used using `bind:`, not that it _must_ be used using `bind:`.\n\nBindable properties can have a fallback value:\n\n```svelte\n<script>\n\tlet { bindableProperty = $bindable('fallback value') } = $props();\n</script>\n```\n\nThis fallback value _only_ applies when the property is _not_ bound. When the property is bound and a fallback value is present, the parent is expected to provide a value other than `undefined`, else a runtime error is thrown. This prevents hard-to-reason-about situations where it's unclear which value should apply.","size_bytes":14251,"metadata":{"title":"bind:"},"created_at":"2025-07-18T15:47:38.953Z","updated_at":"2025-10-12T02:00:03.952Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/13-use.md","title":"use:","filename":"13-use.md","content":"> In Svelte 5.29 and newer, consider using [attachments](@attach) instead, as they are more flexible and composable.\n\nActions are functions that are called when an element is mounted. They are added with the `use:` directive, and will typically use an `$effect` so that they can reset any state when the element is unmounted:\n\n```svelte\n<!file: App.svelte>\n<script>\n\t/** @type {import('svelte/action').Action} */\n\tfunction myaction(node) {\n\t\t// the node has been mounted in the DOM\n\n\t\t$effect(() => {\n\t\t\t// setup goes here\n\n\t\t\treturn () => {\n\t\t\t\t// teardown goes here\n\t\t\t};\n\t\t});\n\t}\n</script>\n\n<div use:myaction>...</div>\n```\n\nAn action can be called with an argument:\n\n```svelte\n<!file: App.svelte>\n<script>\n\t/** @type {import('svelte/action').Action} */\n\tfunction myaction(node,data) {\n\t\t// ...\n\t}\n</script>\n\n<div use:myaction={data}>...</div>\n```\n\nThe action is only called once (but not during server-side rendering) — it will _not_ run again if the argument changes.\n\n> [!LEGACY]\n> Prior to the `$effect` rune, actions could return an object with `update` and `destroy` methods, where `update` would be called with the latest value of the argument if it changed. Using effects is preferred.\n\n## Typing\n\nThe `Action` interface receives three optional type arguments — a node type (which can be `Element`, if the action applies to everything), a parameter, and any custom event handlers created by the action:\n\n```svelte\n<!file: App.svelte>\n<script>\n\t/**\n\t * @type {import('svelte/action').Action<\n\t * \tHTMLDivElement,\n\t * \tundefined,\n\t * \t{\n\t * \t\tonswiperight: (e: CustomEvent) => void;\n\t * \t\tonswipeleft: (e: CustomEvent) => void;\n\t * \t\t// ...\n\t * \t}\n\t * >}\n\t */\n\tfunction gestures(node) {\n\t\t$effect(() => {\n\t\t\t// ...\n\t\t\tnode.dispatchEvent(new CustomEvent('swipeleft'));\n\n\t\t\t// ...\n\t\t\tnode.dispatchEvent(new CustomEvent('swiperight'));\n\t\t});\n\t}\n</script>\n\n<div\n\tuse:gestures\n\tonswipeleft={next}\n\tonswiperight={prev}\n>...</div>\n```","size_bytes":1961,"metadata":{"title":"use:"},"created_at":"2025-07-18T15:47:38.956Z","updated_at":"2025-07-18T15:47:40.234Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/14-transition.md","title":"transition:","filename":"14-transition.md","content":"A _transition_ is triggered by an element entering or leaving the DOM as a result of a state change.\n\nWhen a block (such as an `{#if ...}` block) is transitioning out, all elements inside it, including those that do not have their own transitions, are kept in the DOM until every transition in the block has been completed.\n\nThe `transition:` directive indicates a _bidirectional_ transition, which means it can be smoothly reversed while the transition is in progress.\n\n```svelte\n<script>\n\timport { fade } from 'svelte/transition';\n\n\tlet visible = $state(false);\n</script>\n\n<button onclick={() => visible = !visible}>toggle</button>\n\n{#if visible}\n\t<divtransition:fade>fades in and out</div>\n{/if}\n```\n\n## Local vs global\n\nTransitions are local by default. Local transitions only play when the block they belong to is created or destroyed, _not_ when parent blocks are created or destroyed.\n\n```svelte\n{#if x}\n\t{#if y}\n\t\t<p transition:fade>fades in and out only when y changes</p>\n\n\t\t<p transition:fade|global>fades in and out when x or y change</p>\n\t{/if}\n{/if}\n```\n\n## Built-in transitions\n\nA selection of built-in transitions can be imported from the [`svelte/transition`](svelte-transition) module.\n\n## Transition parameters\n\nTransitions can have parameters.\n\n(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)\n\n```svelte\n{#if visible}\n\t<div transition:fade={{ duration: 2000 }}>fades in and out over two seconds</div>\n{/if}\n```\n\n## Custom transition functions\n\n```js\n/// copy: false\n// @noErrors\ntransition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => {\n\tdelay?: number,\n\tduration?: number,\n\teasing?: (t: number) => number,\n\tcss?: (t: number, u: number) => string,\n\ttick?: (t: number, u: number) => void\n}\n```\n\nTransitions can use custom functions. If the returned object has a `css` function, Svelte will generate keyframes for a [web animation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API).\n\nThe `t` argument passed to `css` is a value between `0` and `1` after the `easing` function has been applied. _In_ transitions run from `0` to `1`, _out_ transitions run from `1` to `0` — in other words, `1` is the element's natural state, as though no transition had been applied. The `u` argument is equal to `1 - t`.\n\nThe function is called repeatedly _before_ the transition begins, with different `t` and `u` arguments.\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport { elasticOut } from 'svelte/easing';\n\n\t/** @type {boolean} */\n\texport let visible;\n\n\t/**\n\t * @param {HTMLElement} node\n\t * @param {{ delay?: number, duration?: number, easing?: (t: number) => number }} params\n\t */\n\tfunction whoosh(node, params) {\n\t\tconst existingTransform = getComputedStyle(node).transform.replace('none', '');\n\n\t\treturn {\n\t\t\tdelay: params.delay || 0,\n\t\t\tduration: params.duration || 400,\n\t\t\teasing: params.easing || elasticOut,\n\t\t\tcss: (t, u) => `transform: ${existingTransform} scale(${t})`\n\t\t};\n\t}\n</script>\n\n{#if visible}\n\t<div in:whoosh>whooshes in</div>\n{/if}\n```\n\nA custom transition function can also return a `tick` function, which is called _during_ the transition with the same `t` and `u` arguments.\n\n\n```svelte\n<!file: App.svelte>\n<script>\n\texport let visible = false;\n\n\t/**\n\t * @param {HTMLElement} node\n\t * @param {{ speed?: number }} params\n\t */\n\tfunction typewriter(node, { speed = 1 }) {\n\t\tconst valid = node.childNodes.length === 1 && node.childNodes[0].nodeType === Node.TEXT_NODE;\n\n\t\tif (!valid) {\n\t\t\tthrow new Error(`This transition only works on elements with a single text node child`);\n\t\t}\n\n\t\tconst text = node.textContent;\n\t\tconst duration = text.length / (speed * 0.01);\n\n\t\treturn {\n\t\t\tduration,\n\t\t\ttick: (t) => {\n\t\t\t\tconst i = ~~(text.length * t);\n\t\t\t\tnode.textContent = text.slice(0, i);\n\t\t\t}\n\t\t};\n\t}\n</script>\n\n{#if visible}\n\t<p in:typewriter={{ speed: 1 }}>The quick brown fox jumps over the lazy dog</p>\n{/if}\n```\n\nIf a transition returns a function instead of a transition object, the function will be called in the next microtask. This allows multiple transitions to coordinate, making [crossfade effects](/tutorial/deferred-transitions) possible.\n\nTransition functions also receive a third argument, `options`, which contains information about the transition.\n\nAvailable values in the `options` object are:\n\n- `direction` - one of `in`, `out`, or `both` depending on the type of transition\n\n## Transition events\n\nAn element with transitions will dispatch the following events in addition to any standard DOM events:\n\n- `introstart`\n- `introend`\n- `outrostart`\n- `outroend`\n\n```svelte\n{#if visible}\n\t<p\n\t\ttransition:fly={{ y: 200, duration: 2000 }}\n\t\tonintrostart={() => (status = 'intro started')}\n\t\tonoutrostart={() => (status = 'outro started')}\n\t\tonintroend={() => (status = 'intro ended')}\n\t\tonoutroend={() => (status = 'outro ended')}\n\t>\n\t\tFlies in and out\n\t</p>\n{/if}\n```","size_bytes":4969,"metadata":{"tags":"transitions","title":"transition:"},"created_at":"2025-07-18T15:47:38.957Z","updated_at":"2026-02-14T01:33:24.876Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/15-in-and-out.md","title":"in: and out:","filename":"15-in-and-out.md","content":"The `in:` and `out:` directives are identical to [`transition:`](transition), except that the resulting transitions are not bidirectional — an `in` transition will continue to 'play' alongside the `out` transition, rather than reversing, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch.\n\n```svelte\n<script>\n  import { fade, fly } from 'svelte/transition';\n\n  let visible = $state(false);\n</script>\n\n<label>\n  <input type=\"checkbox\" bind:checked={visible}>\n  visible\n</label>\n\n{#if visible}\n\t<div in:fly={{ y: 200 }} out:fade>flies in, fades out</div>\n{/if}\n```","size_bytes":694,"metadata":{"tags":"transitions","title":"in: and out:"},"created_at":"2025-07-18T15:47:38.958Z","updated_at":"2026-02-14T01:33:24.877Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/16-animate.md","title":"animate:","filename":"16-animate.md","content":"An animation is triggered when the contents of a [keyed each block](each#Keyed-each-blocks) are re-ordered. Animations do not run when an element is added or removed, only when the index of an existing data item within the each block changes. Animate directives must be on an element that is an _immediate_ child of a keyed each block.\n\nAnimations can be used with Svelte's [built-in animation functions](svelte-animate) or [custom animation functions](#Custom-animation-functions).\n\n```svelte\n<!-- When `list` is reordered the animation will run -->\n{#each list as item, index (item)}\n\t<li animate:flip>{item}</li>\n{/each}\n```\n\n## Animation Parameters\n\nAs with actions and transitions, animations can have parameters.\n\n(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)\n\n```svelte\n{#each list as item, index (item)}\n\t<li animate:flip={{ delay: 500 }}>{item}</li>\n{/each}\n```\n\n## Custom animation functions\n\n```js\n/// copy: false\n// @noErrors\nanimation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => {\n\tdelay?: number,\n\tduration?: number,\n\teasing?: (t: number) => number,\n\tcss?: (t: number, u: number) => string,\n\ttick?: (t: number, u: number) => void\n}\n```\n\nAnimations can use custom functions that provide the `node`, an `animation` object and any `parameters` as arguments. The `animation` parameter is an object containing `from` and `to` properties each containing a [DOMRect](https://developer.mozilla.org/en-US/docs/Web/API/DOMRect#Properties) describing the geometry of the element in its `start` and `end` positions. The `from` property is the DOMRect of the element in its starting position, and the `to` property is the DOMRect of the element in its final position after the list has been reordered and the DOM updated.\n\nIf the returned object has a `css` method, Svelte will create a [web animation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) that plays on the element.\n\nThe `t` argument passed to `css` is a value that goes from `0` and `1` after the `easing` function has been applied. The `u` argument is equal to `1 - t`.\n\nThe function is called repeatedly _before_ the animation begins, with different `t` and `u` arguments.\n\n<!-- TODO: Types -->\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport { cubicOut } from 'svelte/easing';\n\n\t/**\n\t * @param {HTMLElement} node\n\t * @param {{ from: DOMRect; to: DOMRect }} states\n\t * @param {any} params\n\t */\n\tfunction whizz(node, { from, to }, params) {\n\t\tconst dx = from.left - to.left;\n\t\tconst dy = from.top - to.top;\n\n\t\tconst d = Math.sqrt(dx * dx + dy * dy);\n\n\t\treturn {\n\t\t\tdelay: 0,\n\t\t\tduration: Math.sqrt(d) * 120,\n\t\t\teasing: cubicOut,\n\t\t\tcss: (t, u) => `transform: translate(${u * dx}px, ${u * dy}px) rotate(${t * 360}deg);`\n\t\t};\n\t}\n</script>\n\n{#each list as item, index (item)}\n\t<div animate:whizz>{item}</div>\n{/each}\n```\n\nA custom animation function can also return a `tick` function, which is called _during_ the animation with the same `t` and `u` arguments.\n\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport { cubicOut } from 'svelte/easing';\n\n\t/**\n\t * @param {HTMLElement} node\n\t * @param {{ from: DOMRect; to: DOMRect }} states\n\t * @param {any} params\n\t */\n\tfunction whizz(node, { from, to }, params) {\n\t\tconst dx = from.left - to.left;\n\t\tconst dy = from.top - to.top;\n\n\t\tconst d = Math.sqrt(dx * dx + dy * dy);\n\n\t\treturn {\n\t\t\tdelay: 0,\n\t\t\tduration: Math.sqrt(d) * 120,\n\t\t\teasing: cubicOut,\n\t\t\ttick: (t, u) => Object.assign(node.style, { color: t > 0.5 ? 'Pink' : 'Blue' })\n\t\t};\n\t}\n</script>\n\n{#each list as item, index (item)}\n\t<div animate:whizz>{item}</div>\n{/each}\n```","size_bytes":3670,"metadata":{"title":"animate:"},"created_at":"2025-07-18T15:47:38.961Z","updated_at":"2025-07-18T15:47:40.240Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/17-style.md","title":"style:","filename":"17-style.md","content":"The `style:` directive provides a shorthand for setting multiple styles on an element.\n\n```svelte\n<!-- These are equivalent -->\n<div style:color=\"red\">...</div>\n<div style=\"color: red;\">...</div>\n```\n\nThe value can contain arbitrary expressions:\n\n```svelte\n<div style:color={myColor}>...</div>\n```\n\nThe shorthand form is allowed:\n\n```svelte\n<div style:color>...</div>\n```\n\nMultiple styles can be set on a single element:\n\n```svelte\n<div style:color style:width=\"12rem\" style:background-color={darkMode ? 'black' : 'white'}>...</div>\n```\n\nTo mark a style as important, use the `|important` modifier:\n\n```svelte\n<div style:color|important=\"red\">...</div>\n```\n\nWhen `style:` directives are combined with `style` attributes, the directives will take precedence,\neven over `!important` properties:\n\n```svelte\n<div style:color=\"red\" style=\"color: blue\">This will be red</div>\n<div style:color=\"red\" style=\"color: blue !important\">This will still be red</div>\n```","size_bytes":1001,"metadata":{"tags":"template-style","title":"style:"},"created_at":"2025-07-18T15:47:38.962Z","updated_at":"2026-02-14T01:33:24.877Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/18-class.md","title":"class","filename":"18-class.md","content":"There are two ways to set classes on elements: the `class` attribute, and the `class:` directive.\n\n## Attributes\n\nPrimitive values are treated like any other attribute:\n\n```svelte\n<div class={large ? 'large' : 'small'}>...</div>\n```\n\n> For historical reasons, falsy values (like `false` and `NaN`) are stringified (`class=\"false\"`), though `class={undefined}` (or `null`) cause the attribute to be omitted altogether. In a future version of Svelte, all falsy values will cause `class` to be omitted.\n\n### Objects and arrays\n\nSince Svelte 5.16, `class` can be an object or array, and is converted to a string using [clsx](https://github.com/lukeed/clsx).\n\nIf the value is an object, the truthy keys are added:\n\n```svelte\n<script>\n\tlet { cool } = $props();\n</script>\n\n<!-- results in `class=\"cool\"` if `cool` is truthy,\n     `class=\"lame\"` otherwise -->\n<div class={{ cool, lame: !cool }}>...</div>\n```\n\nIf the value is an array, the truthy values are combined:\n\n```svelte\n<!-- if `faded` and `large` are both truthy, results in\n     `class=\"saturate-0 opacity-50 scale-200\"` -->\n<div class={[faded && 'saturate-0 opacity-50', large && 'scale-200']}>...</div>\n```\n\nNote that whether we're using the array or object form, we can set multiple classes simultaneously with a single condition, which is particularly useful if you're using things like Tailwind.\n\nArrays can contain arrays and objects, and clsx will flatten them. This is useful for combining local classes with props, for example:\n\n```svelte\n<!file: Button.svelte>\n<script>\n\tlet props = $props();\n</script>\n\n<button {...props} class={['cool-button', props.class]}>\n\t{@render props.children?.()}\n</button>\n```\n\nThe user of this component has the same flexibility to use a mixture of objects, arrays and strings:\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Button from './Button.svelte';\n\tlet useTailwind = $state(false);\n</script>\n\n<Button\n\tonclick={() => useTailwind = true}\n\tclass={{ 'bg-blue-700 sm:w-1/2': useTailwind }}\n>\n\tAccept the inevitability of Tailwind\n</Button>\n```\n\nSince Svelte 5.19, Svelte also exposes the `ClassValue` type, which is the type of value that the `class` attribute on elements accept. This is useful if you want to use a type-safe class name in component props:\n\n```svelte\n<script lang=\"ts\">\n\timport type { ClassValue } from 'svelte/elements';\n\n\tconst props: { class: ClassValue } = $props();\n</script>\n\n<div class={['original', props.class]}>...</div>\n```\n\n## The `class:` directive\n\nPrior to Svelte 5.16, the `class:` directive was the most convenient way to set classes on elements conditionally.\n\n```svelte\n<!-- These are equivalent -->\n<div class={{ cool, lame: !cool }}>...</div>\n<div class:cool={cool} class:lame={!cool}>...</div>\n```\n\nAs with other directives, we can use a shorthand when the name of the class coincides with the value:\n\n```svelte\n<div class:cool class:lame={!cool}>...</div>\n```","size_bytes":2941,"metadata":{"tags":"template-style","title":"class"},"created_at":"2025-07-18T15:47:38.964Z","updated_at":"2026-02-14T01:33:24.878Z"},{"path":"apps/svelte.dev/content/docs/svelte/03-template-syntax/19-await-expressions.md","title":"await","filename":"19-await-expressions.md","content":"As of Svelte 5.36, you can use the `await` keyword inside your components in three places where it was previously unavailable:\n\n- at the top level of your component's `<script>`\n- inside `$derived(...)` declarations\n- inside your markup\n\nThis feature is currently experimental, and you must opt in by adding the `experimental.async` option wherever you [configure](/docs/kit/configuration) Svelte, usually `svelte.config.js`:\n\n```js\n/// file: svelte.config.js\nexport default {\n\tcompilerOptions: {\n\t\texperimental: {\n\t\t\tasync: true\n\t\t}\n\t}\n};\n```\n\nThe experimental flag will be removed in Svelte 6.\n\n## Synchronized updates\n\nWhen an `await` expression depends on a particular piece of state, changes to that state will not be reflected in the UI until the asynchronous work has completed, so that the UI is not left in an inconsistent state. In other words, in an example like [this](/playground/untitled#H4sIAAAAAAAAE42QsWrDQBBEf2VZUkhYRE4gjSwJ0qVMkS6XYk9awcFpJe5Wdoy4fw-ycdykSPt2dpiZFYVGxgrf2PsJTlPwPWTcO-U-xwIH5zli9bminudNtwEsbl-v8_wYj-x1Y5Yi_8W7SZRFI1ZYxy64WVsjRj0rEDTwEJWUs6f8cKP2Tp8vVIxSPEsHwyKdukmA-j6jAmwO63Y1SidyCsIneA_T6CJn2ZBD00Jk_XAjT4tmQwEv-32eH6AsgYK6wXWOPPTs6Xy1CaxLECDYgb3kSUbq8p5aaifzorCt0RiUZbQcDIJ10ldH8gs3K6X2Xzqbro5zu1KCHaw2QQPrtclvwVSXc2sEC1T-Vqw0LJy-ClRy_uSkx2ogHzn9ADZ1CubKAQAA)...\n\n```svelte\n<script>\n\tlet a = $state(1);\n\tlet b = $state(2);\n\n\tasync function add(a, b) {\n\t\tawait new Promise((f) => setTimeout(f, 500)); // artificial delay\n\t\treturn a + b;\n\t}\n</script>\n\n<input type=\"number\" bind:value={a}>\n<input type=\"number\" bind:value={b}>\n\n<p>{a} + {b} = {await add(a, b)}</p>\n```\n\n...if you increment `a`, the contents of the `<p>` will _not_ immediately update to read this —\n\n```html\n<p>2 + 2 = 3</p>\n```\n\n— instead, the text will update to `2 + 2 = 4` when `add(a, b)` resolves.\n\nUpdates can overlap — a fast update will be reflected in the UI while an earlier slow update is still ongoing.\n\n## Concurrency\n\nSvelte will do as much asynchronous work as it can in parallel. For example if you have two `await` expressions in your markup...\n\n```svelte\n<p>{await one()}</p>\n<p>{await two()}</p>\n```\n\n...both functions will run at the same time, as they are independent expressions, even though they are _visually_ sequential.\n\nThis does not apply to sequential `await` expressions inside your `<script>` or inside async functions — these run like any other asynchronous JavaScript. An exception is that independent `$derived` expressions will update independently, even though they will run sequentially when they are first created:\n\n```js\nasync function one() { return 1; }\nasync function two() { return 2; }\n//cut\n// these will run sequentially the first time,\n// but will update independently\nlet a = $derived(await one());\nlet b = $derived(await two());\n```\n\n\n## Indicating loading states\n\nTo render placeholder UI, you can wrap content in a `<svelte:boundary>` with a [`pending`](svelte-boundary#Properties-pending) snippet. This will be shown when the boundary is first created, but not for subsequent updates, which are globally coordinated.\n\nAfter the contents of a boundary have resolved for the first time and have replaced the `pending` snippet, you can detect subsequent async work with [`$effect.pending()`]($effect#$effect.pending). This is what you would use to display a \"we're asynchronously validating your input\" spinner next to a form field, for example.\n\nYou can also use [`settled()`](svelte#settled) to get a promise that resolves when the current update is complete:\n\n```js\nlet color = 'red';\nlet answer = -1;\nlet updating = false;\n//cut\nimport { tick, settled } from 'svelte';\n\nasync function onclick() {\n\tupdating = true;\n\n\t// without this, the change to `updating` will be\n\t// grouped with the other changes, meaning it\n\t// won't be reflected in the UI\n\tawait tick();\n\n\tcolor = 'octarine';\n\tanswer = 42;\n\n\tawait settled();\n\n\t// any updates affected by `color` or `answer`\n\t// have now been applied\n\tupdating = false;\n}\n```\n\n## Error handling\n\nErrors in `await` expressions will bubble to the nearest [error boundary](svelte-boundary).\n\n## Server-side rendering\n\nSvelte supports asynchronous server-side rendering (SSR) with the `render(...)` API. To use it, simply await the return value:\n\n```js\n/// file: server.js\nimport { render } from 'svelte/server';\nimport App from './App.svelte';\n\nconst { head, body } =awaitrender(App);\n```\n\n\nIf a `<svelte:boundary>` with a `pending` snippet is encountered during SSR, that snippet will be rendered while the rest of the content is ignored. All `await` expressions encountered outside boundaries with `pending` snippets will resolve and render their contents prior to `await render(...)` returning.\n\n\n## Forking\n\nThe [`fork(...)`](svelte#fork) API, added in 5.42, makes it possible to run `await` expressions that you _expect_ to happen in the near future. This is mainly intended for frameworks like SvelteKit to implement preloading when (for example) users signal an intent to navigate.\n\n```svelte\n<script>\n\timport { fork } from 'svelte';\n\timport Menu from './Menu.svelte';\n\n\tlet open = $state(false);\n\n\t/** @type {import('svelte').Fork | null} */\n\tlet pending = null;\n\n\tfunction preload() {\n\t\tpending ??= fork(() => {\n\t\t\topen = true;\n\t\t});\n\t}\n\n\tfunction discard() {\n\t\tpending?.discard();\n\t\tpending = null;\n\t}\n</script>\n\n<button\n\tonfocusin={preload}\n\tonfocusout={discard}\n\tonpointerenter={preload}\n\tonpointerleave={discard}\n\tonclick={() => {\n\t\tpending?.commit();\n\t\tpending = null;\n\n\t\t// in case `pending` didn't exist\n\t\t// (if it did, this is a no-op)\n\t\topen = true;\n\t}}\n>open menu</button>\n\n{#if open}\n\t<!-- any async work inside this component will start\n\t     as soon as the fork is created -->\n\t<Menu onclose={() => open = false} />\n{/if}\n```\n\n## Caveats\n\nAs an experimental feature, the details of how `await` is handled (and related APIs like `$effect.pending()`) are subject to breaking changes outside of a semver major release, though we intend to keep such changes to a bare minimum.\n\n## Breaking changes\n\nEffects run in a slightly different order when the `experimental.async` option is `true`. Specifically, _block_ effects like `{#if ...}` and `{#each ...}` now run before an `$effect.pre` or `beforeUpdate` in the same component, which means that in [very rare situations](/playground/untitled?#H4sIAAAAAAAAE22R3VLDIBCFX2WLvUhnTHsf0zre-Q7WmfwtFV2BgU1rJ5N3F0jaOuoVcPbw7VkYhK4_URTiGYkMnIyjDjLsFGO3EvdCKkIvipdB8NlGXxSCPt96snbtj0gctab2-J_eGs2oOWBE6VunLO_2es-EDKZ5x5ZhC0vPNWM2gHXGouNzAex6hHH1cPHil_Lsb95YT9VQX6KUAbS2DrNsBdsdDFHe8_XSYjH1SrhELTe3MLpsemajweiWVPuxHSbKNd-8eQTdE0EBf4OOaSg2hwNhhE_ABB_ulJzjj9FULvIcqgm5vnAqUB7wWFMfhuugQWkcAr8hVD-mq8D12kOep24J_IszToOXdveGDsuNnZwbJUNlXsKnhJdhUcTo42s41YpOSneikDV5HL8BktM6yRcCAAA=) it is possible to update a block that should no longer exist, but only if you update state inside an effect, [which you should avoid]($effect#When-not-to-use-$effect).","size_bytes":6927,"metadata":{"title":"await"},"created_at":"2025-07-18T15:47:38.965Z","updated_at":"2025-10-26T14:00:08.867Z"},{"path":"apps/svelte.dev/content/docs/svelte/04-styling/01-scoped-styles.md","title":"Scoped styles","filename":"01-scoped-styles.md","content":"Svelte components can include a `<style>` element containing CSS that belongs to the component. This CSS is _scoped_ by default, meaning that styles will not apply to any elements on the page outside the component in question.\n\nThis works by adding a class to affected elements, which is based on a hash of the component styles (e.g. `svelte-123xyz`).\n\n```svelte\n<style>\n\tp {\n\t\t/* this will only affect <p> elements in this component */\n\t\tcolor: burlywood;\n\t}\n</style>\n```\n\n## Specificity\n\nEach scoped selector receives a [specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) increase of 0-1-0, as a result of the scoping class (e.g. `.svelte-123xyz`) being added to the selector. This means that (for example) a `p` selector defined in a component will take precedence over a `p` selector defined in a global stylesheet, even if the global stylesheet is loaded later.\n\nIn some cases, the scoping class must be added to a selector multiple times, but after the first occurrence it is added with `:where(.svelte-xyz123)` in order to not increase specificity further.\n\n## Scoped keyframes\n\nIf a component defines `@keyframes`, the name is scoped to the component using the same hashing approach. Any `animation` rules in the component will be similarly adjusted:\n\n```svelte\n<style>\n\t.bouncy {\n\t\tanimation: bounce 10s;\n\t}\n\n\t/* these keyframes are only accessible inside this component */\n\t@keyframes bounce {\n\t\t/* ... */\n\t}\n</style>\n```","size_bytes":1506,"metadata":{"tags":"styles-scoped","title":"Scoped styles"},"created_at":"2025-07-18T15:47:38.971Z","updated_at":"2026-02-14T01:33:24.878Z"},{"path":"apps/svelte.dev/content/docs/svelte/04-styling/02-global-styles.md","title":"Global styles","filename":"02-global-styles.md","content":"## :global(...)\n\nTo apply styles to a single selector globally, use the `:global(...)` modifier:\n\n```svelte\n<style>\n\t:global(body) {\n\t\t/* applies to <body> */\n\t\tmargin: 0;\n\t}\n\n\tdiv :global(strong) {\n\t\t/* applies to all <strong> elements, in any component,\n\t\t   that are inside <div> elements belonging\n\t\t   to this component */\n\t\tcolor: goldenrod;\n\t}\n\n\tp:global(.big.red) {\n\t\t/* applies to all <p> elements belonging to this component\n\t\t   with `class=\"big red\"`, even if it is applied\n\t\t   programmatically (for example by a library) */\n\t}\n</style>\n```\n\nIf you want to make @keyframes that are accessible globally, you need to prepend your keyframe names with `-global-`.\n\nThe `-global-` part will be removed when compiled, and the keyframe will then be referenced using just `my-animation-name` elsewhere in your code.\n\n```svelte\n<style>\n\t@keyframes -global-my-animation-name {\n\t\t/* code goes here */\n\t}\n</style>\n```\n\n## :global\n\nTo apply styles to a group of selectors globally, create a `:global {...}` block:\n\n```svelte\n<style>\n\t:global {\n\t\t/* applies to every <div> in your application */\n\t\tdiv { ... }\n\n\t\t/* applies to every <p> in your application */\n\t\tp { ... }\n\t}\n\n\t.a :global {\n\t\t/* applies to every `.b .c .d` element, in any component,\n\t\t   that is inside an `.a` element in this component */\n\t\t.b .c .d {...}\n\t}\n</style>\n```","size_bytes":1389,"metadata":{"tags":"styles-global","title":"Global styles"},"created_at":"2025-07-18T15:47:38.972Z","updated_at":"2026-02-14T01:33:24.879Z"},{"path":"apps/svelte.dev/content/docs/svelte/04-styling/03-custom-properties.md","title":"Custom properties","filename":"03-custom-properties.md","content":"You can pass CSS custom properties — both static and dynamic — to components:\n\n```svelte\n<Slider\n\tbind:value\n\tmin={0}\n\tmax={100}\n\t--track-color=\"black\"\n\t--thumb-color=\"rgb({r} {g} {b})\"\n/>\n```\n\nThe above code essentially desugars to this:\n\n```svelte\n<svelte-css-wrapper style=\"display: contents; --track-color: black; --thumb-color: rgb({r} {g} {b})\">\n\t<Slider\n\t\tbind:value\n\t\tmin={0}\n\t\tmax={100}\n\t/>\n</svelte-css-wrapper>\n```\n\nFor an SVG element, it would use `<g>` instead:\n\n```svelte\n<g style=\"--track-color: black; --thumb-color: rgb({r} {g} {b})\">\n\t<Slider\n\t\tbind:value\n\t\tmin={0}\n\t\tmax={100}\n\t/>\n</g>\n```\n\nInside the component, we can read these custom properties (and provide fallback values) using [`var(...)`](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties):\n\n```svelte\n<style>\n\t.track {\n\t\tbackground: var(--track-color, #aaa);\n\t}\n\n\t.thumb {\n\t\tbackground: var(--thumb-color, blue);\n\t}\n</style>\n```\n\nYou don't _have_ to specify the values directly on the component; as long as the custom properties are defined on a parent element, the component can use them. It's common to define custom properties on the `:root` element in a global stylesheet so that they apply to your entire application.","size_bytes":1298,"metadata":{"tags":"styles-custom-properties","title":"Custom properties"},"created_at":"2025-07-18T15:47:38.974Z","updated_at":"2026-02-14T01:33:24.880Z"},{"path":"apps/svelte.dev/content/docs/svelte/04-styling/04-nested-style-elements.md","title":"Nested <style> elements","filename":"04-nested-style-elements.md","content":"There can only be one top-level `<style>` tag per component.\n\nHowever, it is possible to have a `<style>` tag nested inside other elements or logic blocks.\n\nIn that case, the `<style>` tag will be inserted as-is into the DOM; no scoping or processing will be done on the `<style>` tag.\n\n```svelte\n<div>\n\t<style>\n\t\t/* this style tag will be inserted as-is */\n\t\tdiv {\n\t\t\t/* this will apply to all `<div>` elements in the DOM */\n\t\t\tcolor: red;\n\t\t}\n\t</style>\n</div>\n```","size_bytes":506,"metadata":{"title":"Nested <style> elements"},"created_at":"2025-07-18T15:47:38.975Z","updated_at":"2025-07-18T15:47:40.266Z"},{"path":"apps/svelte.dev/content/docs/svelte/05-special-elements/01-svelte-boundary.md","title":"<svelte:boundary>","filename":"01-svelte-boundary.md","content":"```svelte\n<svelte:boundary onerror={handler}>...</svelte:boundary>\n```\n\n> This feature was added in 5.3.0\n\nBoundaries allow you to 'wall off' parts of your app, so that you can:\n\n- provide UI that should be shown when [`await`](await-expressions) expressions are first resolving\n- handle errors that occur during rendering or while running effects, and provide UI that should be rendered when an error happens\n\nIf a boundary handles an error (with a `failed` snippet or `onerror` handler, or both) its existing content will be removed.\n\n\n## Properties\n\nFor the boundary to do anything, one or more of the following must be provided.\n\n### `pending`\n\nThis snippet will be shown when the boundary is first created, and will remain visible until all the [`await`](await-expressions) expressions inside the boundary have resolved ([demo](/playground/untitled#H4sIAAAAAAAAE21QQW6DQAz8ytY9BKQVpFdKkPqDHnorPWzAaSwt3tWugUaIv1eE0KpKD5as8YxnNBOw6RAKKOOAVrA4up5bEy6VGknOyiO3xJ8qMnmPAhpOZDFC8T6BXPyiXADQ258X77P1FWg4moj_4Y1jQZZ49W0CealqruXUcyPkWLVozQXbZDC2R606spYiNo7bqA7qab_fp2paFLUElD6wYhzVa3AdRUySgNHZAVN1qDZaLRHljTp0vSTJ9XJjrSbpX5f0eZXN6zLXXOa_QfmurIVU-moyoyH5ib87o7XuYZfOZe6vnGWmx1uZW7lJOq9upa-sMwuUZdkmmfIbfQ1xZwwaBL8ECgk9zh8axJAdiVsoTsZGnL8Bg4tX_OMBAAA=)):\n\n```svelte\n<svelte:boundary>\n\t<p>{await delayed('hello!')}</p>\n\n\t{#snippet pending()}\n\t\t<p>loading...</p>\n\t{/snippet}\n</svelte:boundary>\n```\n\nThe `pending` snippet will _not_ be shown for subsequent async updates — for these, you can use [`$effect.pending()`]($effect#$effect.pending).\n\n\n\n### `failed`\n\nIf a `failed` snippet is provided, it will be rendered when an error is thrown inside the boundary, with the `error` and a `reset` function that recreates the contents ([demo](/playground/hello-world#H4sIAAAAAAAAE3VRy26DMBD8lS2tFCIh6JkAUlWp39Cq9EBg06CAbdlLArL87zWGKk8ORnhmd3ZnrD1WtOjFXqKO2BDGW96xqpBD5gXerm5QefG39mgQY9EIWHxueRMinLosti0UPsJLzggZKTeilLWgLGc51a3gkuCjKQ7DO7cXZotgJ3kLqzC6hmex1SZnSXTWYHcrj8LJjWTk0PHoZ8VqIdCOKayPykcpuQxAokJaG1dGybYj4gw4K5u6PKTasSbjXKgnIDlA8VvUdo-pzonraBY2bsH7HAl78mKSHZpgIcuHjq9jXSpZSLixRlveKYQUXhQVhL6GPobXAAb7BbNeyvNUs4qfRg3OnELLj5hqH9eQZqCnoBwR9lYcQxuVXeBzc8kMF8yXY4yNJ5oGiUzP_aaf_waTRGJib5_Ad3P_vbCuaYxzeNpbU0eUMPAOKh7Yw1YErgtoXyuYlPLzc10_xo_5A91zkQL_AgAA)):\n\n```svelte\n<svelte:boundary>\n\t<FlakyComponent />\n\n\t{#snippet failed(error, reset)}\n\t\t<button onclick={reset}>oops! try again</button>\n\t{/snippet}\n</svelte:boundary>\n```\n\n> As with [snippets passed to components](snippet#Passing-snippets-to-components), the `failed` snippet can be passed explicitly as a property...\n>\n> ```svelte\n> <svelte:boundary {failed}>...</svelte:boundary>\n> ```\n>\n> ...or implicitly by declaring it directly inside the boundary, as in the example above.\n\n### `onerror`\n\nIf an `onerror` function is provided, it will be called with the same two `error` and `reset` arguments. This is useful for tracking the error with an error reporting service...\n\n```svelte\n<svelte:boundary onerror={(e) => report(e)}>\n\t...\n</svelte:boundary>\n```\n\n...or using `error` and `reset` outside the boundary itself:\n\n```svelte\n<script>\n\tlet error = $state(null);\n\tlet reset = $state(() => {});\n\n\tfunction onerror(e, r) {\n\t\terror = e;\n\t\treset = r;\n\t}\n</script>\n\n<svelte:boundary {onerror}>\n\t<FlakyComponent />\n</svelte:boundary>\n\n{#if error}\n\t<button onclick={() => {\n\t\terror = null;\n\t\treset();\n\t}}>\n\t\toops! try again\n\t</button>\n{/if}\n```\n\nIf an error occurs inside the `onerror` function (or if you rethrow the error), it will be handled by a parent boundary if such exists.\n\n## Using `transformError`\n\nBy default, error boundaries have no effect on the server — if an error occurs during rendering, the render as a whole will fail.\n\nSince 5.51 you can control this behaviour for boundaries with a `failed` snippet, by calling [`render(...)`](imperative-component-api#render) with a `transformError` function.\n\n\nThe `transformError` function must return a JSON-stringifiable object which will be used to render the `failed` snippet. This object will be serialized and used to hydrate the snippet in the browser:\n\n```js\n// @errors: 1005\nimport { render } from 'svelte/server';\nimport App from './App.svelte';\n\nconst { head, body } = await render(App, {\n\ttransformError: (error) => {\n\t\t// log the original error, with the stack trace...\n\t\tconsole.error(error);\n\n\t\t// ...and return a sanitized user-friendly error\n\t\t// to display in the `failed` snippet\n\t\treturn {\n\t\t\tmessage: 'An error occurred!'\n\t\t};\n\t};\n});\n```\n\nIf `transformError` throws (or rethrows) an error, `render(...)` as a whole will fail with that error.\n\n\nIf the boundary has an `onerror` handler, it will be called upon hydration with the deserialized error object.\n\nThe [`mount`](imperative-component-api#mount) and [`hydrate`](imperative-component-api#hydrate) functions also accept a `transformError` option, which defaults to the identity function. As with `render`, this function transforms a render-time error before it is passed to a `failed` snippet or `onerror` handler.","size_bytes":5028,"metadata":{"title":"<svelte:boundary>"},"created_at":"2025-07-18T15:47:38.977Z","updated_at":"2026-02-20T02:00:04.578Z"},{"path":"apps/svelte.dev/content/docs/svelte/05-special-elements/02-svelte-window.md","title":"<svelte:window>","filename":"02-svelte-window.md","content":"```svelte\n<svelte:window onevent={handler} />\n```\n\n```svelte\n<svelte:window bind:prop={value} />\n```\n\nThe `<svelte:window>` element allows you to add event listeners to the `window` object without worrying about removing them when the component is destroyed, or checking for the existence of `window` when server-side rendering.\n\nThis element may only appear at the top level of your component — it cannot be inside a block or element.\n\n```svelte\n<script>\n\tfunction handleKeydown(event) {\n\t\talert(`pressed the ${event.key} key`);\n\t}\n</script>\n\n<svelte:window onkeydown={handleKeydown} />\n```\n\nYou can also bind to the following properties:\n\n- `innerWidth`\n- `innerHeight`\n- `outerWidth`\n- `outerHeight`\n- `scrollX`\n- `scrollY`\n- `online` — an alias for `window.navigator.onLine`\n- `devicePixelRatio`\n\nAll except `scrollX` and `scrollY` are readonly.\n\n```svelte\n<svelte:window bind:scrollY={y} />\n```","size_bytes":936,"metadata":{"title":"<svelte:window>"},"created_at":"2025-07-18T15:47:38.978Z","updated_at":"2025-07-18T15:47:40.271Z"},{"path":"apps/svelte.dev/content/docs/svelte/05-special-elements/03-svelte-document.md","title":"<svelte:document>","filename":"03-svelte-document.md","content":"```svelte\n<svelte:document onevent={handler} />\n```\n\n```svelte\n<svelte:document bind:prop={value} />\n```\n\nSimilarly to `<svelte:window>`, this element allows you to add listeners to events on `document`, such as `visibilitychange`, which don't fire on `window`. It also lets you use [attachments](@attach) on `document`.\n\nAs with `<svelte:window>`, this element may only appear the top level of your component and must never be inside a block or element.\n\n```svelte\n<svelte:document onvisibilitychange={handleVisibilityChange} {@attach someAttachment} />\n```\n\nYou can also bind to the following properties:\n\n- `activeElement`\n- `fullscreenElement`\n- `pointerLockElement`\n- `visibilityState`\n\nAll are readonly.","size_bytes":744,"metadata":{"title":"<svelte:document>"},"created_at":"2025-07-18T15:47:38.980Z","updated_at":"2026-02-20T02:00:04.579Z"},{"path":"apps/svelte.dev/content/docs/svelte/05-special-elements/04-svelte-body.md","title":"<svelte:body>","filename":"04-svelte-body.md","content":"```svelte\n<svelte:body onevent={handler} />\n```\n\nSimilarly to `<svelte:window>`, this element allows you to add listeners to events on `document.body`, such as `mouseenter` and `mouseleave`, which don't fire on `window`. It also lets you use [actions](use) on the `<body>` element.\n\nAs with `<svelte:window>` and `<svelte:document>`, this element may only appear at the top level of your component and must never be inside a block or element.\n\n```svelte\n<svelte:body onmouseenter={handleMouseenter} onmouseleave={handleMouseleave} use:someAction />\n```","size_bytes":583,"metadata":{"title":"<svelte:body>"},"created_at":"2025-07-18T15:47:38.981Z","updated_at":"2025-07-18T15:47:40.281Z"},{"path":"apps/svelte.dev/content/docs/svelte/05-special-elements/05-svelte-head.md","title":"<svelte:head>","filename":"05-svelte-head.md","content":"```svelte\n<svelte:head>...</svelte:head>\n```\n\nThis element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content is exposed separately to the main `body` content.\n\nAs with `<svelte:window>`, `<svelte:document>` and `<svelte:body>`, this element may only appear at the top level of your component and must never be inside a block or element.\n\n```svelte\n<svelte:head>\n\t<title>Hello world!</title>\n\t<meta name=\"description\" content=\"This is where the description goes for SEO\" />\n</svelte:head>\n```","size_bytes":576,"metadata":{"title":"<svelte:head>"},"created_at":"2025-07-18T15:47:38.982Z","updated_at":"2025-07-18T15:47:40.282Z"},{"path":"apps/svelte.dev/content/docs/svelte/05-special-elements/06-svelte-element.md","title":"<svelte:element>","filename":"06-svelte-element.md","content":"```svelte\n<svelte:element this={expression} />\n```\n\nThe `<svelte:element>` element lets you render an element that is unknown at author time, for example because it comes from a CMS. Any properties and event listeners present will be applied to the element.\n\nThe only supported binding is `bind:this`, since Svelte's built-in bindings do not work with generic elements.\n\nIf `this` has a nullish value, the element and its children will not be rendered.\n\nIf `this` is the name of a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element) (e.g., `br`) and `<svelte:element>` has child elements, a runtime error will be thrown in development mode:\n\n```svelte\n<script>\n\tlet tag = $state('hr');\n</script>\n\n<svelte:element this={tag}>\n\tThis text cannot appear inside an hr element\n</svelte:element>\n```\n\nSvelte tries its best to infer the correct namespace from the element's surroundings, but it's not always possible. You can make it explicit with an `xmlns` attribute:\n\n```svelte\n<svelte:element this={tag} xmlns=\"http://www.w3.org/2000/svg\" />\n```\n\n`this` needs to be a valid DOM element tag, things like `#text` or `svelte:head` will not work.","size_bytes":1199,"metadata":{"title":"<svelte:element>"},"created_at":"2025-07-18T15:47:38.983Z","updated_at":"2025-07-18T15:47:40.284Z"},{"path":"apps/svelte.dev/content/docs/svelte/05-special-elements/07-svelte-options.md","title":"<svelte:options>","filename":"07-svelte-options.md","content":"```svelte\n<svelte:options option={value} />\n```\n\nThe `<svelte:options>` element provides a place to specify per-component compiler options, which are detailed in the [compiler section](svelte-compiler#compile). The possible options are:\n\n- `runes={true}` — forces a component into _runes mode_ (see the [Legacy APIs](legacy-overview) section)\n- `runes={false}` — forces a component into _legacy mode_\n- `namespace=\"...\"` — the namespace where this component will be used, can be \"html\" (the default), \"svg\" or \"mathml\"\n- `customElement={...}` — the [options](custom-elements#Component-options) to use when compiling this component as a custom element. If a string is passed, it is used as the `tag` option\n- `css=\"injected\"` — the component will inject its styles inline: During server-side rendering, it's injected as a `<style>` tag in the `head`, during client side rendering, it's loaded via JavaScript\n\n> [!LEGACY] Deprecated options\n> Svelte 4 also included the following options. They are deprecated in Svelte 5 and non-functional in runes mode.\n>\n> - `immutable={true}` — you never use mutable data, so the compiler can do simple referential equality checks to determine if values have changed\n> - `immutable={false}` — the default. Svelte will be more conservative about whether or not mutable objects have changed\n> - `accessors={true}` — adds getters and setters for the component's props\n> - `accessors={false}` — the default\n\n```svelte\n<svelte:options customElement=\"my-custom-element\" />\n```","size_bytes":1557,"metadata":{"title":"<svelte:options>"},"created_at":"2025-07-18T15:47:38.984Z","updated_at":"2025-08-06T14:00:06.412Z"},{"path":"apps/svelte.dev/content/docs/svelte/06-runtime/01-stores.md","title":"Stores","filename":"01-stores.md","content":"<!-- - how to use\n- how to write\n- TODO should the details for the store methods belong to the reference section? -->\n\nA _store_ is an object that allows reactive access to a value via a simple _store contract_. The [`svelte/store` module](../svelte-store) contains minimal store implementations which fulfil this contract.\n\nAny time you have a reference to a store, you can access its value inside a component by prefixing it with the `$` character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialisation and unsubscribe when appropriate.\n\nAssignments to `$`-prefixed variables require that the variable be a writable store, and will result in a call to the store's `.set` method.\n\nNote that the store must be declared at the top level of the component — not inside an `if` block or a function, for example.\n\nLocal variables (that do not represent store values) must _not_ have a `$` prefix.\n\n```svelte\n<script>\n\timport { writable } from 'svelte/store';\n\n\tconst count = writable(0);\n\tconsole.log($count); // logs 0\n\n\tcount.set(1);\n\tconsole.log($count); // logs 1\n\n\t$count = 2;\n\tconsole.log($count); // logs 2\n</script>\n```\n\n## When to use stores\n\nPrior to Svelte 5, stores were the go-to solution for creating cross-component reactive states or extracting logic. With runes, these use cases have greatly diminished.\n\n- when extracting logic, it's better to take advantage of runes' universal reactivity: You can use runes outside the top level of components and even place them into JavaScript or TypeScript files (using a `.svelte.js` or `.svelte.ts` file ending)\n- when creating shared state, you can create a `$state` object containing the values you need and then manipulate said state\n\n```ts\n/// file: state.svelte.js\nexport const userState = $state({\n\tname: 'name',\n\t/* ... */\n});\n```\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport { userState } from './state.svelte.js';\n</script>\n\n<p>User name: {userState.name}</p>\n<button onclick={() => {\n\tuserState.name = 'new name';\n}}>\n\tchange name\n</button>\n```\n\nStores are still a good solution when you have complex asynchronous data streams or it's important to have more manual control over updating values or listening to changes. If you're familiar with RxJs and want to reuse that knowledge, the `$` also comes in handy for you.\n\n## svelte/store\n\nThe `svelte/store` module contains a minimal store implementation which fulfil the store contract. It provides methods for creating stores that you can update from the outside, stores you can only update from the inside, and for combining and deriving stores.\n\n### `writable`\n\nFunction that creates a store which has values that can be set from 'outside' components. It gets created as an object with additional `set` and `update` methods.\n\n`set` is a method that takes one argument which is the value to be set. The store value gets set to the value of the argument if the store value is not already equal to it.\n\n`update` is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.\n\n```js\n/// file: store.js\nimport { writable } from 'svelte/store';\n\nconst count = writable(0);\n\ncount.subscribe((value) => {\n\tconsole.log(value);\n}); // logs '0'\n\ncount.set(1); // logs '1'\n\ncount.update((n) => n + 1); // logs '2'\n```\n\nIf a function is passed as the second argument, it will be called when the number of subscribers goes from zero to one (but not from one to two, etc). That function will be passed a `set` function which changes the value of the store, and an `update` function which works like the `update` method on the store, taking a callback to calculate the store's new value from its old value. It must return a `stop` function that is called when the subscriber count goes from one to zero.\n\n```js\n/// file: store.js\nimport { writable } from 'svelte/store';\n\nconst count = writable(0, () => {\n\tconsole.log('got a subscriber');\n\treturn () => console.log('no more subscribers');\n});\n\ncount.set(1); // does nothing\n\nconst unsubscribe = count.subscribe((value) => {\n\tconsole.log(value);\n}); // logs 'got a subscriber', then '1'\n\nunsubscribe(); // logs 'no more subscribers'\n```\n\nNote that the value of a `writable` is lost when it is destroyed, for example when the page is refreshed. However, you can write your own logic to sync the value to for example the `localStorage`.\n\n### `readable`\n\nCreates a store whose value cannot be set from 'outside', the first argument is the store's initial value, and the second argument to `readable` is the same as the second argument to `writable`.\n\n```ts\nimport { readable } from 'svelte/store';\n\nconst time = readable(new Date(), (set) => {\n\tset(new Date());\n\n\tconst interval = setInterval(() => {\n\t\tset(new Date());\n\t}, 1000);\n\n\treturn () => clearInterval(interval);\n});\n\nconst ticktock = readable('tick', (set, update) => {\n\tconst interval = setInterval(() => {\n\t\tupdate((sound) => (sound === 'tick' ? 'tock' : 'tick'));\n\t}, 1000);\n\n\treturn () => clearInterval(interval);\n});\n```\n\n### `derived`\n\nDerives a store from one or more other stores. The callback runs initially when the first subscriber subscribes and then whenever the store dependencies change.\n\nIn the simplest version, `derived` takes a single store, and the callback returns a derived value.\n\n```ts\n// @filename: ambient.d.ts\nimport { type Writable } from 'svelte/store';\n\ndeclare global {\n\tconst a: Writable<number>;\n}\n\nexport {};\n\n// @filename: index.ts\n//cut\nimport { derived } from 'svelte/store';\n\nconst doubled = derived(a, ($a) => $a * 2);\n```\n\nThe callback can set a value asynchronously by accepting a second argument, `set`, and an optional third argument, `update`, calling either or both of them when appropriate.\n\nIn this case, you can also pass a third argument to `derived` — the initial value of the derived store before `set` or `update` is first called. If no initial value is specified, the store's initial value will be `undefined`.\n\n```ts\n// @filename: ambient.d.ts\nimport { type Writable } from 'svelte/store';\n\ndeclare global {\n\tconst a: Writable<number>;\n}\n\nexport {};\n\n// @filename: index.ts\n// @errors: 18046 2769 7006\n//cut\nimport { derived } from 'svelte/store';\n\nconst delayed = derived(\n\ta,\n\t($a, set) => {\n\t\tsetTimeout(() => set($a), 1000);\n\t},\n\t2000\n);\n\nconst delayedIncrement = derived(a, ($a, set, update) => {\n\tset($a);\n\tsetTimeout(() => update((x) => x + 1), 1000);\n\t// every time $a produces a value, this produces two\n\t// values, $a immediately and then $a + 1 a second later\n});\n```\n\nIf you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.\n\n```ts\n// @filename: ambient.d.ts\nimport { type Writable } from 'svelte/store';\n\ndeclare global {\n\tconst frequency: Writable<number>;\n}\n\nexport {};\n\n// @filename: index.ts\n//cut\nimport { derived } from 'svelte/store';\n\nconst tick = derived(\n\tfrequency,\n\t($frequency, set) => {\n\t\tconst interval = setInterval(() => {\n\t\t\tset(Date.now());\n\t\t}, 1000 / $frequency);\n\n\t\treturn () => {\n\t\t\tclearInterval(interval);\n\t\t};\n\t},\n\t2000\n);\n```\n\nIn both cases, an array of arguments can be passed as the first argument instead of a single store.\n\n```ts\n// @filename: ambient.d.ts\nimport { type Writable } from 'svelte/store';\n\ndeclare global {\n\tconst a: Writable<number>;\n\tconst b: Writable<number>;\n}\n\nexport {};\n\n// @filename: index.ts\n\n//cut\nimport { derived } from 'svelte/store';\n\nconst summed = derived([a, b], ([$a, $b]) => $a + $b);\n\nconst delayed = derived([a, b], ([$a, $b], set) => {\n\tsetTimeout(() => set($a + $b), 1000);\n});\n```\n\n### `readonly`\n\nThis simple helper function makes a store readonly. You can still subscribe to the changes from the original one using this new readable store.\n\n```js\nimport { readonly, writable } from 'svelte/store';\n\nconst writableStore = writable(1);\nconst readableStore = readonly(writableStore);\n\nreadableStore.subscribe(console.log);\n\nwritableStore.set(2); // console: 2\n// @errors: 2339\nreadableStore.set(2); // ERROR\n```\n\n### `get`\n\nGenerally, you should read the value of a store by subscribing to it and using the value as it changes over time. Occasionally, you may need to retrieve the value of a store to which you're not subscribed. `get` allows you to do so.\n\n\n```ts\n// @filename: ambient.d.ts\nimport { type Writable } from 'svelte/store';\n\ndeclare global {\n\tconst store: Writable<string>;\n}\n\nexport {};\n\n// @filename: index.ts\n//cut\nimport { get } from 'svelte/store';\n\nconst value = get(store);\n```\n\n## Store contract\n\n```ts\n// @noErrors\nstore = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void }\n```\n\nYou can create your own stores without relying on [`svelte/store`](../svelte-store), by implementing the _store contract_:\n\n1. A store must contain a `.subscribe` method, which must accept as its argument a subscription function. This subscription function must be immediately and synchronously called with the store's current value upon calling `.subscribe`. All of a store's active subscription functions must later be synchronously called whenever the store's value changes.\n2. The `.subscribe` method must return an unsubscribe function. Calling an unsubscribe function must stop its subscription, and its corresponding subscription function must not be called again by the store.\n3. A store may _optionally_ contain a `.set` method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. Such a store is called a _writable store_.\n\nFor interoperability with RxJS Observables, the `.subscribe` method is also allowed to return an object with an `.unsubscribe` method, rather than return the unsubscription function directly. Note however that unless `.subscribe` synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as `undefined` until it does.","size_bytes":10056,"metadata":{"title":"Stores"},"created_at":"2025-07-18T15:47:38.986Z","updated_at":"2025-07-18T15:47:40.288Z"},{"path":"apps/svelte.dev/content/docs/svelte/06-runtime/02-context.md","title":"Context","filename":"02-context.md","content":"Context allows components to access values owned by parent components without passing them down as props (potentially through many layers of intermediate components, known as 'prop-drilling'). The parent component sets context with `setContext(key, value)`...\n\n```svelte\n<!file: Parent.svelte>\n<script>\n\timport { setContext } from 'svelte';\n\n\tsetContext('my-context', 'hello from Parent.svelte');\n</script>\n```\n\n...and the child retrieves it with `getContext`:\n\n```svelte\n<!file: Child.svelte>\n<script>\n\timport { getContext } from 'svelte';\n\n\tconst message = getContext('my-context');\n</script>\n\n<h1>{message}, inside Child.svelte</h1>\n```\n\nThis is particularly useful when `Parent.svelte` is not directly aware of `Child.svelte`, but instead renders it as part of a `children` [snippet](snippet) ([demo](/playground/untitled#H4sIAAAAAAAAE42Q3W6DMAyFX8WyJgESK-oto6hTX2D3YxcM3IIUQpR40yqUd58CrCXsp7tL7HNsf2dAWXaEKR56yfTBGOOxFWQwfR6Qz8q1XAHjL-GjUhvzToJd7bU09FO9ctMkG0wxM5VuFeeFLLjtVK8ZnkpNkuGo-w6CTTJ9Z3PwsBAemlbUF934W8iy5DpaZtOUcU02-ZLcaS51jHEkTFm_kY1_wfOO8QnXrb8hBzDEc6pgZ4gFoyz4KgiD7nxfTe8ghqAhIfrJ46cTzVZBbkPlODVJsLCDO6V7ZcJoncyw1yRr0hd1GNn_ZbEM3I9i1bmVxOlWElUvDUNHxpQngt3C4CXzjS1rtvkw22wMrTRtTbC8Lkuabe7jvthPPe3DofYCAAA=)):\n\n```svelte\n<Parent>\n\t<Child />\n</Parent>\n```\n\nThe key (`'my-context'`, in the example above) and the context itself can be any JavaScript value.\n\nIn addition to [`setContext`](svelte#setContext) and [`getContext`](svelte#getContext), Svelte exposes [`hasContext`](svelte#hasContext) and [`getAllContexts`](svelte#getAllContexts) functions.\n\n## Using context with state\n\nYou can store reactive state in context ([demo](/playground/untitled#H4sIAAAAAAAAE41R0W6DMAz8FSuaBNUQdK8MkKZ-wh7HHihzu6hgosRMm1D-fUpSVNq12x4iEvvOx_kmQU2PIhfP3DCCJGgHYvxkkYid7NCI_GUS_KUcxhVEMjOelErNB3bsatvG4LW6n0ZsRC4K02qpuKqpZtmrQTNMYJA3QRAs7PTQQxS40eMCt3mX3duxnWb-lS5h7nTI0A4jMWoo4c44P_Hku-zrOazdy64chWo-ScfRkRgl8wgHKrLTH1OxHZkHgoHaTraHcopXUFYzPPVfuC_hwQaD1GrskdiNCdQwJljJqlvXfyqVsA5CGg0uRUQifHw56xFtciO75QrP07vo_JXf_tf8yK2ezDKY_ZWt_1y2qqYzv7bI1IW1V_sN19m-07wCAAA=))...\n\n```svelte\n<script>\n\timport { setContext } from 'svelte';\n\timport Child from './Child.svelte';\n\n\tlet counter = $state({\n\t\tcount: 0\n\t});\n\n\tsetContext('counter', counter);\n</script>\n\n<button onclick={() => counter.count += 1}>\n\tincrement\n</button>\n\n<Child />\n<Child />\n<Child />\n```\n\n...though note that if you _reassign_ `counter` instead of updating it, you will 'break the link' — in other words instead of this...\n\n```svelte\n<button onclick={() => counter = { count: 0 }}>\n\treset\n</button>\n```\n\n...you must do this:\n\n```svelte\n<button onclick={() =>counter.count = 0}>\n\treset\n</button>\n```\n\nSvelte will warn you if you get it wrong.\n\n## Type-safe context\n\nAs an alternative to using `setContext` and `getContext` directly, you can use them via `createContext`. This gives you type safety and makes it unnecessary to use a key:\n\n```ts\n/// file: context.ts\n// @filename: ambient.d.ts\ninterface User {}\n\n// @filename: index.ts\n//cut\nimport { createContext } from 'svelte';\n\nexport const [getUserContext, setUserContext] = createContext<User>();\n```\n\nWhen writing [component tests](testing#Unit-and-component-tests-with-Vitest-Component-testing), it can be useful to create a wrapper component that sets the context in order to check the behaviour of a component that uses it. As of version 5.49, you can do this sort of thing:\n\n```js\nimport { mount, unmount } from 'svelte';\nimport { expect, test } from 'vitest';\nimport { setUserContext } from './context';\nimport MyComponent from './MyComponent.svelte';\n\ntest('MyComponent', () => {\n\tfunction Wrapper(...args) {\n\t\tsetUserContext({ name: 'Bob' });\n\t\treturn MyComponent(...args);\n\t}\n\n\tconst component = mount(Wrapper, {\n\t\ttarget: document.body\n\t});\n\n\texpect(document.body.innerHTML).toBe('<h1>Hello Bob!</h1>');\n\n\tunmount(component);\n});\n```\n\nThis approach also works with [`hydrate`](imperative-component-api#hydrate) and [`render`](imperative-component-api#render).\n\n## Replacing global state\n\nWhen you have state shared by many different components, you might be tempted to put it in its own module and just import it wherever it's needed:\n\n```js\n/// file: state.svelte.js\nexport const myGlobalState = $state({\n\tuser: {\n\t\t// ...\n\t}\n\t// ...\n});\n```\n\nIn many cases this is perfectly fine, but there is a risk: if you mutate the state during server-side rendering (which is discouraged, but entirely possible!)...\n\n```svelte\n<!file: App.svelte->\n<script>\n\timport { myGlobalState } from './state.svelte.js';\n\n\tlet { data } = $props();\n\n\tif (data.user) {\n\t\tmyGlobalState.user = data.user;\n\t}\n</script>\n```\n\n...then the data may be accessible by the _next_ user. Context solves this problem because it is not shared between requests.","size_bytes":4773,"metadata":{"title":"Context"},"created_at":"2025-07-18T15:47:38.987Z","updated_at":"2026-02-14T01:33:24.881Z"},{"path":"apps/svelte.dev/content/docs/svelte/06-runtime/03-lifecycle-hooks.md","title":"Lifecycle hooks","filename":"03-lifecycle-hooks.md","content":"<!-- - onMount/onDestroy\n- mention that `$effect` might be better for your use case\n- beforeUpdate/afterUpdate with deprecation notice?\n- or skip this entirely and only have it in the reference docs? -->\n\nIn Svelte 5, the component lifecycle consists of only two parts: Its creation and its destruction. Everything in-between — when certain state is updated — is not related to the component as a whole; only the parts that need to react to the state change are notified. This is because under the hood the smallest unit of change is actually not a component, it's the (render) effects that the component sets up upon component initialization. Consequently, there's no such thing as a \"before update\"/\"after update\" hook.\n\n## `onMount`\n\nThe `onMount` function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initialisation (but doesn't need to live _inside_ the component; it can be called from an external module).\n\n`onMount` does not run inside a component that is rendered on the server.\n\n```svelte\n<script>\n\timport { onMount } from 'svelte';\n\n\tonMount(() => {\n\t\tconsole.log('the component has mounted');\n\t});\n</script>\n```\n\nIf a function is returned from `onMount`, it will be called when the component is unmounted.\n\n```svelte\n<script>\n\timport { onMount } from 'svelte';\n\n\tonMount(() => {\n\t\tconst interval = setInterval(() => {\n\t\t\tconsole.log('beep');\n\t\t}, 1000);\n\n\t\treturn () => clearInterval(interval);\n\t});\n</script>\n```\n\n\n## `onDestroy`\n\nSchedules a callback to run immediately before the component is unmounted.\n\nOut of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the only one that runs inside a server-side component.\n\n```svelte\n<script>\n\timport { onDestroy } from 'svelte';\n\n\tonDestroy(() => {\n\t\tconsole.log('the component is being destroyed');\n\t});\n</script>\n```\n\n## `tick`\n\nWhile there's no \"after update\" hook, you can use `tick` to ensure that the UI is updated before continuing. `tick` returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.\n\n```svelte\n<script>\n\timport { tick } from 'svelte';\n\n\t$effect.pre(() => {\n\t\tconsole.log('the component is about to update');\n\t\ttick().then(() => {\n\t\t\t\tconsole.log('the component just updated');\n\t\t});\n\t});\n</script>\n```\n\n## Deprecated: `beforeUpdate` / `afterUpdate`\n\nSvelte 4 contained hooks that ran before and after the component as a whole was updated. For backwards compatibility, these hooks were shimmed in Svelte 5 but not available inside components that use runes.\n\n```svelte\n<script>\n\timport { beforeUpdate, afterUpdate } from 'svelte';\n\n\tbeforeUpdate(() => {\n\t\tconsole.log('the component is about to update');\n\t});\n\n\tafterUpdate(() => {\n\t\tconsole.log('the component just updated');\n\t});\n</script>\n```\n\nInstead of `beforeUpdate` use `$effect.pre` and instead of `afterUpdate` use `$effect` instead — these runes offer more granular control and only react to the changes you're actually interested in.\n\n### Chat window example\n\nTo implement a chat window that autoscrolls to the bottom when new messages appear (but only if you were _already_ scrolled to the bottom), we need to measure the DOM before we update it.\n\nIn Svelte 4, we do this with `beforeUpdate`, but this is a flawed approach — it fires before _every_ update, whether it's relevant or not. In the example below, we need to introduce checks like `updatingMessages` to make sure we don't mess with the scroll position when someone toggles dark mode.\n\nWith runes, we can use `$effect.pre`, which behaves the same as `$effect` but runs before the DOM is updated. As long as we explicitly reference `messages` inside the effect body, it will run whenever `messages` changes, but _not_ when `theme` changes.\n\n`beforeUpdate`, and its equally troublesome counterpart `afterUpdate`, are therefore deprecated in Svelte 5.\n\n- [Before](/playground/untitled#H4sIAAAAAAAAE31WXa_bNgz9K6yL1QmWOLlrC-w6H8MeBgwY9tY9NfdBtmlbiywZkpyPBfnvo2zLcZK28AWuRPGI5OGhkEuQc4EmiL9eAskqDOLg97oOZoE9125jDigs0t6oRqfOsjap5rXd7uTO8qpW2sIFEsyVxn_qjFmcAcstar-xPN3DFXKtKgi768IVgQku0ELj3Lgs_kZjWIEGNpAzYXDlHWyJFZI1zJjeh4O5uvl_DY8oUkVeVoFuJKYls-_CGYS25Aboj0EtWNqel0wWoBoLTGZgmdgDS9zW4Uz4NsrswPHoyutN4xInkylstnBxdmIhh8m7xzqmoNE2Wq46n1RJQzEbq4g-JQSl7e-HDx-GdaTy3KD9E3lRWvj5Zu9QX1QN20dj7zyHz8s-1S6lW7Cpz3RnXTcm04hIlfdFuO8p2mQ5-3a06cqjrn559bF_2NHOnRZ5I1PLlXQNyQT-hedMHeUEDyjtdMxsa4n2eIbNhlTwhyRthaOKOmYtniwF6pwt0wXa6MBEg0OibZec27gz_dk3UrZ6hB2LLYoiv521Yd8Gt-foTrfhiCDP0lC9VUUhcDLU49Xe_9943cNvEArHfAjxeBTovvXiNpFynfEDpIIZs9kFbg52QbeNHWZzebz32s7xHco3nJAJl1nshmhz8dYOQJDyZetnbb2gTWe-vEeWlrfpZMavr56ldb29eNt6UXvgwgFbp_WC0tl2RK25rGk6lYz3nUI2lzvBXGHhPZPGWmKUXFNBKqdaW259wl_aHbiqoVIZdpE60Nax6IOujT0LbFFxIVTCxCRR2XloUcYNvSbnGHKBp763jHoj59xiZWJI0Wm0P_m3MSS985xkasn-cFq20xTDy3J5KFcjgUTD69BHdcHIjz431z28IqlxGcPSfdFnrGDZn6gD6lyo45zyHAD-btczf-98nhQxHEvKfeUtOVkSejD3q-9X7JbzjGtsdUxlKdFU8qGsT78uaw848syWMXz85Waq2Gnem4mAn3prweq4q6Y3JEpnqMmnPoFRgmd3ySW0LLRqSKlwYHriCvJvUs2yjMaaoA-XzTXLeGMe45zmhv_XAno3Mj0xF7USuqNvnE9H343QHlq-eAgxpbTPNR9yzUkgLjwSR0NK4wKoxy-jDg-9vy8sUSToakzW-9fX13Em9Q8T6Z26uZhBN36XUYo5q7ggLXBZoub2Ofv7g6GCZfTxe034NCjiudXj7Omla0eTfo7QBPOcYxbE7qG-vl3_B1G-_i_JCAAA)\n- [After](/playground/untitled#H4sIAAAAAAAAE31WXa-jNhD9K7PsdknUQJLurtRLPqo-VKrU1327uQ8GBnBjbGSb5KZR_nvHgMlXtyIS9njO-MyZGZRzUHCBJkhez4FkNQZJ8HvTBLPAnhq3MQcUFmlvVKszZ1mbTPPGbndyZ3ndKG3hDJZne7hAoVUNYY8JV-RBPgIt2AprhA18MpZZnIQ50_twuvLHNRrDSjRXj9fwiCJTBLIKdCsxq5j9EM4gtBU3QD8GjWBZd14xWYJqLTCZg2ViDyx1W4cz4dv0hsiB49FRHkyfsCgws3GjcTKZwmYLZ2feWc9o1W8zJQ2Fb62i5JUQRNRHgs-fx3WsisKg_RN5WVn4-WrvUd9VA9tH4-AcwbfFQIpkLWByvWzqSe2sk3kyjUlOec_XPU-3TRaz_75tuvKoi19e3OvipSpamVmupJM2F_gXnnJ1lBM8oLQjHceys8R7PMFms4HwD2lRhzeEe-EsvluSrHe2TJdo4wMTLY48XKwPzm0KGm2r5ajFtRYU4TWOY7-ddWHfxhDP0QkQhnf5PWRnVVkKnIx8fZsOb5dR16nwG4TCCRdCMphWQ7z1_DoOcp3zA2SCGbPZBa5jd0G_TRxmc36Me-mG6A7l60XIlMs8ce2-OXtrDyBItdz6qVjPadObzx-RZdV1nJjx64tXad1sz962njceOHfAzmk9JzrbXqg1lw3NkZL7vgE257t-uMDcO6attSSokpmgFqVMO2U93e_dDlzOUKsc-3t6zNZp6K9cG3sS2KGSUqiUiUmq8tNYoJwbmvpTAoXA96GyjCojI26xNglk6DpwOPm7NdRYp4ia0JL94bTqRiGB5WJxqFY37RGPoz3c6i4jP3rcUA7wmhqNywQW7om_YQ2L4UQdUBdCHSPiOQJ8bFcxHzeK0jKBY0XcV95SkCWlD9t-9eOM3TLKucauiyktJdpaPqT19ddF4wFHntsqgS-_XE01e48GMwnw02AtWZP02QyGVOkcNfk072CU4PkduZSWpVYt9SkcmJ64hPwHpWF5ziVls3wIFmmW89Y83vMeGf5PBxjcyPSkXNy10J18t3x6-a6CDtBq6SGklNKeazFyLahB3PVIGo2UbhOgGi9vKjzW_j6xVFFD17difXx5ebll0vwvkcGpn4sZ9MN3vqFYsJoL6gUuK9TcPrO_PxgzWMRfflSEr2NHPJf6lj1957rRpH8CNMG84JgHidUtXt4u_wK21LXERAgAAA==)\n\n```svelte\n<script>\n\timport {beforeUpdate, afterUpdate,tick } from 'svelte';\n\n\tlet updatingMessages = false;\n\tlet theme =$state('dark');\n\tlet messages =$state([]);\n\n\tlet viewport;\n\n\tbeforeUpdate(() => {\n\t$effect.pre(() => {\n\t\tif (!updatingMessages) return;\n\t\tmessages;\n\t\tconst autoscroll = viewport && viewport.offsetHeight + viewport.scrollTop > viewport.scrollHeight - 50;\n\n\t\tif (autoscroll) {\n\t\t\ttick().then(() => {\n\t\t\t\tviewport.scrollTo(0, viewport.scrollHeight);\n\t\t\t});\n\t\t}\n\n\t\tupdatingMessages = false;\n\t});\n\n\tfunction handleKeydown(event) {\n\t\tif (event.key === 'Enter') {\n\t\t\tconst text = event.target.value;\n\t\t\tif (!text) return;\n\n\t\t\tupdatingMessages = true;\n\t\t\tmessages = [...messages, text];\n\t\t\tevent.target.value = '';\n\t\t}\n\t}\n\n\tfunction toggle() {\n\t\ttheme = theme === 'dark' ? 'light' : 'dark';\n\t}\n</script>\n\n<div class:dark={theme === 'dark'}>\n\t<div bind:this={viewport}>\n\t\t{#each messages as message}\n\t\t\t<p>{message}</p>\n\t\t{/each}\n\t</div>\n\n\t<inputonkeydown={handleKeydown} />\n\n\t<buttononclick={toggle}> Toggle dark mode </button>\n</div>\n```","size_bytes":7578,"metadata":{"title":"Lifecycle hooks"},"created_at":"2025-07-18T15:47:38.988Z","updated_at":"2025-11-26T14:00:04.202Z"},{"path":"apps/svelte.dev/content/docs/svelte/06-runtime/04-imperative-component-api.md","title":"Imperative component API","filename":"04-imperative-component-api.md","content":"<!-- better title needed?\n\n- mount\n- unmount\n- render\n- hydrate\n- how they interact with each other -->\n\nEvery Svelte application starts by imperatively creating a root component. On the client this component is mounted to a specific element. On the server, you want to get back a string of HTML instead which you can render. The following functions help you achieve those tasks.\n\n## `mount`\n\nInstantiates a component and mounts it to the given target:\n\n```js\n// @errors: 2322\nimport { mount } from 'svelte';\nimport App from './App.svelte';\n\nconst app = mount(App, {\n\ttarget: document.querySelector('#app'),\n\tprops: { some: 'property' }\n});\n```\n\nYou can mount multiple components per page, and you can also mount from within your application, for example when creating a tooltip component and attaching it to the hovered element.\n\nNote that unlike calling `new App(...)` in Svelte 4, things like effects (including `onMount` callbacks, and action functions) will not run during `mount`. If you need to force pending effects to run (in the context of a test, for example) you can do so with `flushSync()`.\n\n## `unmount`\n\nUnmounts a component that was previously created with [`mount`](#mount) or [`hydrate`](#hydrate).\n\nIf `options.outro` is `true`, [transitions](transition) will play before the component is removed from the DOM:\n\n```js\nimport { mount, unmount } from 'svelte';\nimport App from './App.svelte';\n\nconst app = mount(App, { target: document.body });\n\n// later\nunmount(app, { outro: true });\n```\n\nReturns a `Promise` that resolves after transitions have completed if `options.outro` is true, or immediately otherwise.\n\n## `render`\n\nOnly available on the server and when compiling with the `server` option. Takes a component and returns an object with `body` and `head` properties on it, which you can use to populate the HTML when server-rendering your app:\n\n```js\n// @errors: 2724 2305 2307\nimport { render } from 'svelte/server';\nimport App from './App.svelte';\n\nconst result = render(App, {\n\tprops: { some: 'property' }\n});\nresult.body; // HTML for somewhere in this <body> tag\nresult.head; // HTML for somewhere in this <head> tag\n```\n\n## `hydrate`\n\nLike `mount`, but will reuse up any HTML rendered by Svelte's SSR output (from the [`render`](#render) function) inside the target and make it interactive:\n\n```js\n// @errors: 2322\nimport { hydrate } from 'svelte';\nimport App from './App.svelte';\n\nconst app = hydrate(App, {\n\ttarget: document.querySelector('#app'),\n\tprops: { some: 'property' }\n});\n```\n\nAs with `mount`, effects will not run during `hydrate` — use `flushSync()` immediately afterwards if you need them to.","size_bytes":2681,"metadata":{"title":"Imperative component API"},"created_at":"2025-07-18T15:47:38.992Z","updated_at":"2025-07-18T15:47:40.293Z"},{"path":"apps/svelte.dev/content/docs/svelte/06-runtime/05-hydratable.md","title":"Hydratable data","filename":"05-hydratable.md","content":"In Svelte, when you want to render asynchronous content data on the server, you can simply `await` it. This is great! However, it comes with a pitfall: when hydrating that content on the client, Svelte has to redo the asynchronous work, which blocks hydration for however long it takes:\n\n```svelte\n<script>\n  import { getUser } from 'my-database-library';\n\n  // This will get the user on the server, render the user's name into the h1,\n  // and then, during hydration on the client, it will get the user _again_,\n  // blocking hydration until it's done.\n  const user = await getUser();\n</script>\n\n<h1>{user.name}</h1>\n```\n\nThat's silly, though. If we've already done the hard work of getting the data on the server, we don't want to get it again during hydration on the client. `hydratable` is a low-level API built to solve this problem. You probably won't need this very often — it will be used behind the scenes by whatever datafetching library you use. For example, it powers [remote functions in SvelteKit](/docs/kit/remote-functions).\n\nTo fix the example above:\n\n```svelte\n<script>\n  import { hydratable } from 'svelte';\n  import { getUser } from 'my-database-library';\n\n  // During server rendering, this will serialize and stash the result of `getUser`, associating\n  // it with the provided key and baking it into the `head` content. During hydration, it will\n  // look for the serialized version, returning it instead of running `getUser`. After hydration\n  // is done, if it's called again, it'll simply invoke `getUser`.\n  const user = await hydratable('user', () => getUser());\n</script>\n\n<h1>{user.name}</h1>\n```\n\nThis API can also be used to provide access to random or time-based values that are stable between server rendering and hydration. For example, to get a random number that doesn't update on hydration:\n\n```ts\nimport { hydratable } from 'svelte';\nconst rand = hydratable('random', () => Math.random());\n```\n\nIf you're a library author, be sure to prefix the keys of your `hydratable` values with the name of your library so that your keys don't conflict with other libraries.\n\n## Serialization\n\nAll data returned from a `hydratable` function must be serializable. But this doesn't mean you're limited to JSON — Svelte uses [`devalue`](https://npmjs.com/package/devalue), which can serialize all sorts of things including `Map`, `Set`, `URL`, and `BigInt`. Check the documentation page for a full list. In addition to these, thanks to some Svelte magic, you can also fearlessly use promises:\n\n```svelte\n<script>\n  import { hydratable } from 'svelte';\n  const promises = hydratable('random', () => {\n    return {\n      one: Promise.resolve(1),\n      two: Promise.resolve(2)\n    }\n  });\n</script>\n\n{await promises.one}\n{await promises.two}\n```\n\n## CSP\n\n`hydratable` adds an inline `<script>` block to the `head` returned from `render`. If you're using [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) (CSP), this script will likely fail to run. You can provide a `nonce` to `render`:\n\n```js\n/// file: server.js\nimport { render } from 'svelte/server';\nimport App from './App.svelte';\n//cut\nconst nonce = crypto.randomUUID();\n\nconst { head, body } = await render(App, {\n\tcsp: { nonce }\n});\n```\n\nThis will add the `nonce` to the script block, on the assumption that you will later add the same nonce to the CSP header of the document that contains it:\n\n```js\n/// file: server.js\nlet response = new Response();\nlet nonce = 'xyz123';\n//cut\nresponse.headers.set(\n  'Content-Security-Policy',\n  `script-src 'nonce-${nonce}'`\n );\n```\n\nIt's essential that a `nonce` — which, British slang definition aside, means 'number used once' — is only used when dynamically server rendering an individual response.\n\nIf instead you are generating static HTML ahead of time, you must use hashes instead:\n\n```js\n/// file: server.js\nimport { render } from 'svelte/server';\nimport App from './App.svelte';\n//cut\nconst { head, body, hashes } = await render(App, {\n\tcsp: { hash: true }\n});\n```\n\n`hashes.script` will be an array of strings like `[\"sha256-abcd123\"]`. As with `nonce`, the hashes should be used in your CSP header:\n\n```js\n/// file: server.js\nlet response = new Response();\nlet hashes = { script: ['sha256-xyz123'] };\n//cut\nresponse.headers.set(\n  'Content-Security-Policy',\n  `script-src ${hashes.script.map((hash) => `'${hash}'`).join(' ')}`\n );\n```\n\nWe recommend using `nonce` over hash if you can, as `hash` will interfere with streaming SSR in the future.","size_bytes":4550,"metadata":{"title":"Hydratable data"},"created_at":"2025-11-26T14:00:04.242Z","updated_at":"2025-12-20T02:00:04.435Z"},{"path":"apps/svelte.dev/content/docs/svelte/07-misc/01-best-practices.md","title":"Best practices","filename":"01-best-practices.md","content":"<!-- llm-ignore-start -->\nThis document outlines some best practices that will help you write fast, robust Svelte apps. It is also available as a `svelte-core-bestpractices` skill for your agents.\n<!-- llm-ignore-end -->\n\n## `$state`\n\nOnly use the `$state` rune for variables that should be _reactive_ — in other words, variables that cause an `$effect`, `$derived` or template expression to update. Everything else can be a normal variable.\n\nObjects and arrays (`$state({...})` or `$state([...])`) are made deeply reactive, meaning mutation will trigger updates. This has a trade-off: in exchange for fine-grained reactivity, the objects must be proxied, which has performance overhead. In cases where you're dealing with large objects that are only ever reassigned (rather than mutated), use `$state.raw` instead. This is often the case with API responses, for example.\n\n## `$derived`\n\nTo compute something from state, use `$derived` rather than `$effect`:\n\n```js\n// @errors: 2451\nlet num = 0;\n//cut\n// do this\nlet square = $derived(num * num);\n\n// don't do this\nlet square;\n\n$effect(() => {\n\tsquare = num * num;\n});\n```\n\n\nDeriveds are writable — you can assign to them, just like `$state`, except that they will re-evaluate when their expression changes.\n\nIf the derived expression is an object or array, it will be returned as-is — it is _not_ made deeply reactive. You can, however, use `$state` inside `$derived.by` in the rare cases that you need this.\n\n## `$effect`\n\nEffects are an escape hatch and should mostly be avoided. In particular, avoid updating state inside effects.\n\n- If you need to sync state to an external library such as D3, it is often neater to use [`{@attach ...}`](@attach)\n- If you need to run some code in response to user interaction, put the code directly in an event handler or use a [function binding](bind#Function-bindings) as appropriate\n- If you need to log values for debugging purposes, use [`$inspect`]($inspect)\n- If you need to observe something external to Svelte, use [`createSubscriber`](svelte-reactivity#createSubscriber)\n\nNever wrap the contents of an effect in `if (browser) {...}` or similar — effects do not run on the server.\n\n## `$props`\n\nTreat props as though they will change. For example, values that depend on props should usually use `$derived`:\n\n```js\n// @errors: 2451\nlet { type } = $props();\n\n// do this\nlet color = $derived(type === 'danger' ? 'red' : 'green');\n\n// don't do this — `color` will not update if `type` changes\nlet color = type === 'danger' ? 'red' : 'green';\n```\n\n## `$inspect.trace`\n\n`$inspect.trace` is a debugging tool for reactivity. If something is not updating properly or running more than it should you can add `$inspect.trace(label)` as the first line of an `$effect` or `$derived.by` (or any function they call) to trace their dependencies and discover which one triggered an update.\n\n## Events\n\nAny element attribute starting with `on` is treated as an event listener:\n\n```svelte\n<button onclick={() => {...}}>click me</button>\n\n<!-- attribute shorthand also works -->\n<button {onclick}>...</button>\n\n<!-- so do spread attributes -->\n<button {...props}>...</button>\n```\n\nIf you need to attach listeners to `window` or `document` you can use `<svelte:window>` and `<svelte:document>`:\n\n```svelte\n<svelte:window onkeydown={...} />\n<svelte:document onvisibilitychange={...} />\n```\n\nAvoid using `onMount` or `$effect` for this.\n\n## Snippets\n\n[Snippets](snippet) are a way to define reusable chunks of markup that can be instantiated with the [`{@render ...}`](@render) tag, or passed to components as props. They must be declared within the template.\n\n```svelte\n{#snippet greeting(name)}\n  <p>hello {name}!</p>\n{/snippet}\n\n{@render greeting('world')}\n```\n\n\n## Each blocks\n\nPrefer to use [keyed each blocks](each#Keyed-each-blocks) — this improves performance by allowing Svelte to surgically insert or remove items rather than updating the DOM belonging to existing items.\n\n\nAvoid destructuring if you need to mutate the item (with something like `bind:value={item.count}`, for example).\n\n## Using JavaScript variables in CSS\n\nIf you have a JS variable that you want to use inside CSS you can set a CSS custom property with the `style:` directive.\n\n```svelte\n<div style:--columns={columns}>...</div>\n```\n\nYou can then reference `var(--columns)` inside the component's `<style>`.\n\n## Styling child components\n\nThe CSS in a component's `<style>` is scoped to that component. If a parent component needs to control the child's styles, the preferred way is to use CSS custom properties:\n\n```svelte\n<!-- Parent.svelte -->\n<Child --color=\"red\" />\n\n<!-- Child.svelte -->\n<h1>Hello</h1>\n\n<style>\n\th1 {\n\t\tcolor: var(--color);\n\t}\n</style>\n```\n\nIf this impossible (for example, the child component comes from a library) you can use `:global` to override styles:\n\n```svelte\n<div>\n\t<Child />\n</div>\n\n<style>\n\tdiv :global {\n\t\th1 {\n\t\t\tcolor: red;\n\t\t}\n\t}\n</style>\n```\n\n## Context\n\nConsider using context instead of declaring state in a shared module. This will scope the state to the part of the app that needs it, and eliminate the possibility of it leaking between users when server-side rendering.\n\nUse `createContext` rather than `setContext` and `getContext`, as it provides type safety.\n\n## Async Svelte\n\nIf using version 5.36 or higher, you can use [await expressions](await-expressions) and [hydratable](hydratable) to use promises directly inside components. Note that these require the `experimental.async` option to be enabled in `svelte.config.js` as they are not yet considered fully stable.\n\n## Avoid legacy features\n\nAlways use runes mode for new code, and avoid features that have more modern replacements:\n\n- use `$state` instead of implicit reactivity (e.g. `let count = 0; count += 1`)\n- use `$derived` and `$effect` instead of `$:` assignments and statements (but only use effects when there is no better solution)\n- use `$props` instead of `export let`, `$$props` and `$$restProps`\n- use `onclick={...}` instead of `on:click={...}`\n- use `{#snippet ...}` and `{@render ...}` instead of `<slot>` and `$$slots` and `<svelte:fragment>`\n- use `<DynamicComponent>` instead of `<svelte:component this={DynamicComponent}>`\n- use `import Self from './ThisComponent.svelte'` and `<Self>` instead of `<svelte:self>`\n- use classes with `$state` fields to share reactivity between components, instead of using stores\n- use `{@attach ...}` instead of `use:action`\n- use clsx-style arrays and objects in `class` attributes, instead of the `class:` directive","size_bytes":6866,"metadata":{"name":"svelte-core-bestpractices","title":"Best practices","description":"Guidance on writing fast, robust, modern Svelte code. Load this skill whenever in a Svelte project and asked to write/edit or analyze a Svelte component or module. Covers reactivity, event handling, styling, integration with libraries and more."},"created_at":"2026-02-28T02:00:03.904Z","updated_at":"2026-02-28T02:00:03.904Z"},{"path":"apps/svelte.dev/content/docs/svelte/07-misc/02-testing.md","title":"Testing","filename":"02-testing.md","content":"Testing helps you write and maintain your code and guard against regressions. Testing frameworks help you with that, allowing you to describe assertions or expectations about how your code should behave. Svelte is unopinionated about which testing framework you use — you can write unit tests, integration tests, and end-to-end tests using solutions like [Vitest](https://vitest.dev/), [Jasmine](https://jasmine.github.io/), [Cypress](https://www.cypress.io/) and [Playwright](https://playwright.dev/).\n\n## Unit and component tests with Vitest\n\nUnit tests allow you to test small isolated parts of your code. Integration tests allow you to test parts of your application to see if they work together. If you're using Vite (including via SvelteKit), we recommend using [Vitest](https://vitest.dev/). You can use the Svelte CLI to [setup Vitest](/docs/cli/vitest) either during project creation or later on.\n\nTo setup Vitest manually, first install it:\n\n```sh\nnpm install -D vitest\n```\n\nThen adjust your `vite.config.js`:\n\n```js\n/// file: vite.config.js\nimport { defineConfig } from'vitest/config';\n\nexport default defineConfig({\n\t// ...\n\t// Tell Vitest to use the `browser` entry points in `package.json` files, even though it's running in Node\n\tresolve: process.env.VITEST\n\t\t? {\n\t\t\t\tconditions: ['browser']\n\t\t\t}\n\t\t: undefined\n});\n```\n\n\nYou can now write unit tests for code inside your `.js/.ts` files:\n\n```js\n/// file: multiplier.svelte.test.js\nimport { flushSync } from 'svelte';\nimport { expect, test } from 'vitest';\nimport { multiplier } from './multiplier.svelte.js';\n\ntest('Multiplier', () => {\n\tlet double = multiplier(0, 2);\n\n\texpect(double.value).toEqual(0);\n\n\tdouble.set(5);\n\n\texpect(double.value).toEqual(10);\n});\n```\n\n```js\n/// file: multiplier.svelte.js\n/**\n * @param {number} initial\n * @param {number} k\n */\nexport function multiplier(initial, k) {\n\tlet count = $state(initial);\n\n\treturn {\n\t\tget value() {\n\t\t\treturn count * k;\n\t\t},\n\t\t/** @param {number} c */\n\t\tset: (c) => {\n\t\t\tcount = c;\n\t\t}\n\t};\n}\n```\n\n### Using runes inside your test files\n\nSince Vitest processes your test files the same way as your source files, you can use runes inside your tests as long as the filename includes `.svelte`:\n\n```js\n/// file: multiplier.svelte.test.js\nimport { flushSync } from 'svelte';\nimport { expect, test } from 'vitest';\nimport { multiplier } from './multiplier.svelte.js';\n\ntest('Multiplier', () => {\n\tlet count = $state(0);\n\tlet double = multiplier(() => count, 2);\n\n\texpect(double.value).toEqual(0);\n\n\tcount = 5;\n\n\texpect(double.value).toEqual(10);\n});\n```\n\n```js\n/// file: multiplier.svelte.js\n/**\n * @param {() => number} getCount\n * @param {number} k\n */\nexport function multiplier(getCount, k) {\n\treturn {\n\t\tget value() {\n\t\t\treturn getCount() * k;\n\t\t}\n\t};\n}\n```\n\nIf the code being tested uses effects, you need to wrap the test inside `$effect.root`:\n\n```js\n/// file: logger.svelte.test.js\nimport { flushSync } from 'svelte';\nimport { expect, test } from 'vitest';\nimport { logger } from './logger.svelte.js';\n\ntest('Effect', () => {\n\tconst cleanup = $effect.root(() => {\n\t\tlet count = $state(0);\n\n\t\t// logger uses an $effect to log updates of its input\n\t\tlet log = logger(() => count);\n\n\t\t// effects normally run after a microtask,\n\t\t// use flushSync to execute all pending effects synchronously\n\t\tflushSync();\n\t\texpect(log).toEqual([0]);\n\n\t\tcount = 1;\n\t\tflushSync();\n\n\t\texpect(log).toEqual([0, 1]);\n\t});\n\n\tcleanup();\n});\n```\n\n```js\n/// file: logger.svelte.js\n/**\n * @param {() => any} getValue\n */\nexport function logger(getValue) {\n\t/** @type {any[]} */\n\tlet log = [];\n\n\t$effect(() => {\n\t\tlog.push(getValue());\n\t});\n\n\treturn log;\n}\n```\n\n### Component testing\n\nIt is possible to test your components in isolation, which allows you to render them in a browser (real or simulated), simulate behavior, and make assertions, without spinning up your whole app.\n\n\nTo get started, install jsdom (a library that shims DOM APIs):\n\n```sh\nnpm install -D jsdom\n```\n\nThen adjust your `vite.config.js`:\n\n```js\n/// file: vite.config.js\nimport { defineConfig } from 'vitest/config';\n\nexport default defineConfig({\n\tplugins: [\n\t\t/* ... */\n\t],\n\ttest: {\n\t\t// If you are testing components client-side, you need to set up a DOM environment.\n\t\t// If not all your files should have this environment, you can use a\n\t\t// `// @vitest-environment jsdom` comment at the top of the test files instead.\n\t\tenvironment: 'jsdom'\n\t},\n\t// Tell Vitest to use the `browser` entry points in `package.json` files, even though it's running in Node\n\tresolve: process.env.VITEST\n\t\t? {\n\t\t\t\tconditions: ['browser']\n\t\t\t}\n\t\t: undefined\n});\n```\n\nAfter that, you can create a test file in which you import the component to test, interact with it programmatically and write expectations about the results:\n\n```js\n/// file: component.test.js\nimport { flushSync, mount, unmount } from 'svelte';\nimport { expect, test } from 'vitest';\nimport Component from './Component.svelte';\n\ntest('Component', () => {\n\t// Instantiate the component using Svelte's `mount` API\n\tconst component = mount(Component, {\n\t\ttarget: document.body, // `document` exists because of jsdom\n\t\tprops: { initial: 0 }\n\t});\n\n\texpect(document.body.innerHTML).toBe('<button>0</button>');\n\n\t// Click the button, then flush the changes so you can synchronously write expectations\n\tdocument.body.querySelector('button').click();\n\tflushSync();\n\n\texpect(document.body.innerHTML).toBe('<button>1</button>');\n\n\t// Remove the component from the DOM\n\tunmount(component);\n});\n```\n\nWhile the process is very straightforward, it is also low level and somewhat brittle, as the precise structure of your component may change frequently. Tools like [@testing-library/svelte](https://testing-library.com/docs/svelte-testing-library/intro/) can help streamline your tests. The above test could be rewritten like this:\n\n```js\n/// file: component.test.js\nimport { render, screen } from '@testing-library/svelte';\nimport userEvent from '@testing-library/user-event';\nimport { expect, test } from 'vitest';\nimport Component from './Component.svelte';\n\ntest('Component', async () => {\n\tconst user = userEvent.setup();\n\trender(Component);\n\n\tconst button = screen.getByRole('button');\n\texpect(button).toHaveTextContent(0);\n\n\tawait user.click(button);\n\texpect(button).toHaveTextContent(1);\n});\n```\n\nWhen writing component tests that involve two-way bindings, context or snippet props, it's best to create a wrapper component for your specific test and interact with that. `@testing-library/svelte` contains some [examples](https://testing-library.com/docs/svelte-testing-library/example).\n\n## Component tests with Storybook\n\n[Storybook](https://storybook.js.org) is a tool for developing and documenting UI components, and it can also be used to test your components. They're run with Vitest's browser mode, which renders your components in a real browser for the most realistic testing environment.\n\nTo get started, first install Storybook ([using Svelte's CLI](/docs/cli/storybook)) in your project via `npx sv add storybook` and choose the recommended configuration that includes testing features. If you're already using Storybook, and for more information on Storybook's testing capabilities, follow the [Storybook testing docs](https://storybook.js.org/docs/writing-tests?renderer=svelte) to get started.\n\nYou can create stories for component variations and test interactions with the [play function](https://storybook.js.org/docs/writing-tests/interaction-testing?renderer=svelte#writing-interaction-tests), which allows you to simulate behavior and make assertions using the Testing Library and Vitest APIs. Here's an example of two stories that can be tested, one that renders an empty LoginForm component and one that simulates a user filling out the form:\n\n```svelte\n/// file: LoginForm.stories.svelte\n<script module>\n\timport { defineMeta } from '@storybook/addon-svelte-csf';\n\timport { expect, fn } from 'storybook/test';\n\n\timport LoginForm from './LoginForm.svelte';\n\n\tconst { Story } = defineMeta({\n\t\tcomponent: LoginForm,\n\t\targs: {\n\t\t\t// Pass a mock function to the `onSubmit` prop\n\t\t\tonSubmit: fn(),\n\t\t}\n\t});\n</script>\n \n<Story name=\"Empty Form\" />\n \n<Story\n\tname=\"Filled Form\"\n\tplay={async ({ args, canvas, userEvent }) => {\n\t\t// Simulate a user filling out the form\n\t\tawait userEvent.type(canvas.getByTestId('email'), 'email@provider.com');\n\t\tawait userEvent.type(canvas.getByTestId('password'), 'a-random-password');\n\t\tawait userEvent.click(canvas.getByRole('button'));\n\n\t\t// Run assertions\n\t\tawait expect(args.onSubmit).toHaveBeenCalledTimes(1);\n\t\tawait expect(canvas.getByText('You’re in!')).toBeInTheDocument();\n\t}}\n/>\n```\n\n## End-to-end tests with Playwright\n\nE2E (short for 'end to end') tests allow you to test your full application through the eyes of the user. This section uses [Playwright](https://playwright.dev/) as an example, but you can also use other solutions like [Cypress](https://www.cypress.io/) or [NightwatchJS](https://nightwatchjs.org/).\n\nYou can use the Svelte CLI to [setup Playwright](/docs/cli/playwright) either during project creation or later on. You can also [set it up with `npm init playwright`](https://playwright.dev/docs/intro). Additionally, you may also want to install an IDE plugin such as [the VS Code extension](https://playwright.dev/docs/getting-started-vscode) to be able to execute tests from inside your IDE.\n\nIf you've run `npm init playwright` or are not using Vite, you may need to adjust the Playwright config to tell Playwright what to do before running the tests — mainly starting your application at a certain port. For example:\n\n```js\n/// file: playwright.config.js\nconst config = {\n\twebServer: {\n\t\tcommand: 'npm run build && npm run preview',\n\t\tport: 4173\n\t},\n\ttestDir: 'tests',\n\ttestMatch: /(.+\\.)?(test|spec)\\.[jt]s/\n};\n\nexport default config;\n```\n\nYou can now start writing tests. These are totally unaware of Svelte as a framework, so you mainly interact with the DOM and write assertions.\n\n```js\n// @errors: 2307 7031\n/// file: tests/hello-world.spec.js\nimport { expect, test } from '@playwright/test';\n\ntest('home page has expected h1', async ({ page }) => {\n\tawait page.goto('/');\n\tawait expect(page.locator('h1')).toBeVisible();\n});\n```","size_bytes":10263,"metadata":{"title":"Testing"},"created_at":"2025-07-18T15:47:38.994Z","updated_at":"2026-02-14T01:33:24.881Z"},{"path":"apps/svelte.dev/content/docs/svelte/07-misc/03-typescript.md","title":"TypeScript","filename":"03-typescript.md","content":"<!-- - [basically what we have today](https://svelte.dev/docs/typescript)\n- built-in support, but only for type-only features\n- generics\n- using `Component` and the other helper types\n- using `svelte-check` -->\n\nYou can use TypeScript within Svelte components. IDE extensions like the [Svelte VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) will help you catch errors right in your editor, and [`svelte-check`](https://www.npmjs.com/package/svelte-check) does the same on the command line, which you can integrate into your CI.\n\n## `<script lang=\"ts\">`\n\nTo use TypeScript inside your Svelte components, add `lang=\"ts\"` to your `script` tags:\n\n```svelte\n<script lang=\"ts\">\n\tlet name: string = 'world';\n\n\tfunction greet(name: string) {\n\t\talert(`Hello, ${name}!`);\n\t}\n</script>\n\n<button onclick={(e: Event) => greet(e.target.innerText)}>\n\t{name as string}\n</button>\n```\n\nDoing so allows you to use TypeScript's _type-only_ features. That is, all features that just disappear when transpiling to JavaScript, such as type annotations or interface declarations. Features that require the TypeScript compiler to output actual code are not supported. This includes:\n\n- using enums\n- using `private`, `protected` or `public` modifiers in constructor functions together with initializers\n- using features that are not yet part of the ECMAScript standard (i.e. not level 4 in the TC39 process) and therefore not implemented yet within Acorn, the parser we use for parsing JavaScript\n\nIf you want to use one of these features, you need to setup up a `script` preprocessor.\n\n## Preprocessor setup\n\nTo use non-type-only TypeScript features within Svelte components, you need to add a preprocessor that will turn TypeScript into JavaScript.\n\n```ts\n/// file: svelte.config.js\n// @noErrors\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte';\n\nconst config = {\n\t// Note the additional `{ script: true }`\n\tpreprocess: vitePreprocess({ script: true })\n};\n\nexport default config;\n```\n\n### Using SvelteKit or Vite\n\nThe easiest way to get started is scaffolding a new SvelteKit project by typing `npx sv create`, following the prompts and choosing the TypeScript option.\n\n```ts\n/// file: svelte.config.js\n// @noErrors\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte';\n\nconst config = {\n\tpreprocess: vitePreprocess()\n};\n\nexport default config;\n```\n\nIf you don't need or want all the features SvelteKit has to offer, you can scaffold a Svelte-flavoured Vite project instead by typing `npm create vite@latest` and selecting the `svelte-ts` option.\n\nIn both cases, a `svelte.config.js` with `vitePreprocess` will be added. Vite/SvelteKit will read from this config file.\n\n### Other build tools\n\nIf you're using tools like Rollup or Webpack instead, install their respective Svelte plugins. For Rollup that's [rollup-plugin-svelte](https://github.com/sveltejs/rollup-plugin-svelte) and for Webpack that's [svelte-loader](https://github.com/sveltejs/svelte-loader). For both, you need to install `typescript` and `svelte-preprocess` and add the preprocessor to the plugin config (see the respective READMEs for more info).\n\n\n## tsconfig.json settings\n\nWhen using TypeScript, make sure your `tsconfig.json` is setup correctly.\n\n- Use a [`target`](https://www.typescriptlang.org/tsconfig/#target) of at least `ES2015` so classes are not compiled to functions\n- Set [`verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax) to `true` so that imports are left as-is\n- Set [`isolatedModules`](https://www.typescriptlang.org/tsconfig/#isolatedModules) to `true` so that each file is looked at in isolation. TypeScript has a few features which require cross-file analysis and compilation, which the Svelte compiler and tooling like Vite don't do. \n\n## Typing `$props`\n\nType `$props` just like a regular object with certain properties.\n\n```svelte\n<script lang=\"ts\">\n\timport type { Snippet } from 'svelte';\n\n\tinterface Props {\n\t\trequiredProperty: number;\n\t\toptionalProperty?: boolean;\n\t\tsnippetWithStringArgument: Snippet<[string]>;\n\t\teventHandler: (arg: string) => void;\n\t\t[key: string]: unknown;\n\t}\n\n\tlet {\n\t\trequiredProperty,\n\t\toptionalProperty,\n\t\tsnippetWithStringArgument,\n\t\teventHandler,\n\t\t...everythingElse\n\t}: Props = $props();\n</script>\n\n<button onclick={() => eventHandler('clicked button')}>\n\t{@render snippetWithStringArgument('hello')}\n</button>\n```\n\n## Generic `$props`\n\nComponents can declare a generic relationship between their properties. One example is a generic list component that receives a list of items and a callback property that receives an item from the list. To declare that the `items` property and the `select` callback operate on the same types, add the `generics` attribute to the `script` tag:\n\n```svelte\n<script lang=\"ts\" generics=\"Item extends { text: string }\">\n\tinterface Props {\n\t\titems: Item[];\n\t\tselect(item: Item): void;\n\t}\n\n\tlet { items, select }: Props = $props();\n</script>\n\n{#each items as item}\n\t<button onclick={() => select(item)}>\n\t\t{item.text}\n\t</button>\n{/each}\n```\n\nThe content of `generics` is what you would put between the `<...>` tags of a generic function. In other words, you can use multiple generics, `extends` and fallback types.\n\n## Typing wrapper components\n\nIn case you're writing a component that wraps a native element, you may want to expose all the attributes of the underlying element to the user. In that case, use (or extend from) one of the interfaces provided by `svelte/elements`. Here's an example for a `Button` component:\n\n```svelte\n<script lang=\"ts\">\n\timport type { HTMLButtonAttributes } from 'svelte/elements';\n\n\tlet { children, ...rest }: HTMLButtonAttributes = $props();\n</script>\n\n<button {...rest}>\n\t{@render children?.()}\n</button>\n```\n\nNot all elements have a dedicated type definition. For those without one, use `SvelteHTMLElements`:\n\n```svelte\n<script lang=\"ts\">\n\timport type { SvelteHTMLElements } from 'svelte/elements';\n\n\tlet { children, ...rest }: SvelteHTMLElements['div'] = $props();\n</script>\n\n<div {...rest}>\n\t{@render children?.()}\n</div>\n```\n\n## Typing `$state`\n\nYou can type `$state` like any other variable.\n\n```ts\nlet count: number = $state(0);\n```\n\nIf you don't give `$state` an initial value, part of its types will be `undefined`.\n\n```ts\n// @noErrors\n// Error: Type 'number | undefined' is not assignable to type 'number'\nlet count: number = $state();\n```\n\nIf you know that the variable _will_ be defined before you first use it, use an `as` casting. This is especially useful in the context of classes:\n\n```ts\nclass Counter {\n\tcount = $state() as number;\n\tconstructor(initial: number) {\n\t\tthis.count = initial;\n\t}\n}\n```\n\n## The `Component` type\n\nSvelte components are of type `Component`. You can use it and its related types to express a variety of constraints.\n\nUsing it together with dynamic components to restrict what kinds of component can be passed to it:\n\n```svelte\n<script lang=\"ts\">\n\timport type { Component } from 'svelte';\n\n\tinterface Props {\n\t\t// only components that have at most the \"prop\"\n\t\t// property required can be passed\n\t\tDynamicComponent: Component<{ prop: string }>;\n\t}\n\n\tlet { DynamicComponent }: Props = $props();\n</script>\n\n<DynamicComponent prop=\"foo\" />\n```\n\n> [!LEGACY] In Svelte 4, components were of type `SvelteComponent`\n\nTo extract the properties from a component, use `ComponentProps`.\n\n```ts\nimport type { Component, ComponentProps } from 'svelte';\nimport MyComponent from './MyComponent.svelte';\n\nfunction withProps<TComponent extends Component<any>>(\n\tcomponent: TComponent,\n\tprops: ComponentProps<TComponent>\n) {}\n\n// Errors if the second argument is not the correct props expected\n// by the component in the first argument.\nwithProps(MyComponent, { foo: 'bar' });\n```\n\nTo declare that a variable expects the constructor or instance type of a component:\n\n```svelte\n<script lang=\"ts\">\n\timport MyComponent from './MyComponent.svelte';\n\n\tlet componentConstructor: typeof MyComponent = MyComponent;\n\tlet componentInstance: MyComponent;\n</script>\n\n<MyComponent bind:this={componentInstance} />\n```\n\n## Enhancing built-in DOM types\n\nSvelte provides a best effort of all the HTML DOM types that exist. Sometimes you may want to use experimental attributes or custom events coming from an action. In these cases, TypeScript will throw a type error, saying that it does not know these types. If it's a non-experimental standard attribute/event, this may very well be a missing typing from our [HTML typings](https://github.com/sveltejs/svelte/blob/main/packages/svelte/elements.d.ts). In that case, you are welcome to open an issue and/or a PR fixing it.\n\nIn case this is a custom or experimental attribute/event, you can enhance the typings by augmenting the `svelte/elements` module like this:\n\n```ts\n/// file: additional-svelte-typings.d.ts\nimport { HTMLButtonAttributes } from 'svelte/elements';\n\ndeclare module 'svelte/elements' {\n\t// add a new element\n\texport interface SvelteHTMLElements {\n\t\t'custom-button': HTMLButtonAttributes;\n\t}\n\n\t// add a new global attribute that is available on all html elements\n\texport interface HTMLAttributes<T> {\n\t\tglobalattribute?: string;\n\t}\n\n\t// add a new attribute for button elements\n\texport interface HTMLButtonAttributes {\n\t\tveryexperimentalattribute?: string;\n\t}\n}\n\nexport {}; // ensure this is not an ambient module, else types will be overridden instead of augmented\n```\n\nThen make sure that the `d.ts` file is referenced in your `tsconfig.json`. If it reads something like `\"include\": [\"src/**/*\"]` and your `d.ts` file is inside `src`, it should work. You may need to reload for the changes to take effect.","size_bytes":9682,"metadata":{"title":"TypeScript"},"created_at":"2025-07-18T15:47:38.995Z","updated_at":"2026-02-23T02:00:04.048Z"},{"path":"apps/svelte.dev/content/docs/svelte/07-misc/04-custom-elements.md","title":"Custom elements","filename":"04-custom-elements.md","content":"<!-- - [basically what we have today](https://svelte.dev/docs/custom-elements-api) -->\n\nSvelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `<svelte:options>` [element](svelte-options). Within the custom element you can access the host element via the [`$host`](https://svelte.dev/docs/svelte/$host) rune.\n\n```svelte\n<svelte:options customElement=\"my-element\" />\n\n<script>\n\tlet { name = 'world' } = $props();\n</script>\n\n<h1>Hello {name}!</h1>\n<slot />\n```\n\nYou can leave out the tag name for any of your inner components which you don't want to expose and use them like regular Svelte components. Consumers of the component can still name it afterwards if needed, using the static `element` property which contains the custom element constructor and which is available when the `customElement` compiler option is `true`.\n\n```js\n// @noErrors\nimport MyElement from './MyElement.svelte';\n\ncustomElements.define('my-element', MyElement.element);\n```\n\nOnce a custom element has been defined, it can be used as a regular DOM element:\n\n```js\ndocument.body.innerHTML = `\n\t<my-element>\n\t\t<p>This is some slotted content</p>\n\t</my-element>\n`;\n```\n\nAny [props](basic-markup#Component-props) are exposed as properties of the DOM element (as well as being readable/writable as attributes, where possible).\n\n```js\n// @noErrors\nconst el = document.querySelector('my-element');\n\n// get the current value of the 'name' prop\nconsole.log(el.name);\n\n// set a new value, updating the shadow DOM\nel.name = 'everybody';\n```\n\nNote that you need to list out all properties explicitly, i.e. doing `let props = $props()` without declaring `props` in the [component options](#Component-options) means that Svelte can't know which props to expose as properties on the DOM element.\n\n## Component lifecycle\n\nCustom elements are created from Svelte components using a wrapper approach. This means the inner Svelte component has no knowledge that it is a custom element. The custom element wrapper takes care of handling its lifecycle appropriately.\n\nWhen a custom element is created, the Svelte component it wraps is _not_ created right away. It is only created in the next tick after the `connectedCallback` is invoked. Properties assigned to the custom element before it is inserted into the DOM are temporarily saved and then set on component creation, so their values are not lost. The same does not work for invoking exported functions on the custom element though, they are only available after the element has mounted. If you need to invoke functions before component creation, you can work around it by using the [`extend` option](#Component-options).\n\nWhen a custom element written with Svelte is created or updated, the shadow DOM will reflect the value in the next tick, not immediately. This way updates can be batched, and DOM moves which temporarily (but synchronously) detach the element from the DOM don't lead to unmounting the inner component.\n\nThe inner Svelte component is destroyed in the next tick after the `disconnectedCallback` is invoked.\n\n## Component options\n\nWhen constructing a custom element, you can tailor several aspects by defining `customElement` as an object within `<svelte:options>` since Svelte 4. This object may contain the following properties:\n\n- `tag: string`: an optional `tag` property for the custom element's name. If set, a custom element with this tag name will be defined with the document's `customElements` registry upon importing this component.\n- `shadow`: an optional property to modify shadow root properties. It accepts the following values:\n  - `\"none\"`: No shadow root is created. Note that styles are then no longer encapsulated, and you can't use slots.\n  - `\"open\"`: Shadow root is created with the `mode: \"open\"` option.\n  - [`ShadowRootInit`](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow#options): You can pass a settings object that will be passed to `attachShadow()` when shadow root is created.\n- `props`: an optional property to modify certain details and behaviors of your component's properties. It offers the following settings:\n  - `attribute: string`: To update a custom element's prop, you have two alternatives: either set the property on the custom element's reference as illustrated above or use an HTML attribute. For the latter, the default attribute name is the lowercase property name. Modify this by assigning `attribute: \"<desired name>\"`.\n  - `reflect: boolean`: By default, updated prop values do not reflect back to the DOM. To enable this behavior, set `reflect: true`.\n  - `type: 'String' | 'Boolean' | 'Number' | 'Array' | 'Object'`: While converting an attribute value to a prop value and reflecting it back, the prop value is assumed to be a `String` by default. This may not always be accurate. For instance, for a number type, define it using `type: \"Number\"`\n    You don't need to list all properties, those not listed will use the default settings.\n- `extend`: an optional property which expects a function as its argument. It is passed the custom element class generated by Svelte and expects you to return a custom element class. This comes in handy if you have very specific requirements to the life cycle of the custom element or want to enhance the class to for example use [ElementInternals](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals#examples) for better HTML form integration.\n\n```svelte\n<svelte:options\n\tcustomElement={{\n\t\ttag: 'custom-element',\n\t\tshadow: {\n\t\t\tmode: import.meta.env.DEV ? 'open' : 'closed',\n\t\t\tclonable: true,\n\t\t\t// ...\n\t\t},\n\t\tprops: {\n\t\t\tname: { reflect: true, type: 'Number', attribute: 'element-index' }\n\t\t},\n\t\textend: (customElementConstructor) => {\n\t\t\t// Extend the class so we can let it participate in HTML forms\n\t\t\treturn class extends customElementConstructor {\n\t\t\t\tstatic formAssociated = true;\n\n\t\t\t\tconstructor() {\n\t\t\t\t\tsuper();\n\t\t\t\t\tthis.attachedInternals = this.attachInternals();\n\t\t\t\t}\n\n\t\t\t\t// Add the function here, not below in the component so that\n\t\t\t\t// it's always available, not just when the inner Svelte component\n\t\t\t\t// is mounted\n\t\t\t\trandomIndex() {\n\t\t\t\t\tthis.elementIndex = Math.random();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}}\n/>\n\n<script>\n\tlet { elementIndex, attachedInternals } = $props();\n\t// ...\n\tfunction check() {\n\t\tattachedInternals.checkValidity();\n\t}\n</script>\n\n...\n```\n\n\n## Caveats and limitations\n\nCustom elements can be a useful way to package components for consumption in a non-Svelte app, as they will work with vanilla HTML and JavaScript as well as [most frameworks](https://custom-elements-everywhere.com/). There are, however, some important differences to be aware of:\n\n- Styles are _encapsulated_, rather than merely _scoped_ (unless you set `shadow: \"none\"`). This means that any non-component styles (such as you might have in a `global.css` file) will not apply to the custom element, including styles with the `:global(...)` modifier\n- Instead of being extracted out as a separate .css file, styles are inlined into the component as a JavaScript string\n- Custom elements are not generally suitable for server-side rendering, as the shadow DOM is invisible until JavaScript loads\n- In Svelte, slotted content renders _lazily_. In the DOM, it renders _eagerly_. In other words, it will always be created even if the component's `<slot>` element is inside an `{#if ...}` block. Similarly, including a `<slot>` in an `{#each ...}` block will not cause the slotted content to be rendered multiple times\n- The deprecated `let:` directive has no effect, because custom elements do not have a way to pass data to the parent component that fills the slot\n- Polyfills are required to support older browsers\n- You can use Svelte's context feature between regular Svelte components within a custom element, but you can't use them across custom elements. In other words, you can't use `setContext` on a parent custom element and read that with `getContext` in a child custom element.\n- Don't declare properties or attributes starting with `on`, as their usage will be interpreted as an event listener. In other words, Svelte treats `<custom-element oneworld={true}></custom-element>` as `customElement.addEventListener('eworld', true)` (and not as `customElement.oneworld = true`)","size_bytes":8407,"metadata":{"title":"Custom elements"},"created_at":"2025-07-18T15:47:38.996Z","updated_at":"2026-02-14T01:33:24.882Z"},{"path":"apps/svelte.dev/content/docs/svelte/07-misc/06-v4-migration-guide.md","title":"Svelte 4 migration guide","filename":"06-v4-migration-guide.md","content":"This migration guide provides an overview of how to migrate from Svelte version 3 to 4. See the linked PRs for more details about each change. Use the migration script to migrate some of these automatically: `npx svelte-migrate@latest svelte-4`\n\nIf you're a library author, consider whether to only support Svelte 4 or if it's possible to support Svelte 3 too. Since most of the breaking changes don't affect many people, this may be easily possible. Also remember to update the version range in your `peerDependencies`.\n\n## Minimum version requirements\n\n- Upgrade to Node 16 or higher. Earlier versions are no longer supported. ([#8566](https://github.com/sveltejs/svelte/issues/8566))\n- If you are using SvelteKit, upgrade to 1.20.4 or newer ([sveltejs/kit#10172](https://github.com/sveltejs/kit/pull/10172))\n- If you are using Vite without SvelteKit, upgrade to `vite-plugin-svelte` 2.4.1 or newer ([#8516](https://github.com/sveltejs/svelte/issues/8516))\n- If you are using webpack, upgrade to webpack 5 or higher and `svelte-loader` 3.1.8 or higher. Earlier versions are no longer supported. ([#8515](https://github.com/sveltejs/svelte/issues/8515), [198dbcf](https://github.com/sveltejs/svelte/commit/198dbcf))\n- If you are using Rollup, upgrade to `rollup-plugin-svelte` 7.1.5 or higher ([198dbcf](https://github.com/sveltejs/svelte/commit/198dbcf))\n- If you are using TypeScript, upgrade to TypeScript 5 or higher. Lower versions might still work, but no guarantees are made about that. ([#8488](https://github.com/sveltejs/svelte/issues/8488))\n\n## Browser conditions for bundlers\n\nBundlers must now specify the `browser` condition when building a frontend bundle for the browser. SvelteKit and Vite will handle this automatically for you. If you're using any others, you may observe lifecycle callbacks such as `onMount` not get called and you'll need to update the module resolution configuration.\n- For Rollup this is done within the `@rollup/plugin-node-resolve` plugin by setting `browser: true` in its options. See the [`rollup-plugin-svelte`](https://github.com/sveltejs/rollup-plugin-svelte/#usage) documentation for more details\n- For webpack this is done by adding `\"browser\"` to the `conditionNames` array. You may also have to update your `alias` config, if you have set it. See the [`svelte-loader`](https://github.com/sveltejs/svelte-loader#usage) documentation for more details\n\n([#8516](https://github.com/sveltejs/svelte/issues/8516))\n\n## Removal of CJS related output\n\nSvelte no longer supports the CommonJS (CJS) format for compiler output and has also removed the `svelte/register` hook and the CJS runtime version. If you need to stay on the CJS output format, consider using a bundler to convert Svelte's ESM output to CJS in a post-build step. ([#8613](https://github.com/sveltejs/svelte/issues/8613))\n\n## Stricter types for Svelte functions\n\nThere are now stricter types for `createEventDispatcher`, `Action`, `ActionReturn`, and `onMount`:\n\n- `createEventDispatcher` now supports specifying that a payload is optional, required, or non-existent, and the call sites are checked accordingly ([#7224](https://github.com/sveltejs/svelte/issues/7224))\n\n```ts\n// @errors: 2554 2345\nimport { createEventDispatcher } from 'svelte';\n\nconst dispatch = createEventDispatcher<{\n\toptional: number | null;\n\trequired: string;\n\tnoArgument: null;\n}>();\n\n// Svelte version 3:\ndispatch('optional');\ndispatch('required'); // I can still omit the detail argument\ndispatch('noArgument', 'surprise'); // I can still add a detail argument\n\n// Svelte version 4 using TypeScript strict mode:\ndispatch('optional');\ndispatch('required'); // error, missing argument\ndispatch('noArgument', 'surprise'); // error, cannot pass an argument\n```\n\n- `Action` and `ActionReturn` have a default parameter type of `undefined` now, which means you need to type the generic if you want to specify that this action receives a parameter. The migration script will migrate this automatically ([#7442](https://github.com/sveltejs/svelte/pull/7442))\n\n```ts\n// @noErrors\nconst action: Action = (node, params) => { ... } // this is now an error if you use params in any way\nconst action: Action<HTMLElement, string> = (node, params) => { ... } // params is of type string\n```\n\n- `onMount` now shows a type error if you return a function asynchronously from it, because this is likely a bug in your code where you expect the callback to be called on destroy, which it will only do for synchronously returned functions ([#8136](https://github.com/sveltejs/svelte/issues/8136))\n\n```js\n// @noErrors\n// Example where this change reveals an actual bug\nonMount(\n// someCleanup() not called because function handed to onMount is async\n\tasync () => {\n\t\tconst something = await foo();\n// someCleanup() is called because function handed to onMount is sync\n\t() => {\n\t\tfoo().then(something => {...});\n\t\t// ...\n\t\treturn () => someCleanup();\n\t}\n);\n```\n\n## Custom Elements with Svelte\n\nThe creation of custom elements with Svelte has been overhauled and significantly improved. The `tag` option is deprecated in favor of the new `customElement` option:\n\n```svelte\n<svelte:options tag=\"my-component\" />\n<svelte:options customElement=\"my-component\" />\n```\n\nThis change was made to allow [more configurability](custom-elements#Component-options) for advanced use cases. The migration script will adjust your code automatically. The update timing of properties has changed slightly as well. ([#8457](https://github.com/sveltejs/svelte/issues/8457))\n\n## SvelteComponentTyped is deprecated\n\n`SvelteComponentTyped` is deprecated, as `SvelteComponent` now has all its typing capabilities. Replace all instances of `SvelteComponentTyped` with `SvelteComponent`.\n\n```js\nimport { SvelteComponentTyped } from 'svelte';\nimport { SvelteComponent } from 'svelte';\n\nexport class Foo extends SvelteComponentTyped<{ aProp: string }> {}\nexport class Foo extends SvelteComponent<{ aProp: string }> {}\n```\n\nIf you have used `SvelteComponent` as the component instance type previously, you may see a somewhat opaque type error now, which is solved by changing `: typeof SvelteComponent` to `: typeof SvelteComponent<any>`.\n\n```svelte\n<script>\n\timport ComponentA from './ComponentA.svelte';\n\timport ComponentB from './ComponentB.svelte';\n\timport { SvelteComponent } from 'svelte';\n\n\tlet component: typeof SvelteComponent<any>;\n\n\tfunction choseRandomly() {\n\t\tcomponent = Math.random() > 0.5 ? ComponentA : ComponentB;\n\t}\n</script>\n\n<button on:click={choseRandomly}>random</button>\n<svelte:element this={component} />\n```\n\nThe migration script will do both automatically for you. ([#8512](https://github.com/sveltejs/svelte/issues/8512))\n\n## Transitions are local by default\n\nTransitions are now local by default to prevent confusion around page navigations. \"local\" means that a transition will not play if it's within a nested control flow block (`each/if/await/key`) and not the direct parent block but a block above it is created/destroyed. In the following example, the `slide` intro animation will only play when `success` goes from `false` to `true`, but it will _not_ play when `show` goes from `false` to `true`:\n\n```svelte\n{#if show}\n\t...\n\t{#if success}\n\t\t<p in:slide>Success</p>\n\t{/each}\n{/if}\n```\n\nTo make transitions global, add the `|global` modifier — then they will play when _any_ control flow block above is created/destroyed. The migration script will do this automatically for you. ([#6686](https://github.com/sveltejs/svelte/issues/6686))\n\n## Default slot bindings\n\nDefault slot bindings are no longer exposed to named slots and vice versa:\n\n```svelte\n<script>\n\timport Nested from './Nested.svelte';\n</script>\n\n<Nested let:count>\n\t<p>\n\t\tcount in default slot — is available: {count}\n\t</p>\n\t<p slot=\"bar\">\n\t\tcount in bar slot — is not available: {count}\n\t</p>\n</Nested>\n```\n\nThis makes slot bindings more consistent as the behavior is undefined when for example the default slot is from a list and the named slot is not. ([#6049](https://github.com/sveltejs/svelte/issues/6049))\n\n## Preprocessors\n\nThe order in which preprocessors are applied has changed. Now, preprocessors are executed in order, and within one group, the order is markup, script, style.\n\n```js\n// @errors: 2304\nimport { preprocess } from 'svelte/compiler';\n\nconst { code } = await preprocess(\n\tsource,\n\t[\n\t\t{\n\t\t\tmarkup: () => {\n\t\t\t\tconsole.log('markup-1');\n\t\t\t},\n\t\t\tscript: () => {\n\t\t\t\tconsole.log('script-1');\n\t\t\t},\n\t\t\tstyle: () => {\n\t\t\t\tconsole.log('style-1');\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tmarkup: () => {\n\t\t\t\tconsole.log('markup-2');\n\t\t\t},\n\t\t\tscript: () => {\n\t\t\t\tconsole.log('script-2');\n\t\t\t},\n\t\t\tstyle: () => {\n\t\t\t\tconsole.log('style-2');\n\t\t\t}\n\t\t}\n\t],\n\t{\n\t\tfilename: 'App.svelte'\n\t}\n);\n\n// Svelte 3 logs:\n// markup-1\n// markup-2\n// script-1\n// script-2\n// style-1\n// style-2\n\n// Svelte 4 logs:\n// markup-1\n// script-1\n// style-1\n// markup-2\n// script-2\n// style-2\n```\n\nThis could affect you for example if you are using `MDsveX` - in which case you should make sure it comes before any script or style preprocessor.\n\n```js\n// @noErrors\npreprocess: [\nvitePreprocess(),\n\tmdsvex(mdsvexConfig)\nmdsvex(mdsvexConfig),\n\tvitePreprocess()\n]\n```\n\nEach preprocessor must also have a name. ([#8618](https://github.com/sveltejs/svelte/issues/8618))\n\n## New eslint package\n\n`eslint-plugin-svelte3` is deprecated. It may still work with Svelte 4 but we make no guarantees about that. We recommend switching to our new package [eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte). See [this Github post](https://github.com/sveltejs/kit/issues/10242#issuecomment-1610798405) for an instruction how to migrate. Alternatively, you can create a new project using `npm create svelte@latest`, select the eslint (and possibly TypeScript) option and then copy over the related files into your existing project.\n\n## Other breaking changes\n\n- the `inert` attribute is now applied to outroing elements to make them invisible to assistive technology and prevent interaction. ([#8628](https://github.com/sveltejs/svelte/pull/8628))\n- the runtime now uses `classList.toggle(name, boolean)` which may not work in very old browsers. Consider using a [polyfill](https://github.com/eligrey/classList.js) if you need to support these browsers. ([#8629](https://github.com/sveltejs/svelte/issues/8629))\n- the runtime now uses the `CustomEvent` constructor which may not work in very old browsers. Consider using a [polyfill](https://github.com/theftprevention/event-constructor-polyfill/tree/master) if you need to support these browsers. ([#8775](https://github.com/sveltejs/svelte/pull/8775))\n- people implementing their own stores from scratch using the `StartStopNotifier` interface (which is passed to the create function of `writable` etc) from `svelte/store` now need to pass an update function in addition to the set function. This has no effect on people using stores or creating stores using the existing Svelte stores. ([#6750](https://github.com/sveltejs/svelte/issues/6750))\n- `derived` will now throw an error on falsy values instead of stores passed to it. ([#7947](https://github.com/sveltejs/svelte/issues/7947))\n- type definitions for `svelte/internal` were removed to further discourage usage of those internal methods which are not public API. Most of these will likely change for Svelte 5\n- Removal of DOM nodes is now batched which slightly changes its order, which might affect the order of events fired if you're using a `MutationObserver` on these elements ([#8763](https://github.com/sveltejs/svelte/pull/8763))\n- if you enhanced the global typings through the `svelte.JSX` namespace before, you need to migrate this to use the `svelteHTML` namespace. Similarly if you used the `svelte.JSX` namespace to use type definitions from it, you need to migrate those to use the types from `svelte/elements` instead. You can find more information about what to do [here](https://github.com/sveltejs/language-tools/blob/master/docs/preprocessors/typescript.md#im-getting-deprecation-warnings-for-sveltejsx--i-want-to-migrate-to-the-new-typings)","size_bytes":12118,"metadata":{"title":"Svelte 4 migration guide"},"created_at":"2025-07-18T15:47:39.006Z","updated_at":"2025-11-26T14:00:04.223Z"},{"path":"apps/svelte.dev/content/docs/svelte/07-misc/07-v5-migration-guide.md","title":"Svelte 5 migration guide","filename":"07-v5-migration-guide.md","content":"Version 5 comes with an overhauled syntax and reactivity system. While it may look different at first, you'll soon notice many similarities. This guide goes over the changes in detail and shows you how to upgrade. Along with it, we also provide information on _why_ we did these changes.\n\nYou don't have to migrate to the new syntax right away — Svelte 5 still supports the old Svelte 4 syntax, and you can mix and match components using the new syntax with components using the old and vice versa. We expect many people to be able to upgrade with only a few lines of code changed initially. There's also a [migration script](#Migration-script) that helps you with many of these steps automatically.\n\n## Reactivity syntax changes\n\nAt the heart of Svelte 5 is the new runes API. Runes are basically compiler instructions that inform Svelte about reactivity. Syntactically, runes are functions starting with a dollar-sign.\n\n### let → $state\n\nIn Svelte 4, a `let` declaration at the top level of a component was implicitly reactive. In Svelte 5, things are more explicit: a variable is reactive when created using the `$state` rune. Let's migrate the counter to runes mode by wrapping the counter in `$state`:\n\n```svelte\n<script>\n\tlet count =$state(0);\n</script>\n```\n\nNothing else changes. `count` is still the number itself, and you read and write directly to it, without a wrapper like `.value` or `getCount()`.\n\n> `let` being implicitly reactive at the top level worked great, but it meant that reactivity was constrained — a `let` declaration anywhere else was not reactive. This forced you to resort to using stores when refactoring code out of the top level of components for reuse. This meant you had to learn an entirely separate reactivity model, and the result often wasn't as nice to work with. Because reactivity is more explicit in Svelte 5, you can keep using the same API outside the top level of components. Head to [the tutorial](/tutorial) to learn more.\n\n### $: → $derived/$effect\n\nIn Svelte 4, a `$:` statement at the top level of a component could be used to declare a derivation, i.e. state that is entirely defined through a computation of other state. In Svelte 5, this is achieved using the `$derived` rune:\n\n```svelte\n<script>\n\tlet count = $state(0);\n\t$:constdouble =$derived(count * 2);\n</script>\n```\n\nAs with `$state`, nothing else changes. `double` is still the number itself, and you read it directly, without a wrapper like `.value` or `getDouble()`.\n\nA `$:` statement could also be used to create side effects. In Svelte 5, this is achieved using the `$effect` rune:\n\n```svelte\n<script>\n\tlet count = $state(0);\n\n\t$:$effect(() =>{\n\t\tif (count > 5) {\n\t\t\talert('Count is too high!');\n\t\t}\n\t});\n</script>\n```\n\nNote that [when `$effect` runs is different]($effect#Understanding-dependencies) than when `$:` runs.\n\n> `$:` was a great shorthand and easy to get started with: you could slap a `$:` in front of most code and it would somehow work. This intuitiveness was also its drawback the more complicated your code became, because it wasn't as easy to reason about. Was the intent of the code to create a derivation, or a side effect? With `$derived` and `$effect`, you have a bit more up-front decision making to do (spoiler alert: 90% of the time you want `$derived`), but future-you and other developers on your team will have an easier time.\n>\n> There were also gotchas that were hard to spot:\n>\n> - `$:` only updated directly before rendering, which meant you could read stale values in-between rerenders\n> - `$:` only ran once per tick, which meant that statements may run less often than you think\n> - `$:` dependencies were determined through static analysis of the dependencies. This worked in most cases, but could break in subtle ways during a refactoring where dependencies would be for example moved into a function and no longer be visible as a result\n> - `$:` statements were also ordered by using static analysis of the dependencies. In some cases there could be ties and the ordering would be wrong as a result, needing manual interventions. Ordering could also break while refactoring code and some dependencies no longer being visible as a result.\n>\n> Lastly, it wasn't TypeScript-friendly (our editor tooling had to jump through some hoops to make it valid for TypeScript), which was a blocker for making Svelte's reactivity model truly universal.\n>\n> `$derived` and `$effect` fix all of these by\n>\n> - always returning the latest value\n> - running as often as needed to be stable\n> - determining the dependencies at runtime, and therefore being immune to refactorings\n> - executing dependencies as needed and therefore being immune to ordering problems\n> - being TypeScript-friendly\n\n### export let → $props\n\nIn Svelte 4, properties of a component were declared using `export let`. Each property was one declaration. In Svelte 5, all properties are declared through the `$props` rune, through destructuring:\n\n```svelte\n<script>\n\texport let optional = 'unset';\n\texport let required;\n\tlet { optional = 'unset', required } = $props();\n</script>\n```\n\nThere are multiple cases where declaring properties becomes less straightforward than having a few `export let` declarations:\n\n- you want to rename the property, for example because the name is a reserved identifier (e.g. `class`)\n- you don't know which other properties to expect in advance\n- you want to forward every property to another component\n\nAll these cases need special syntax in Svelte 4:\n\n- renaming: `export { klass as class}`\n- other properties: `$$restProps`\n- all properties `$$props`\n\nIn Svelte 5, the `$props` rune makes this straightforward without any additional Svelte-specific syntax:\n\n- renaming: use property renaming `let { class: klass } = $props();`\n- other properties: use spreading `let { foo, bar, ...rest } = $props();`\n- all properties: don't destructure `let props = $props();`\n\n```svelte\n<script>\n\tlet klass = '';\n\texport { klass as class};\n\tlet { class: klass, ...rest } = $props();\n</script>\n<button class={klass} {...$$restPropsrest}>click me</button>\n```\n\n> `export let` was one of the more controversial API decisions, and there was a lot of debate about whether you should think about a property being `export`ed or `import`ed. `$props` doesn't have this trait. It's also in line with the other runes, and the general thinking reduces to \"everything special to reactivity in Svelte is a rune\".\n>\n> There were also a lot of limitations around `export let`, which required additional API, as shown above. `$props` unite this in one syntactical concept that leans heavily on regular JavaScript destructuring syntax.\n\n## Event changes\n\nEvent handlers have been given a facelift in Svelte 5. Whereas in Svelte 4 we use the `on:` directive to attach an event listener to an element, in Svelte 5 they are properties like any other (in other words — remove the colon):\n\n```svelte\n<script>\n\tlet count = $state(0);\n</script>\n\n<button on:click={() => count++}>\n\tclicks: {count}\n</button>\n```\n\nSince they're just properties, you can use the normal shorthand syntax...\n\n```svelte\n<script>\n\tlet count = $state(0);\n\n\tfunction onclick() {\n\t\tcount++;\n\t}\n</script>\n\n<button {onclick}>\n\tclicks: {count}\n</button>\n```\n\n...though when using a named event handler function it's usually better to use a more descriptive name.\n\n### Component events\n\nIn Svelte 4, components could emit events by creating a dispatcher with `createEventDispatcher`.\n\nThis function is deprecated in Svelte 5. Instead, components should accept _callback props_ — which means you then pass functions as properties to these components:\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Pump from './Pump.svelte';\n\n\tlet size = $state(15);\n\tlet burst = $state(false);\n\n\tfunction reset() {\n\t\tsize = 15;\n\t\tburst = false;\n\t}\n</script>\n\n<Pump\n\ton:inflate={(power) => {\n\t\tsize += power.detail;\n\t\tif (size > 75) burst = true;\n\t}}\n\ton:deflate={(power) => {\n\t\tif (size > 0) size -= power.detail;\n\t}}\n/>\n\n{#if burst}\n\t<button onclick={reset}>new balloon</button>\n\t<span class=\"boom\">💥</span>\n{:else}\n\t<span class=\"balloon\" style=\"scale: {0.01 * size}\">\n\t\t🎈\n\t</span>\n{/if}\n```\n\n```svelte\n<!file: Pump.svelte>\n<script>\n\timport { createEventDispatcher } from 'svelte';\n\tconst dispatch = createEventDispatcher();\n\n\tlet { inflate, deflate } = $props();\n\tlet power = $state(5);\n</script>\n\n<button onclick={() =>dispatch('inflate', power)inflate(power)}>\n\tinflate\n</button>\n<button onclick={() =>dispatch('deflate', power)deflate(power)}>\n\tdeflate\n</button>\n<button onclick={() => power--}>-</button>\nPump power: {power}\n<button onclick={() => power++}>+</button>\n```\n\n### Bubbling events\n\nInstead of doing `<button on:click>` to 'forward' the event from the element to the component, the component should accept an `onclick` callback prop:\n\n```svelte\n<script>\n\tlet { onclick } = $props();\n</script>\n\n<buttonon:click{onclick}>\n\tclick me\n</button>\n```\n\nNote that this also means you can 'spread' event handlers onto the element along with other props instead of tediously forwarding each event separately:\n\n```svelte\n<script>\n\tlet props = $props();\n</script>\n\n<button{...$$props} on:click on:keydown on:all_the_other_stuff{...props}>\n\tclick me\n</button>\n```\n\n### Event modifiers\n\nIn Svelte 4, you can add event modifiers to handlers:\n\n```svelte\n<button on:click|once|preventDefault={handler}>...</button>\n```\n\nModifiers are specific to `on:` and so do not work with modern event handlers. Adding things like `event.preventDefault()` inside the handler itself is preferable, since all the logic lives in one place rather than being split between handler and modifiers.\n\nSince event handlers are just functions, you can create your own wrappers as necessary:\n\n```svelte\n<script>\n\tfunction once(fn) {\n\t\treturn function (event) {\n\t\t\tif (fn) fn.call(this, event);\n\t\t\tfn = null;\n\t\t};\n\t}\n\n\tfunction preventDefault(fn) {\n\t\treturn function (event) {\n\t\t\tevent.preventDefault();\n\t\t\tfn.call(this, event);\n\t\t};\n\t}\n</script>\n\n<button onclick={once(preventDefault(handler))}>...</button>\n```\n\nThere are three modifiers — `capture`, `passive` and `nonpassive` — that can't be expressed as wrapper functions, since they need to be applied when the event handler is bound rather than when it runs.\n\nFor `capture`, we add the modifier to the event name:\n\n```svelte\n<button onclickcapture={...}>...</button>\n```\n\nChanging the [`passive`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#using_passive_listeners) option of an event handler, meanwhile, is not something to be done lightly. If you have a use case for it — and you probably don't! — then you will need to use an action to apply the event handler yourself.\n\n### Multiple event handlers\n\nIn Svelte 4, this is possible:\n\n```svelte\n<button on:click={one} on:click={two}>...</button>\n```\n\nDuplicate attributes/properties on elements — which now includes event handlers — are not allowed. Instead, do this:\n\n```svelte\n<button\n\tonclick={(e) => {\n\t\tone(e);\n\t\ttwo(e);\n\t}}\n>\n\t...\n</button>\n```\n\nWhen spreading props, local event handlers must go _after_ the spread, or they risk being overwritten:\n\n```svelte\n<button\n\t{...props}\n\tonclick={(e) => {\n\t\tdoStuff(e);\n\t\tprops.onclick?.(e);\n\t}}\n>\n\t...\n</button>\n```\n\n> `createEventDispatcher` was always a bit boilerplate-y:\n>\n> - import the function\n> - call the function to get a dispatch function\n> - call said dispatch function with a string and possibly a payload\n> - retrieve said payload on the other end through a `.detail` property, because the event itself was always a `CustomEvent`\n>\n> It was always possible to use component callback props, but because you had to listen to DOM events using `on:`, it made sense to use `createEventDispatcher` for component events due to syntactical consistency. Now that we have event attributes (`onclick`), it's the other way around: Callback props are now the more sensible thing to do.\n>\n> The removal of event modifiers is arguably one of the changes that seems like a step back for those who've liked the shorthand syntax of event modifiers. Given that they are not used that frequently, we traded a smaller surface area for more explicitness. Modifiers also were inconsistent, because most of them were only useable on DOM elements.\n>\n> Multiple listeners for the same event are also no longer possible, but it was something of an anti-pattern anyway, since it impedes readability: if there are many attributes, it becomes harder to spot that there are two handlers unless they are right next to each other. It also implies that the two handlers are independent, when in fact something like `event.stopImmediatePropagation()` inside `one` would prevent `two` from being called.\n>\n> By deprecating `createEventDispatcher` and the `on:` directive in favour of callback props and normal element properties, we:\n>\n> - reduce Svelte's learning curve\n> - remove boilerplate, particularly around `createEventDispatcher`\n> - remove the overhead of creating `CustomEvent` objects for events that may not even have listeners\n> - add the ability to spread event handlers\n> - add the ability to know which event handlers were provided to a component\n> - add the ability to express whether a given event handler is required or optional\n> - increase type safety (previously, it was effectively impossible for Svelte to guarantee that a component didn't emit a particular event)\n\n## Snippets instead of slots\n\nIn Svelte 4, content can be passed to components using slots. Svelte 5 replaces them with snippets, which are more powerful and flexible, and so slots are deprecated in Svelte 5.\n\nThey continue to work, however, and you can pass snippets to a component that uses slots:\n\n```svelte\n<!file: Child.svelte>\n<slot />\n<hr />\n<slot name=\"foo\" message=\"hello\" />\n```\n\n```svelte\n<!file: Parent.svelte>\n<script>\n\timport Child from './Child.svelte';\n</script>\n\n<Child>\n\tdefault child content\n\n\t{#snippet foo({ message })}\n\t\tmessage from child: {message}\n\t{/snippet}\n</Child>\n```\n\n(The reverse is not true — you cannot pass slotted content to a component that uses [`{@render ...}`](/docs/svelte/@render) tags.)\n\nWhen using custom elements, you should still use `<slot />` like before. In a future version, when Svelte removes its internal version of slots, it will leave those slots as-is, i.e. output a regular DOM tag instead of transforming it.\n\n### Default content\n\nIn Svelte 4, the easiest way to pass a piece of UI to the child was using a `<slot />`. In Svelte 5, this is done using the `children` prop instead, which is then shown with `{@render children()}`:\n\n```svelte\n<script>\n\tlet { children } = $props();\n</script>\n\n<slot />\n{@render children?.()}\n```\n\n### Multiple content placeholders\n\nIf you wanted multiple UI placeholders, you had to use named slots. In Svelte 5, use props instead, name them however you like and `{@render ...}` them:\n\n```svelte\n<script>\n\tlet { header, main, footer } = $props();\n</script>\n\n<header>\n\t<slot name=\"header\" />\n\t{@render header()}\n</header>\n\n<main>\n\t<slot name=\"main\" />\n\t{@render main()}\n</main>\n\n<footer>\n\t<slot name=\"footer\" />\n\t{@render footer()}\n</footer>\n```\n\n### Passing data back up\n\nIn Svelte 4, you would pass data to a `<slot />` and then retrieve it with `let:` in the parent component. In Svelte 5, snippets take on that responsibility:\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport List from './List.svelte';\n</script>\n\n<List items={['one', 'two', 'three']}let:item>\n\t{#snippet item(text)}\n\t\t<span>{text}</span>\n\t{/snippet}\n\t<span slot=\"empty\">No items yet</span>\n\t{#snippet empty()}\n\t\t<span>No items yet</span>\n\t{/snippet}\n</List>\n```\n\n```svelte\n<!file: List.svelte>\n<script>\n\tlet { items,item, empty} = $props();\n</script>\n\n{#if items.length}\n\t<ul>\n\t\t{#each items as entry}\n\t\t\t<li>\n\t\t\t\t<slot item={entry} />\n\t\t\t\t{@render item(entry)}\n\t\t\t</li>\n\t\t{/each}\n\t</ul>\n{:else}\n\t<slot name=\"empty\" />\n\t{@render empty?.()}\n{/if}\n```\n\n> Slots were easy to get started with, but the more advanced the use case became, the more involved and confusing the syntax became:\n>\n> - the `let:` syntax was confusing to many people as it _creates_ a variable whereas all other `:` directives _receive_ a variable\n> - the scope of a variable declared with `let:` wasn't clear. In the example above, it may look like you can use the `item` slot prop in the `empty` slot, but that's not true\n> - named slots had to be applied to an element using the `slot` attribute. Sometimes you didn't want to create an element, so we had to add the `<svelte:fragment>` API\n> - named slots could also be applied to a component, which changed the semantics of where `let:` directives are available (even today us maintainers often don't know which way around it works)\n>\n> Snippets solve all of these problems by being much more readable and clear. At the same time they're more powerful as they allow you to define sections of UI that you can render _anywhere_, not just passing them as props to a component.\n\n## Migration script\n\nBy now you should have a pretty good understanding of the before/after and how the old syntax relates to the new syntax. It probably also became clear that a lot of these migrations are rather technical and repetitive — something you don't want to do by hand.\n\nWe thought the same, which is why we provide a migration script to do most of the migration automatically. You can upgrade your project by using `npx sv migrate svelte-5`. This will do the following things:\n\n- bump core dependencies in your `package.json`\n- migrate to runes (`let` → `$state` etc)\n- migrate to event attributes for DOM elements (`on:click` → `onclick`)\n- migrate slot creations to render tags (`<slot />` → `{@render children()}`)\n- migrate slot usages to snippets (`<div slot=\"x\">...</div>` → `{#snippet x()}<div>...</div>{/snippet}`)\n- migrate obvious component creations (`new Component(...)` → `mount(Component, ...)`)\n\nYou can also migrate a single component in VS Code through the `Migrate Component to Svelte 5 Syntax` command, or in our Playground through the `Migrate` button.\n\nNot everything can be migrated automatically, and some migrations need manual cleanup afterwards. The following sections describe these in more detail.\n\n### run\n\nYou may see that the migration script converts some of your `$:` statements to a `run` function which is imported from `svelte/legacy`. This happens if the migration script couldn't reliably migrate the statement to a `$derived` and concluded this is a side effect instead. In some cases this may be wrong and it's best to change this to use a `$derived` instead. In other cases it may be right, but since `$:` statements also ran on the server but `$effect` does not, it isn't safe to transform it as such. Instead, `run` is used as a stopgap solution. `run` mimics most of the characteristics of `$:`, in that it runs on the server once, and runs as `$effect.pre` on the client (`$effect.pre` runs _before_ changes are applied to the DOM; most likely you want to use `$effect` instead).\n\n```svelte\n<script>\n\timport { run } from 'svelte/legacy';\n\trun(() => {\n\t$effect(() => {\n\t\t// some side effect code\n\t})\n</script>\n```\n\n### Event modifiers\n\nEvent modifiers are not applicable to event attributes (e.g. you can't do `onclick|preventDefault={...}`). Therefore, when migrating event directives to event attributes, we need a function-replacement for these modifiers. These are imported from `svelte/legacy`, and should be migrated away from in favor of e.g. just using `event.preventDefault()`.\n\n```svelte\n<script>\n\timport { preventDefault } from 'svelte/legacy';\n</script>\n\n<button\n\tonclick={preventDefault((event) => {\n\t\tevent.preventDefault();\n\t\t// ...\n\t})}\n>\n\tclick me\n</button>\n```\n\n### Things that are not automigrated\n\nThe migration script does not convert `createEventDispatcher`. You need to adjust those parts manually. It doesn't do it because it's too risky because it could result in breakage for users of the component, which the migration script cannot find out.\n\nThe migration script does not convert `beforeUpdate/afterUpdate`. It doesn't do it because it's impossible to determine the actual intent of the code. As a rule of thumb you can often go with a combination of `$effect.pre` (runs at the same time as `beforeUpdate` did) and `tick` (imported from `svelte`, allows you to wait until changes are applied to the DOM and then do some work).\n\n## Components are no longer classes\n\nIn Svelte 3 and 4, components are classes. In Svelte 5 they are functions and should be instantiated differently. If you need to manually instantiate components, you should use `mount` or `hydrate` (imported from `svelte`) instead. If you see this error using SvelteKit, try updating to the latest version of SvelteKit first, which adds support for Svelte 5. If you're using Svelte without SvelteKit, you'll likely have a `main.js` file (or similar) which you need to adjust:\n\n```js\nimport { mount } from 'svelte';\nimport App from './App.svelte'\n\nconst app = new App({ target: document.getElementById(\"app\") });\nconst app = mount(App, { target: document.getElementById(\"app\") });\n\nexport default app;\n```\n\n`mount` and `hydrate` have the exact same API. The difference is that `hydrate` will pick up the Svelte's server-rendered HTML inside its target and hydrate it. Both return an object with the exports of the component and potentially property accessors (if compiled with `accessors: true`). They do not come with the `$on`, `$set` and `$destroy` methods you may know from the class component API. These are its replacements:\n\nFor `$on`, instead of listening to events, pass them via the `events` property on the options argument.\n\n```js\nimport { mount } from 'svelte';\nimport App from './App.svelte'\n\nconst app = new App({ target: document.getElementById(\"app\") });\napp.$on('event', callback);\nconst app = mount(App, { target: document.getElementById(\"app\"), events: { event: callback } });\n```\n\n\nFor `$set`, use `$state` instead to create a reactive property object and manipulate it. If you're doing this inside a `.js` or `.ts` file, adjust the ending to include `.svelte`, i.e. `.svelte.js` or `.svelte.ts`.\n\n```js\nimport { mount } from 'svelte';\nimport App from './App.svelte'\n\nconst app = new App({ target: document.getElementById(\"app\"), props: { foo: 'bar' } });\napp.$set({ foo: 'baz' });\nconst props = $state({ foo: 'bar' });\nconst app = mount(App, { target: document.getElementById(\"app\"), props });\nprops.foo = 'baz';\n```\n\nFor `$destroy`, use `unmount` instead.\n\n```js\nimport { mount, unmount } from 'svelte';\nimport App from './App.svelte'\n\nconst app = new App({ target: document.getElementById(\"app\"), props: { foo: 'bar' } });\napp.$destroy();\nconst app = mount(App, { target: document.getElementById(\"app\") });\nunmount(app);\n```\n\nAs a stop-gap-solution, you can also use `createClassComponent` or `asClassComponent` (imported from `svelte/legacy`) instead to keep the same API known from Svelte 4 after instantiating.\n\n```js\nimport { createClassComponent } from 'svelte/legacy';\nimport App from './App.svelte'\n\nconst app = new App({ target: document.getElementById(\"app\") });\nconst app = createClassComponent({ component: App, target: document.getElementById(\"app\") });\n\nexport default app;\n```\n\nIf this component is not under your control, you can use the `compatibility.componentApi` compiler option for auto-applied backwards compatibility, which means code using `new Component(...)` keeps working without adjustments (note that this adds a bit of overhead to each component). This will also add `$set` and `$on` methods for all component instances you get through `bind:this`.\n\n```js\n/// svelte.config.js\nexport default {\n\tcompilerOptions: {\n\t\tcompatibility: {\n\t\t\tcomponentApi: 4\n\t\t}\n\t}\n};\n```\n\nNote that `mount` and `hydrate` are _not_ synchronous, so things like `onMount` won't have been called by the time the function returns and the pending block of promises will not have been rendered yet (because `#await` waits a microtask to wait for a potentially immediately-resolved promise). If you need that guarantee, call `flushSync` (import from `'svelte'`) after calling `mount/hydrate`.\n\n### Server API changes\n\nSimilarly, components no longer have a `render` method when compiled for server-side rendering. Instead, pass the function to `render` from `svelte/server`:\n\n```js\nimport { render } from 'svelte/server';\nimport App from './App.svelte';\n\nconst { html, head } = App.render({ props: { message: 'hello' }});\nconst { html, head } = render(App, { props: { message: 'hello' }});\n```\n\nIn Svelte 4, rendering a component to a string also returned the CSS of all components. In Svelte 5, this is no longer the case by default because most of the time you're using a tooling chain that takes care of it in other ways (like SvelteKit). If you need CSS to be returned from `render`, you can set the `css` compiler option to `'injected'` and it will add `<style>` elements to the `head`.\n\n### Component typing changes\n\nThe change from classes towards functions is also reflected in the typings: `SvelteComponent`, the base class from Svelte 4, is deprecated in favour of the new `Component` type which defines the function shape of a Svelte component. To manually define a component shape in a `d.ts` file:\n\n```ts\nimport type { Component } from 'svelte';\nexport declare const MyComponent: Component<{\n\tfoo: string;\n}>;\n```\n\nTo declare that a component of a certain type is required:\n\n```js\nimport { ComponentA, ComponentB } from 'component-library';\nimport type { SvelteComponent } from 'svelte';\nimport type { Component } from 'svelte';\n\nlet C: typeof SvelteComponent<{ foo: string }> = $state(\nlet C: Component<{ foo: string }> = $state(\n\tMath.random() ? ComponentA : ComponentB\n);\n```\n\nThe two utility types `ComponentEvents` and `ComponentType` are also deprecated. `ComponentEvents` is obsolete because events are defined as callback props now, and `ComponentType` is obsolete because the new `Component` type is the component type already (i.e. `ComponentType<SvelteComponent<{ prop: string }>>` is equivalent to `Component<{ prop: string }>`).\n\n### bind:this changes\n\nBecause components are no longer classes, using `bind:this` no longer returns a class instance with `$set`, `$on` and `$destroy` methods on it. It only returns the instance exports (`export function/const`) and, if you're using the `accessors` option, a getter/setter-pair for each property.\n\n## `<svelte:component>` is no longer necessary\n\nIn Svelte 4, components are _static_ — if you render `<Thing>`, and the value of `Thing` changes, [nothing happens](/playground/7f1fa24f0ab44c1089dcbb03568f8dfa?version=4.2.18). To make it dynamic you had to use `<svelte:component>`.\n\nThis is no longer true in Svelte 5:\n\n```svelte\n<script>\n\timport A from './A.svelte';\n\timport B from './B.svelte';\n\n\tlet Thing = $state();\n</script>\n\n<select bind:value={Thing}>\n\t<option value={A}>A</option>\n\t<option value={B}>B</option>\n</select>\n\n<!-- these are equivalent -->\n<Thing />\n<svelte:component this={Thing} />\n```\nWhile migrating, keep in mind that your component's name should be capitalized (`Thing`) to distinguish it from elements, unless using dot notation.\n\n### Dot notation indicates a component\n\nIn Svelte 4, `<foo.bar>` would create an element with a tag name of `\"foo.bar\"`. In Svelte 5, `foo.bar` is treated as a component instead. This is particularly useful inside `each` blocks:\n\n```svelte\n{#each items as item}\n\t<item.component {...item.props} />\n{/each}\n```\n\n## Whitespace handling changed\n\nPreviously, Svelte employed a very complicated algorithm to determine if whitespace should be kept or not. Svelte 5 simplifies this which makes it easier to reason about as a developer. The rules are:\n\n- Whitespace between nodes is collapsed to one whitespace\n- Whitespace at the start and end of a tag is removed completely\n\n  This new behavior is slightly different from native HTML rendering. For example, `<p>foo<span> - bar</span></p>` will render:\n\n  - `foo - bar` in HTML\n  - `foo- bar` in Svelte 5\n\n  You can reintroduce the missing space by moving it outside the `<span>`...\n\n  ```svelte\n  <p>foo <span>- bar</span></p>\n  ```\n\n  ...or, if necessary for styling reasons, including it as an expression:\n\n  ```svelte\n  <p>foo<span>{' '}- bar</span></p>\n  ```\n\n- Certain exceptions apply such as keeping whitespace inside `pre` tags\n\nAs before, you can disable whitespace trimming by setting the `preserveWhitespace` option in your compiler settings or on a per-component basis in `<svelte:options>`.\n\n## Modern browser required\n\nSvelte 5 requires a modern browser (in other words, not Internet Explorer) for various reasons:\n\n- it uses [`Proxies`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)\n- elements with `clientWidth`/`clientHeight`/`offsetWidth`/`offsetHeight` bindings use a [`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) rather than a convoluted `<iframe>` hack\n- `<input type=\"range\" bind:value={...} />` only uses an `input` event listener, rather than also listening for `change` events as a fallback\n\nThe `legacy` compiler option, which generated bulkier but IE-friendly code, no longer exists.\n\n## Changes to compiler options\n\n- The `false`/`true` (already deprecated previously) and the `\"none\"` values were removed as valid values from the `css` option\n- The `legacy` option was repurposed\n- The `hydratable` option has been removed. Svelte components are always hydratable now\n- The `enableSourcemap` option has been removed. Source maps are always generated now, tooling can choose to ignore it\n- The `tag` option was removed. Use `<svelte:options customElement=\"tag-name\" />` inside the component instead\n- The `loopGuardTimeout`, `format`, `sveltePath`, `errorMode` and `varsReport` options were removed\n\n## The `children` prop is reserved\n\nContent inside component tags becomes a snippet prop called `children`. You cannot have a separate prop by that name.\n\n## Breaking changes in runes mode\n\nSome breaking changes only apply once your component is in runes mode.\n\n### Bindings to component exports are not allowed\n\nExports from runes mode components cannot be bound to directly. For example, having `export const foo = ...` in component `A` and then doing `<A bind:foo />` causes an error. Use `bind:this` instead — `<A bind:this={a} />` — and access the export as `a.foo`. This change makes things easier to reason about, as it enforces a clear separation between props and exports.\n\n### Bindings need to be explicitly defined using `$bindable()`\n\nIn Svelte 4 syntax, every property (declared via `export let`) is bindable, meaning you can `bind:` to it. In runes mode, properties are not bindable by default: you need to denote bindable props with the `$bindable` rune.\n\nIf a bindable property has a default value (e.g. `let { foo = $bindable('bar') } = $props();`), you need to pass a non-`undefined` value to that property if you're binding to it. This prevents ambiguous behavior — the parent and child must have the same value — and results in better performance (in Svelte 4, the default value was reflected back to the parent, resulting in wasteful additional render cycles).\n\n### `accessors` option is ignored\n\nSetting the `accessors` option to `true` makes properties of a component directly accessible on the component instance.\n\n```svelte\n<svelte:options accessors={true} />\n\n<script>\n\t// available via componentInstance.name\n\texport let name;\n</script>\n```\n\nIn runes mode, properties are never accessible on the component instance. You can use component exports instead if you need to expose them.\n\n```svelte\n<script>\n\tlet { name } = $props();\n\t// available via componentInstance.getName()\n\texport const getName = () => name;\n</script>\n```\n\nAlternatively, if the place where they are instantiated is under your control, you can also make use of runes inside `.js/.ts` files by adjusting their ending to include `.svelte`, i.e. `.svelte.js` or `.svelte.ts`, and then use `$state`:\n\n```js\nimport { mount } from 'svelte';\nimport App from './App.svelte'\n\nconst app = new App({ target: document.getElementById(\"app\"), props: { foo: 'bar' } });\napp.foo = 'baz'\nconst props = $state({ foo: 'bar' });\nconst app = mount(App, { target: document.getElementById(\"app\"), props });\nprops.foo = 'baz';\n```\n\n### `immutable` option is ignored\n\nSetting the `immutable` option has no effect in runes mode. This concept is replaced by how `$state` and its variations work.\n\n### Classes are no longer \"auto-reactive\"\n\nIn Svelte 4, doing the following triggered reactivity:\n\n```svelte\n<script>\n\tlet foo = new Foo();\n</script>\n\n<button on:click={() => (foo.value = 1)}>{foo.value}</button\n>\n```\n\nThis is because the Svelte compiler treated the assignment to `foo.value` as an instruction to update anything that referenced `foo`. In Svelte 5, reactivity is determined at runtime rather than compile time, so you should define `value` as a reactive `$state` field on the `Foo` class. Wrapping `new Foo()` with `$state(...)` will have no effect — only vanilla objects and arrays are made deeply reactive.\n\n### Touch events are passive\n\nWhen using `ontouchstart` and `ontouchmove` event attributes, the handlers are [passive](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#using_passive_listeners) to align with browser defaults. This greatly improves responsiveness by allowing the browser to scroll the document immediately, rather than waiting to see if the event handler calls `event.preventDefault()`.\n\nIn the very rare cases that you need to prevent these event defaults, you should use [`on`](/docs/svelte/svelte-events#on) instead (for example inside an action).\n\n### Attribute/prop syntax is stricter\n\nIn Svelte 4, complex attribute values needn't be quoted:\n\n```svelte\n<Component prop=this{is}valid />\n```\n\nThis is a footgun. In runes mode, if you want to concatenate stuff you must wrap the value in quotes:\n\n```svelte\n<Component prop=\"this{is}valid\" />\n```\n\nNote that Svelte 5 will also warn if you have a single expression wrapped in quotes, like `answer=\"{42}\"` — in Svelte 6, that will cause the value to be converted to a string, rather than passed as a number.\n\n### HTML structure is stricter\n\nIn Svelte 4, you were allowed to write HTML code that would be repaired by the browser when server-side rendering it. For example you could write this...\n\n```svelte\n<table>\n\t<tr>\n\t\t<td>hi</td>\n\t</tr>\n</table>\n```\n\n... and the browser would auto-insert a `<tbody>` element:\n\n```svelte\n<table>\n\t<tbody>\n\t\t<tr>\n\t\t\t<td>hi</td>\n\t\t</tr>\n\t</tbody>\n</table>\n```\n\nSvelte 5 is more strict about the HTML structure and will throw a compiler error in cases where the browser would repair the DOM.\n\n## Other breaking changes\n\n### Stricter `@const` assignment validation\n\nAssignments to destructured parts of a `@const` declaration are no longer allowed. It was an oversight that this was ever allowed.\n\n### :is(...), :has(...), and :where(...) are scoped\n\nPreviously, Svelte did not analyse selectors inside `:is(...)`, `:has(...)`, and `:where(...)`, effectively treating them as global. Svelte 5 analyses them in the context of the current component. Some selectors may now therefore be treated as unused if they were relying on this treatment. To fix this, use `:global(...)` inside the `:is(...)/:has(...)/:where(...)` selectors.\n\nWhen using Tailwind's `@apply` directive, add a `:global` selector to preserve rules that use Tailwind-generated `:is(...)` selectors:\n\n```css\nmain:global{\n\t@apply bg-blue-100 dark:bg-blue-900;\n}\n```\n\n### CSS hash position no longer deterministic\n\nPreviously Svelte would always insert the CSS hash last. This is no longer guaranteed in Svelte 5. This is only breaking if you [have very weird css selectors](https://stackoverflow.com/questions/15670631/does-the-order-of-classes-listed-on-an-item-affect-the-css).\n\n### Scoped CSS uses :where(...)\n\nTo avoid issues caused by unpredictable specificity changes, scoped CSS selectors now use `:where(.svelte-xyz123)` selector modifiers alongside `.svelte-xyz123` (where `xyz123` is, as previously, a hash of the `<style>` contents). You can read more detail [here](https://github.com/sveltejs/svelte/pull/10443).\n\nIn the event that you need to support ancient browsers that don't implement `:where`, you can manually alter the emitted CSS, at the cost of unpredictable specificity changes:\n\n```js\n// @errors: 2552\ncss = css.replace(/:where\\((.+?)\\)/, '$1');\n```\n\n### Error/warning codes have been renamed\n\nError and warning codes have been renamed. Previously they used dashes to separate the words, they now use underscores (e.g. foo-bar becomes foo_bar). Additionally, a handful of codes have been reworded slightly.\n\n### Reduced number of namespaces\n\nThe number of valid namespaces you can pass to the compiler option `namespace` has been reduced to `html` (the default), `mathml` and `svg`.\n\nThe `foreign` namespace was only useful for Svelte Native, which we're planning to support differently in a 5.x minor.\n\n### beforeUpdate/afterUpdate changes\n\n`beforeUpdate` no longer runs twice on initial render if it modifies a variable referenced in the template.\n\n`afterUpdate` callbacks in a parent component will now run after `afterUpdate` callbacks in any child components.\n\n`beforeUpdate/afterUpdate` no longer run when the component contains a `<slot>` and its content is updated.\n\nBoth functions are disallowed in runes mode — use `$effect.pre(...)` and `$effect(...)` instead.\n\n### `contenteditable` behavior change\n\nIf you have a `contenteditable` node with a corresponding binding _and_ a reactive value inside it (example: `<div contenteditable=true bind:textContent>count is {count}</div>`), then the value inside the contenteditable will not be updated by updates to `count` because the binding takes full control over the content immediately and it should only be updated through it.\n\n### `oneventname` attributes no longer accept string values\n\nIn Svelte 4, it was possible to specify event attributes on HTML elements as a string:\n\n```svelte\n<button onclick=\"alert('hello')\">...</button>\n```\n\nThis is not recommended, and is no longer possible in Svelte 5, where properties like `onclick` replace `on:click` as the mechanism for adding event handlers.\n\n### `null` and `undefined` become the empty string\n\nIn Svelte 4, `null` and `undefined` were printed as the corresponding string. In 99 out of 100 cases you want this to become the empty string instead, which is also what most other frameworks out there do. Therefore, in Svelte 5, `null` and `undefined` become the empty string.\n\n### `bind:files` values can only be `null`, `undefined` or `FileList`\n\n`bind:files` is now a two-way binding. As such, when setting a value, it needs to be either falsy (`null` or `undefined`) or of type `FileList`.\n\n### Bindings now react to form resets\n\nPreviously, bindings did not take into account `reset` event of forms, and therefore values could get out of sync with the DOM. Svelte 5 fixes this by placing a `reset` listener on the document and invoking bindings where necessary.\n\n### `walk` no longer exported\n\n`svelte/compiler` reexported `walk` from `estree-walker` for convenience. This is no longer true in Svelte 5, import it directly from that package instead in case you need it.\n\n### Content inside `svelte:options` is forbidden\n\nIn Svelte 4 you could have content inside a `<svelte:options />` tag. It was ignored, but you could write something in there. In Svelte 5, content inside that tag is a compiler error.\n\n### `<slot>` elements in declarative shadow roots are preserved\n\nSvelte 4 replaced the `<slot />` tag in all places with its own version of slots. Svelte 5 preserves them in the case they are a child of a `<template shadowrootmode=\"...\">` element.\n\n### `<svelte:element>` tag must be an expression\n\nIn Svelte 4, `<svelte:element this=\"div\">` is valid code. This makes little sense — you should just do `<div>`. In the vanishingly rare case that you _do_ need to use a literal value for some reason, you can do this:\n\n```svelte\n<svelte:element this={\"div\"}>\n```\n\nNote that whereas Svelte 4 would treat `<svelte:element this=\"input\">` (for example) identically to `<input>` for the purposes of determining which `bind:` directives could be applied, Svelte 5 does not.\n\n### `mount` plays transitions by default\n\nThe `mount` function used to render a component tree plays transitions by default unless the `intro` option is set to `false`. This is different from legacy class components which, when manually instantiated, didn't play transitions by default.\n\n### `<img src={...}>` and `{@html ...}` hydration mismatches are not repaired\n\nIn Svelte 4, if the value of a `src` attribute or `{@html ...}` tag differ between server and client (a.k.a. a hydration mismatch), the mismatch is repaired. This is very costly: setting a `src` attribute (even if it evaluates to the same thing) causes images and iframes to be reloaded, and reinserting a large blob of HTML is slow.\n\nSince these mismatches are extremely rare, Svelte 5 assumes that the values are unchanged, but in development will warn you if they are not. To force an update you can do something like this:\n\n```svelte\n<script>\n\tlet { markup, src } = $props();\n\n\tif (typeof window !== 'undefined') {\n\t\t// stash the values...\n\t\tconst initial = { markup, src };\n\n\t\t// unset them...\n\t\tmarkup = src = undefined;\n\n\t\t$effect(() => {\n\t\t\t// ...and reset after we've mounted\n\t\t\tmarkup = initial.markup;\n\t\t\tsrc = initial.src;\n\t\t});\n\t}\n</script>\n\n{@html markup}\n<img {src} />\n```\n\n### Hydration works differently\n\nSvelte 5 makes use of comments during server-side rendering which are used for more robust and efficient hydration on the client. You therefore should not remove comments from your HTML output if you intend to hydrate it, and if you manually authored HTML to be hydrated by a Svelte component, you need to adjust that HTML to include said comments at the correct positions.\n\n### `onevent` attributes are delegated\n\nEvent attributes replace event directives: Instead of `on:click={handler}` you write `onclick={handler}`. For backwards compatibility the `on:event` syntax is still supported and behaves the same as in Svelte 4. Some of the `onevent` attributes however are delegated, which means you need to take care to not stop event propagation on those manually, as they then might never reach the listener for this event type at the root.\n\n### `--style-props` uses a different element\n\nSvelte 5 uses an extra `<svelte-css-wrapper>` element instead of a `<div>` to wrap the component when using CSS custom properties.\n\n<!-- TODO in final docs, add link to corresponding section for more details -->","size_bytes":42791,"metadata":{"title":"Svelte 5 migration guide"},"created_at":"2025-07-18T15:47:39.008Z","updated_at":"2026-02-28T02:00:03.906Z"},{"path":"apps/svelte.dev/content/docs/svelte/07-misc/99-faq.md","title":"Frequently asked questions","filename":"99-faq.md","content":"## I'm new to Svelte. Where should I start?\n\nWe think the best way to get started is playing through the interactive [tutorial](/tutorial). Each step there is mainly focused on one specific aspect and is easy to follow. You'll be editing and running real Svelte components right in your browser.\n\nFive to ten minutes should be enough to get you up and running. An hour and a half should get you through the entire tutorial.\n\n## Where can I get support?\n\nIf your question is about certain syntax, the [reference docs](/docs/svelte) are a good place to start.\n\nStack Overflow is a popular forum to ask code-level questions or if you’re stuck with a specific error. Read through the existing questions tagged with [Svelte](https://stackoverflow.com/questions/tagged/svelte+or+svelte-3) or [ask your own](https://stackoverflow.com/questions/ask?tags=svelte)!\n\nThere are online forums and chats which are a great place for discussion about best practices, application architecture or just to get to know fellow Svelte users. [Our Discord](/chat) or [the Reddit channel](https://www.reddit.com/r/sveltejs/) are examples of that. If you have an answerable code-level question, Stack Overflow is usually a better fit.\n\n## Are there any third-party resources?\n\nSvelte Society maintains a [list of books and videos](https://sveltesociety.dev/collection/a-list-of-books-and-courses-ac01dd10363184fa).\n\n## How can I get VS Code to syntax-highlight my .svelte files?\n\nThere is an [official VS Code extension for Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode).\n\n## Is there a tool to automatically format my .svelte files?\n\nYou can use prettier with the [prettier-plugin-svelte](https://www.npmjs.com/package/prettier-plugin-svelte) plugin.\n\n## How do I document my components?\n\nIn editors which use the Svelte Language Server you can document Components, functions and exports using specially formatted comments.\n\n````svelte\n<script>\n\t/** What should we call the user? */\n\texport let name = 'world';\n</script>\n\n<!--\n@component\nHere's some documentation for this component.\nIt will show up on hover.\n\nYou can use markdown here.\nYou can also use code blocks here.\nUsage:\n  ```svelte\n  <main name=\"Arethra\">\n  ```\n-->\n<main>\n\t<h1>\n\t\tHello, {name}\n\t</h1>\n</main>\n````\n\nNote: The `@component` is necessary in the HTML comment which describes your component.\n\n## Does Svelte scale?\n\nThere will be a blog post about this eventually, but in the meantime, check out [this issue](https://github.com/sveltejs/svelte/issues/2546).\n\n## Is there a UI component library?\n\nThere are several [UI component libraries](/packages#component-libraries) as well as standalone components listed on [the packages page](/packages).\n\n## How do I test Svelte apps?\n\nHow your application is structured and where logic is defined will determine the best way to ensure it is properly tested. It is important to note that not all logic belongs within a component — this includes concerns such as data transformation, cross-component state management, and logging, among others. Remember that the Svelte library has its own test suite, so you do not need to write tests to validate implementation details provided by Svelte.\n\nA Svelte application will typically have three different types of tests: Unit, Component, and End-to-End (E2E).\n\n_Unit Tests_: Focus on testing business logic in isolation. Often this is validating individual functions and edge cases. By minimizing the surface area of these tests they can be kept lean and fast, and by extracting as much logic as possible from your Svelte components more of your application can be covered using them. When creating a new SvelteKit project, you will be asked whether you would like to setup [Vitest](https://vitest.dev/) for unit testing. There are a number of other test runners that could be used as well.\n\n_Component Tests_: Validating that a Svelte component mounts and interacts as expected throughout its lifecycle requires a tool that provides a Document Object Model (DOM). Components can be compiled (since Svelte is a compiler and not a normal library) and mounted to allow asserting against element structure, listeners, state, and all the other capabilities provided by a Svelte component. Tools for component testing range from an in-memory implementation like jsdom paired with a test runner like [Vitest](https://vitest.dev/) to solutions that leverage an actual browser to provide a visual testing capability such as [Playwright](https://playwright.dev/docs/test-components) or [Cypress](https://www.cypress.io/).\n\n_End-to-End Tests_: To ensure your users are able to interact with your application it is necessary to test it as a whole in a manner as close to production as possible. This is done by writing end-to-end (E2E) tests which load and interact with a deployed version of your application in order to simulate how the user will interact with your application. When creating a new SvelteKit project, you will be asked whether you would like to setup [Playwright](https://playwright.dev/) for end-to-end testing. There are many other E2E test libraries available for use as well.\n\nSome resources for getting started with testing:\n\n- [Svelte docs on testing](/docs/svelte/testing)\n- [Setup Vitest using the Svelte CLI](/docs/cli/vitest)\n- [Svelte Testing Library](https://testing-library.com/docs/svelte-testing-library/example/)\n- [Svelte Component Testing in Cypress](https://docs.cypress.io/guides/component-testing/svelte/overview)\n- [Example using uvu test runner with JSDOM](https://github.com/lukeed/uvu/tree/master/examples/svelte)\n- [Test Svelte components using Vitest & Playwright](https://davipon.hashnode.dev/test-svelte-component-using-vitest-playwright)\n- [Component testing with WebdriverIO](https://webdriver.io/docs/component-testing/svelte)\n\n## Is there a router?\n\nThe official routing library is [SvelteKit](/docs/kit). SvelteKit provides a filesystem router, server-side rendering (SSR), and hot module reloading (HMR) in one easy-to-use package. It shares similarities with Next.js for React and Nuxt.js for Vue. SvelteKit also supports hash-based routing for client-side applications.\n\nHowever, you can use any router library. A sampling of available routers are highlighted [on the packages page](/packages#routing).\n\n## How do I write a mobile app with Svelte?\n\nWhile most mobile apps are written without using JavaScript, if you'd like to leverage your existing Svelte components and knowledge of Svelte when building mobile apps, you can turn a [SvelteKit SPA](https://kit.svelte.dev/docs/single-page-apps) into a mobile app with [Tauri](https://v2.tauri.app/start/frontend/sveltekit/) or [Capacitor](https://capacitorjs.com/solution/svelte). Mobile features like the camera, geolocation, and push notifications are available via plugins for both platforms.\n\nSome work has been completed towards [custom renderer support in Svelte 5](https://github.com/sveltejs/svelte/issues/15470), but this feature is not yet available. The custom rendering API would support additional mobile frameworks like Lynx JS and Svelte Native. Svelte Native was an option available for Svelte 4, but Svelte 5 does not currently support it. Svelte Native lets you write NativeScript apps using Svelte components that contain [NativeScript UI components](https://docs.nativescript.org/ui/) rather than DOM elements, which may be familiar for users coming from React Native.\n\n## Can I tell Svelte not to remove my unused styles?\n\nNo. Svelte removes the styles from the component and warns you about them in order to prevent issues that would otherwise arise.\n\nSvelte's component style scoping works by generating a class unique to the given component, adding it to the relevant elements in the component that are under Svelte's control, and then adding it to each of the selectors in that component's styles. When the compiler can't see what elements a style selector applies to, there would be two bad options for keeping it:\n\n- If it keeps the selector and adds the scoping class to it, the selector will likely not match the expected elements in the component, and they definitely won't if they were created by a child component or `{@html ...}`.\n- If it keeps the selector without adding the scoping class to it, the given style will become a global style, affecting your entire page.\n\nIf you need to style something that Svelte can't identify at compile time, you will need to explicitly opt into global styles by using `:global(...)`. But also keep in mind that you can wrap `:global(...)` around only part of a selector. `.foo :global(.bar) { ... }` will style any `.bar` elements that appear within the component's `.foo` elements. As long as there's some parent element in the current component to start from, partially global selectors like this will almost always be able to get you what you want.\n\n## Is Svelte v2 still available?\n\nNew features aren't being added to it, and bugs will probably only be fixed if they are extremely nasty or present some sort of security vulnerability.\n\nThe documentation is still available [here](https://v2.svelte.dev/guide).\n\n## How do I do hot module reloading?\n\nWe recommend using [SvelteKit](/docs/kit), which supports HMR out of the box and is built on top of [Vite](https://vitejs.dev/) and [svelte-hmr](https://github.com/sveltejs/svelte-hmr). There are also community plugins for [rollup](https://github.com/rixo/rollup-plugin-svelte-hot) and [webpack](https://github.com/sveltejs/svelte-loader).","size_bytes":9574,"metadata":{"title":"Frequently asked questions"},"created_at":"2025-07-18T15:47:39.012Z","updated_at":"2026-02-14T01:33:24.883Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md","title":"svelte","filename":"20-svelte.md","content":"```js\n// @noErrors\nimport {\n\tSvelteComponent,\n\tSvelteComponentTyped,\n\tafterUpdate,\n\tbeforeUpdate,\n\tcreateContext,\n\tcreateEventDispatcher,\n\tcreateRawSnippet,\n\tflushSync,\n\tfork,\n\tgetAbortSignal,\n\tgetAllContexts,\n\tgetContext,\n\thasContext,\n\thydratable,\n\thydrate,\n\tmount,\n\tonDestroy,\n\tonMount,\n\tsetContext,\n\tsettled,\n\ttick,\n\tunmount,\n\tuntrack\n} from 'svelte';\n```\n\n## SvelteComponent\n\nThis was the base class for Svelte components in Svelte 4. Svelte 5+ components\nare completely different under the hood. For typing, use `Component` instead.\nTo instantiate components, use `mount` instead.\nSee [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.\n\n<div class=\"ts-block\">\n\n```dts\nclass SvelteComponent<\n\tProps extends Record<string, any> = Record<string, any>,\n\tEvents extends Record<string, any> = any,\n\tSlots extends Record<string, any> = any\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nstatic element?: typeof HTMLElement;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe custom element version of the component. Only present if compiled with the `customElement` compiler option\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n[prop: string]: any;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nconstructor(options: ComponentConstructorOptions<Properties<Props, Slots>>);\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> This constructor only exists when using the `asClassComponent` compatibility helper, which\nis a stop-gap solution. Migrate towards using `mount` instead. See\n[migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.\n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n$destroy(): void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> This method only exists when using one of the legacy compatibility helpers, which\nis a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)\nfor more info.\n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n$on<K extends Extract<keyof Events, string>>(\n\ttype: K,\n\tcallback: (e: Events[K]) => void\n): () => void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> This method only exists when using one of the legacy compatibility helpers, which\nis a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)\nfor more info.\n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n$set(props: Partial<Props>): void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> This method only exists when using one of the legacy compatibility helpers, which\nis a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)\nfor more info.\n\n</div>\n\n</div>\n</div></div>\n\n\n\n## SvelteComponentTyped\n\n<blockquote class=\"tag deprecated note\">\n\nUse `Component` instead. See [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information.\n\n</blockquote>\n\n<div class=\"ts-block\">\n\n```dts\nclass SvelteComponentTyped<\n\tProps extends Record<string, any> = Record<string, any>,\n\tEvents extends Record<string, any> = any,\n\tSlots extends Record<string, any> = any\n> extends SvelteComponent<Props, Events, Slots> {}\n```\n\n</div>\n\n\n\n## afterUpdate\n\n<blockquote class=\"tag deprecated note\">\n\nUse [`$effect`](/docs/svelte/$effect) instead\n\n</blockquote>\n\nSchedules a callback to run immediately after the component has been updated.\n\nThe first time the callback runs will be after the initial `onMount`.\n\nIn runes mode use `$effect` instead.\n\n<div class=\"ts-block\">\n\n```dts\nfunction afterUpdate(fn: () => void): void;\n```\n\n</div>\n\n\n\n## beforeUpdate\n\n<blockquote class=\"tag deprecated note\">\n\nUse [`$effect.pre`](/docs/svelte/$effect#$effect.pre) instead\n\n</blockquote>\n\nSchedules a callback to run immediately before the component is updated after any state change.\n\nThe first time the callback runs will be before the initial `onMount`.\n\nIn runes mode use `$effect.pre` instead.\n\n<div class=\"ts-block\">\n\n```dts\nfunction beforeUpdate(fn: () => void): void;\n```\n\n</div>\n\n\n\n## createContext\n\n<blockquote class=\"since note\">\n\nAvailable since 5.40.0\n\n</blockquote>\n\nReturns a `[get, set]` pair of functions for working with context in a type-safe way.\n\n`get` will throw an error if no parent component called `set`.\n\n<div class=\"ts-block\">\n\n```dts\nfunction createContext<T>(): [() => T, (context: T) => T];\n```\n\n</div>\n\n\n\n## createEventDispatcher\n\n<blockquote class=\"tag deprecated note\">\n\nUse callback props and/or the `$host()` rune instead — see [migration guide](/docs/svelte/v5-migration-guide#Event-changes-Component-events)\n\n</blockquote>\n\nCreates an event dispatcher that can be used to dispatch [component events](/docs/svelte/legacy-on#Component-events).\nEvent dispatchers are functions that can take two arguments: `name` and `detail`.\n\nComponent events created with `createEventDispatcher` create a\n[CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).\nThese events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture).\nThe `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail)\nproperty and can contain any type of data.\n\nThe event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument:\n```ts\nconst dispatch = createEventDispatcher<{\n loaded: null; // does not take a detail argument\n change: string; // takes a detail argument of type string, which is required\n optional: number | null; // takes an optional detail argument of type number\n}>();\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction createEventDispatcher<\n\tEventMap extends Record<string, any> = any\n>(): EventDispatcher<EventMap>;\n```\n\n</div>\n\n\n\n## createRawSnippet\n\nCreate a snippet programmatically\n\n<div class=\"ts-block\">\n\n```dts\nfunction createRawSnippet<Params extends unknown[]>(\n\tfn: (...params: Getters<Params>) => {\n\t\trender: () => string;\n\t\tsetup?: (element: Element) => void | (() => void);\n\t}\n): Snippet<Params>;\n```\n\n</div>\n\n\n\n## flushSync\n\nSynchronously flush any pending updates.\nReturns void if no callback is provided, otherwise returns the result of calling the callback.\n\n<div class=\"ts-block\">\n\n```dts\nfunction flushSync<T = void>(fn?: (() => T) | undefined): T;\n```\n\n</div>\n\n\n\n## fork\n\n<blockquote class=\"since note\">\n\nAvailable since 5.42\n\n</blockquote>\n\nCreates a 'fork', in which state changes are evaluated but not applied to the DOM.\nThis is useful for speculatively loading data (for example) when you suspect that\nthe user is about to take some action.\n\nFrameworks like SvelteKit can use this to preload data when the user touches or\nhovers over a link, making any subsequent navigation feel instantaneous.\n\nThe `fn` parameter is a synchronous function that modifies some state. The\nstate changes will be reverted after the fork is initialised, then reapplied\nif and when the fork is eventually committed.\n\nWhen it becomes clear that a fork will _not_ be committed (e.g. because the\nuser navigated elsewhere), it must be discarded to avoid leaking memory.\n\n<div class=\"ts-block\">\n\n```dts\nfunction fork(fn: () => void): Fork;\n```\n\n</div>\n\n\n\n## getAbortSignal\n\nReturns an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that aborts when the current [derived](/docs/svelte/$derived) or [effect](/docs/svelte/$effect) re-runs or is destroyed.\n\nMust be called while a derived or effect is running.\n\n```svelte\n<script>\n\timport { getAbortSignal } from 'svelte';\n\n\tlet { id } = $props();\n\n\tasync function getData(id) {\n\t\tconst response = await fetch(`/items/${id}`, {\n\t\t\tsignal: getAbortSignal()\n\t\t});\n\n\t\treturn await response.json();\n\t}\n\n\tconst data = $derived(await getData(id));\n</script>\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction getAbortSignal(): AbortSignal;\n```\n\n</div>\n\n\n\n## getAllContexts\n\nRetrieves the whole context map that belongs to the closest parent component.\nMust be called during component initialisation. Useful, for example, if you\nprogrammatically create a component and want to pass the existing context to it.\n\n<div class=\"ts-block\">\n\n```dts\nfunction getAllContexts<\n\tT extends Map<any, any> = Map<any, any>\n>(): T;\n```\n\n</div>\n\n\n\n## getContext\n\nRetrieves the context that belongs to the closest parent component with the specified `key`.\nMust be called during component initialisation.\n\n[`createContext`](/docs/svelte/svelte#createContext) is a type-safe alternative.\n\n<div class=\"ts-block\">\n\n```dts\nfunction getContext<T>(key: any): T;\n```\n\n</div>\n\n\n\n## hasContext\n\nChecks whether a given `key` has been set in the context of a parent component.\nMust be called during component initialisation.\n\n<div class=\"ts-block\">\n\n```dts\nfunction hasContext(key: any): boolean;\n```\n\n</div>\n\n\n\n## hydratable\n\n<div class=\"ts-block\">\n\n```dts\nfunction hydratable<T>(key: string, fn: () => T): T;\n```\n\n</div>\n\n\n\n## hydrate\n\nHydrates a component on the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component\n\n<div class=\"ts-block\">\n\n```dts\nfunction hydrate<\n\tProps extends Record<string, any>,\n\tExports extends Record<string, any>\n>(\n\tcomponent:\n\t\t| ComponentType<SvelteComponent<Props>>\n\t\t| Component<Props, Exports, any>,\n\toptions: {} extends Props\n\t\t? {\n\t\t\t\ttarget: Document | Element | ShadowRoot;\n\t\t\t\tprops?: Props;\n\t\t\t\tevents?: Record<string, (e: any) => any>;\n\t\t\t\tcontext?: Map<any, any>;\n\t\t\t\tintro?: boolean;\n\t\t\t\trecover?: boolean;\n\t\t\t\ttransformError?: (error: unknown) => unknown;\n\t\t\t}\n\t\t: {\n\t\t\t\ttarget: Document | Element | ShadowRoot;\n\t\t\t\tprops: Props;\n\t\t\t\tevents?: Record<string, (e: any) => any>;\n\t\t\t\tcontext?: Map<any, any>;\n\t\t\t\tintro?: boolean;\n\t\t\t\trecover?: boolean;\n\t\t\t\ttransformError?: (error: unknown) => unknown;\n\t\t\t}\n): Exports;\n```\n\n</div>\n\n\n\n## mount\n\nMounts a component to the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component.\nTransitions will play during the initial render unless the `intro` option is set to `false`.\n\n<div class=\"ts-block\">\n\n```dts\nfunction mount<\n\tProps extends Record<string, any>,\n\tExports extends Record<string, any>\n>(\n\tcomponent:\n\t\t| ComponentType<SvelteComponent<Props>>\n\t\t| Component<Props, Exports, any>,\n\toptions: MountOptions<Props>\n): Exports;\n```\n\n</div>\n\n\n\n## onDestroy\n\nSchedules a callback to run immediately before the component is unmounted.\n\nOut of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the\nonly one that runs inside a server-side component.\n\n<div class=\"ts-block\">\n\n```dts\nfunction onDestroy(fn: () => any): void;\n```\n\n</div>\n\n\n\n## onMount\n\n`onMount`, like [`$effect`](/docs/svelte/$effect), schedules a function to run as soon as the component has been mounted to the DOM.\nUnlike `$effect`, the provided function only runs once.\n\nIt must be called during the component's initialisation (but doesn't need to live _inside_ the component;\nit can be called from an external module). If a function is returned _synchronously_ from `onMount`,\nit will be called when the component is unmounted.\n\n`onMount` functions do not run during [server-side rendering](/docs/svelte/svelte-server#render).\n\n<div class=\"ts-block\">\n\n```dts\nfunction onMount<T>(\n\tfn: () =>\n\t\t| NotFunction<T>\n\t\t| Promise<NotFunction<T>>\n\t\t| (() => any)\n): void;\n```\n\n</div>\n\n\n\n## setContext\n\nAssociates an arbitrary `context` object with the current component and the specified `key`\nand returns that object. The context is then available to children of the component\n(including slotted content) with `getContext`.\n\nLike lifecycle functions, this must be called during component initialisation.\n\n[`createContext`](/docs/svelte/svelte#createContext) is a type-safe alternative.\n\n<div class=\"ts-block\">\n\n```dts\nfunction setContext<T>(key: any, context: T): T;\n```\n\n</div>\n\n\n\n## settled\n\n<blockquote class=\"since note\">\n\nAvailable since 5.36\n\n</blockquote>\n\nReturns a promise that resolves once any state changes, and asynchronous work resulting from them,\nhave resolved and the DOM has been updated\n\n<div class=\"ts-block\">\n\n```dts\nfunction settled(): Promise<void>;\n```\n\n</div>\n\n\n\n## tick\n\nReturns a promise that resolves once any pending state changes have been applied.\n\n<div class=\"ts-block\">\n\n```dts\nfunction tick(): Promise<void>;\n```\n\n</div>\n\n\n\n## unmount\n\nUnmounts a component that was previously mounted using `mount` or `hydrate`.\n\nSince 5.13.0, if `options.outro` is `true`, [transitions](/docs/svelte/transition) will play before the component is removed from the DOM.\n\nReturns a `Promise` that resolves after transitions have completed if `options.outro` is true, or immediately otherwise (prior to 5.13.0, returns `void`).\n\n```js\n// @errors: 7031\nimport { mount, unmount } from 'svelte';\nimport App from './App.svelte';\n\nconst app = mount(App, { target: document.body });\n\n// later...\nunmount(app, { outro: true });\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction unmount(\n\tcomponent: Record<string, any>,\n\toptions?:\n\t\t| {\n\t\t\t\toutro?: boolean;\n\t\t  }\n\t\t| undefined\n): Promise<void>;\n```\n\n</div>\n\n\n\n## untrack\n\nWhen used inside a [`$derived`](/docs/svelte/$derived) or [`$effect`](/docs/svelte/$effect),\nany state read inside `fn` will not be treated as a dependency.\n\n```ts\n$effect(() => {\n\t// this will run when `data` changes, but not when `time` changes\n\tsave(data, {\n\t\ttimestamp: untrack(() => time)\n\t});\n});\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction untrack<T>(fn: () => T): T;\n```\n\n</div>\n\n\n\n## Component\n\nCan be used to create strongly typed Svelte components.\n\n#### Example:\n\nYou have component library on npm called `component-library`, from which\nyou export a component called `MyComponent`. For Svelte+TypeScript users,\nyou want to provide typings. Therefore you create a `index.d.ts`:\n```ts\nimport type { Component } from 'svelte';\nexport declare const MyComponent: Component<{ foo: string }> {}\n```\nTyping this makes it possible for IDEs like VS Code with the Svelte extension\nto provide intellisense and to use the component like this in a Svelte file\nwith TypeScript:\n```svelte\n<script lang=\"ts\">\n\timport { MyComponent } from \"component-library\";\n</script>\n<MyComponent foo={'bar'} />\n```\n\n<div class=\"ts-block\">\n\n```dts\ninterface Component<\n\tProps extends Record<string, any> = {},\n\tExports extends Record<string, any> = {},\n\tBindings extends keyof Props | '' = string\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n(\n\tthis: void,\n\tinternals: ComponentInternals,\n\tprops: Props\n): {\n\t/**\n\t * @deprecated This method only exists when using one of the legacy compatibility helpers, which\n\t * is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)\n\t * for more info.\n\t */\n\t$on?(type: string, callback: (e: any) => void): () => void;\n\t/**\n\t * @deprecated This method only exists when using one of the legacy compatibility helpers, which\n\t * is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)\n\t * for more info.\n\t */\n\t$set?(props: Partial<Props>): void;\n} & Exports;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `internal` An internal object used by Svelte. Do not use or modify.\n- `props` The props passed to the component.\n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nelement?: typeof HTMLElement;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe custom element version of the component. Only present if compiled with the `customElement` compiler option\n\n</div>\n</div></div>\n\n## ComponentConstructorOptions\n\n<blockquote class=\"tag deprecated note\">\n\nIn Svelte 4, components are classes. In Svelte 5, they are functions.\nUse `mount` instead to instantiate components.\nSee [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)\nfor more info.\n\n</blockquote>\n\n<div class=\"ts-block\">\n\n```dts\ninterface ComponentConstructorOptions<\n\tProps extends Record<string, any> = Record<string, any>\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ntarget: Element | Document | ShadowRoot;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nanchor?: Element;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nprops?: Props;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncontext?: Map<any, any>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nhydrate?: boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nintro?: boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrecover?: boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsync?: boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nidPrefix?: string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\n$$inline?: boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ntransformError?: (error: unknown) => unknown;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## ComponentEvents\n\n<blockquote class=\"tag deprecated note\">\n\nThe new `Component` type does not have a dedicated Events type. Use `ComponentProps` instead.\n\n</blockquote>\n\n<div class=\"ts-block\">\n\n```dts\ntype ComponentEvents<Comp extends SvelteComponent> =\n\tComp extends SvelteComponent<any, infer Events>\n\t\t? Events\n\t\t: never;\n```\n\n</div>\n\n## ComponentInternals\n\nInternal implementation details that vary between environments\n\n<div class=\"ts-block\">\n\n```dts\ntype ComponentInternals = Branded<{}, 'ComponentInternals'>;\n```\n\n</div>\n\n## ComponentProps\n\nConvenience type to get the props the given component expects.\n\nExample: Ensure a variable contains the props expected by `MyComponent`:\n\n```ts\nimport type { ComponentProps } from 'svelte';\nimport MyComponent from './MyComponent.svelte';\n\n// Errors if these aren't the correct props expected by MyComponent.\nconst props: ComponentProps<typeof MyComponent> = { foo: 'bar' };\n```\n\n\nExample: A generic function that accepts some component and infers the type of its props:\n\n```ts\nimport type { Component, ComponentProps } from 'svelte';\nimport MyComponent from './MyComponent.svelte';\n\nfunction withProps<TComponent extends Component<any>>(\n\tcomponent: TComponent,\n\tprops: ComponentProps<TComponent>\n) {};\n\n// Errors if the second argument is not the correct props expected by the component in the first argument.\nwithProps(MyComponent, { foo: 'bar' });\n```\n\n<div class=\"ts-block\">\n\n```dts\ntype ComponentProps<\n\tComp extends SvelteComponent | Component<any, any>\n> =\n\tComp extends SvelteComponent<infer Props>\n\t\t? Props\n\t\t: Comp extends Component<infer Props, any>\n\t\t\t? Props\n\t\t\t: never;\n```\n\n</div>\n\n## ComponentType\n\n<blockquote class=\"tag deprecated note\">\n\nThis type is obsolete when working with the new `Component` type.\n\n</blockquote>\n\n<div class=\"ts-block\">\n\n```dts\ntype ComponentType<\n\tComp extends SvelteComponent = SvelteComponent\n> = (new (\n\toptions: ComponentConstructorOptions<\n\t\tComp extends SvelteComponent<infer Props>\n\t\t\t? Props\n\t\t\t: Record<string, any>\n\t>\n) => Comp) & {\n\t/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */\n\telement?: typeof HTMLElement;\n};\n```\n\n</div>\n\n## EventDispatcher\n\n<div class=\"ts-block\">\n\n```dts\ninterface EventDispatcher<\n\tEventMap extends Record<string, any>\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n<Type extends keyof EventMap>(\n\t...args: null extends EventMap[Type]\n\t\t? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]\n\t\t: undefined extends EventMap[Type]\n\t\t\t? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]\n\t\t\t: [type: Type, parameter: EventMap[Type], options?: DispatchOptions]\n): boolean;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## Fork\n\n<blockquote class=\"since note\">\n\nAvailable since 5.42\n\n</blockquote>\n\nRepresents work that is happening off-screen, such as data being preloaded\nin anticipation of the user navigating\n\n<div class=\"ts-block\">\n\n```dts\ninterface Fork {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ncommit(): Promise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\nCommit the fork. The promise will resolve once the state change has been applied\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndiscard(): void;\n```\n\n<div class=\"ts-block-property-details\">\n\nDiscard the fork\n\n</div>\n</div></div>\n\n## MountOptions\n\nDefines the options accepted by the `mount()` function.\n\n<div class=\"ts-block\">\n\n```dts\ntype MountOptions<\n\tProps extends Record<string, any> = Record<string, any>\n> = {\n\t/**\n\t * Target element where the component will be mounted.\n\t */\n\ttarget: Document | Element | ShadowRoot;\n\t/**\n\t * Optional node inside `target`. When specified, it is used to render the component immediately before it.\n\t */\n\tanchor?: Node;\n\t/**\n\t * Allows the specification of events.\n\t * @deprecated Use callback props instead.\n\t */\n\tevents?: Record<string, (e: any) => any>;\n\t/**\n\t * Can be accessed via `getContext()` at the component level.\n\t */\n\tcontext?: Map<any, any>;\n\t/**\n\t * Whether or not to play transitions on initial render.\n\t * @default true\n\t */\n\tintro?: boolean;\n\t/**\n\t * A function that transforms errors caught by error boundaries before they are passed to the `failed` snippet.\n\t * Defaults to the identity function.\n\t */\n\ttransformError?: (\n\t\terror: unknown\n\t) => unknown | Promise<unknown>;\n} & ({} extends Props\n\t? {\n\t\t\t/**\n\t\t\t * Component properties.\n\t\t\t */\n\t\t\tprops?: Props;\n\t\t}\n\t: {\n\t\t\t/**\n\t\t\t * Component properties.\n\t\t\t */\n\t\t\tprops: Props;\n\t\t});\n```\n\n</div>\n\n## Snippet\n\nThe type of a `#snippet` block. You can use it to (for example) express that your component expects a snippet of a certain type:\n```ts\nlet { banner }: { banner: Snippet<[{ text: string }]> } = $props();\n```\nYou can only call a snippet through the `{@render ...}` tag.\n\nSee the [snippet documentation](/docs/svelte/snippet) for more info.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Snippet<Parameters extends unknown[] = []> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n(\n\tthis: void,\n\t// this conditional allows tuples but not arrays. Arrays would indicate a\n\t// rest parameter type, which is not supported. If rest parameters are added\n\t// in the future, the condition can be removed.\n\t...args: number extends Parameters['length'] ? never : Parameters\n): {\n\t'{@render ...} must be called with a Snippet': \"import type { Snippet } from 'svelte'\";\n} & typeof SnippetReturn;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>","size_bytes":23556,"metadata":{"title":"svelte"},"created_at":"2025-07-18T15:47:39.019Z","updated_at":"2026-02-20T02:00:04.581Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md","title":"svelte/action","filename":"21-svelte-action.md","content":"This module provides types for [actions](use), which have been superseded by [attachments](@attach).\n\n## Action\n\nActions are functions that are called when an element is created.\nYou can use this interface to type such actions.\nThe following example defines an action that only works on `<div>` elements\nand optionally accepts a parameter which it has a default value for:\n```ts\nexport const myAction: Action<HTMLDivElement, { someProperty: boolean } | undefined> = (node, param = { someProperty: true }) => {\n\t// ...\n}\n```\n`Action<HTMLDivElement>` and `Action<HTMLDivElement, undefined>` both signal that the action accepts no parameters.\n\nYou can return an object with methods `update` and `destroy` from the function and type which additional attributes and events it has.\nSee interface `ActionReturn` for more details.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Action<\n\tElement = HTMLElement,\n\tParameter = undefined,\n\tAttributes extends Record<string, any> = Record<\n\t\tnever,\n\t\tany\n\t>\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n<Node extends Element>(\n\t...args: undefined extends Parameter\n\t\t? [node: Node, parameter?: Parameter]\n\t\t: [node: Node, parameter: Parameter]\n): void | ActionReturn<Parameter, Attributes>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## ActionReturn\n\nActions can return an object containing the two properties defined in this interface. Both are optional.\n- update: An action can have a parameter. This method will be called whenever that parameter changes,\n\timmediately after Svelte has applied updates to the markup. `ActionReturn` and `ActionReturn<undefined>` both\n\tmean that the action accepts no parameters.\n- destroy: Method that is called after the element is unmounted\n\nAdditionally, you can specify which additional attributes and events the action enables on the applied element.\nThis applies to TypeScript typings only and has no effect at runtime.\n\nExample usage:\n```ts\ninterface Attributes {\n\tnewprop?: string;\n\t'on:event': (e: CustomEvent<boolean>) => void;\n}\n\nexport function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes> {\n\t// ...\n\treturn {\n\t\tupdate: (updatedParameter) => {...},\n\t\tdestroy: () => {...}\n\t};\n}\n```\n\n<div class=\"ts-block\">\n\n```dts\ninterface ActionReturn<\n\tParameter = undefined,\n\tAttributes extends Record<string, any> = Record<\n\t\tnever,\n\t\tany\n\t>\n> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nupdate?: (parameter: Parameter) => void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndestroy?: () => void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>","size_bytes":2697,"metadata":{"title":"svelte/action"},"created_at":"2025-07-18T15:47:39.020Z","updated_at":"2025-07-31T23:52:36.239Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md","title":"svelte/animate","filename":"21-svelte-animate.md","content":"```js\n// @noErrors\nimport { flip } from 'svelte/animate';\n```\n\n## flip\n\nThe flip function calculates the start and end position of an element and animates between them, translating the x and y values.\n`flip` stands for [First, Last, Invert, Play](https://aerotwist.com/blog/flip-your-animations/).\n\n<div class=\"ts-block\">\n\n```dts\nfunction flip(\n\tnode: Element,\n\t{\n\t\tfrom,\n\t\tto\n\t}: {\n\t\tfrom: DOMRect;\n\t\tto: DOMRect;\n\t},\n\tparams?: FlipParams\n): AnimationConfig;\n```\n\n</div>\n\n\n\n## AnimationConfig\n\n<div class=\"ts-block\">\n\n```dts\ninterface AnimationConfig {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: (t: number) => number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncss?: (t: number, u: number) => string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ntick?: (t: number, u: number) => void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## FlipParams\n\n<div class=\"ts-block\">\n\n```dts\ninterface FlipParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number | ((len: number) => number);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: (t: number) => number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>","size_bytes":1726,"metadata":{"title":"svelte/animate"},"created_at":"2025-07-18T15:47:39.023Z","updated_at":"2025-07-18T15:47:40.322Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-attachments.md","title":"svelte/attachments","filename":"21-svelte-attachments.md","content":"```js\n// @noErrors\nimport { createAttachmentKey, fromAction } from 'svelte/attachments';\n```\n\n## createAttachmentKey\n\n<blockquote class=\"since note\">\n\nAvailable since 5.29\n\n</blockquote>\n\nCreates an object key that will be recognised as an attachment when the object is spread onto an element,\nas a programmatic alternative to using `{@attach ...}`. This can be useful for library authors, though\nis generally not needed when building an app.\n\n```svelte\n<script>\n\timport { createAttachmentKey } from 'svelte/attachments';\n\n\tconst props = {\n\t\tclass: 'cool',\n\t\tonclick: () => alert('clicked'),\n\t\t[createAttachmentKey()]: (node) => {\n\t\t\tnode.textContent = 'attached!';\n\t\t}\n\t};\n</script>\n\n<button {...props}>click me</button>\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction createAttachmentKey(): symbol;\n```\n\n</div>\n\n\n\n## fromAction\n\nConverts an [action](/docs/svelte/use) into an [attachment](/docs/svelte/@attach) keeping the same behavior.\nIt's useful if you want to start using attachments on components but you have actions provided by a library.\n\nNote that the second argument, if provided, must be a function that _returns_ the argument to the\naction function, not the argument itself.\n\n```svelte\n<!-- with an action -->\n<div use:foo={bar}>...</div>\n\n<!-- with an attachment -->\n<div {@attach fromAction(foo, () => bar)}>...</div>\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction fromAction<\n\tE extends EventTarget,\n\tT extends unknown\n>(\n\taction:\n\t\t| Action<E, T>\n\t\t| ((element: E, arg: T) => void | ActionReturn<T>),\n\tfn: () => T\n): Attachment<E>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction fromAction<E extends EventTarget>(\n\taction:\n\t\t| Action<E, void>\n\t\t| ((element: E) => void | ActionReturn<void>)\n): Attachment<E>;\n```\n\n</div>\n\n\n\n## Attachment\n\nAn [attachment](/docs/svelte/@attach) is a function that runs when an element is mounted\nto the DOM, and optionally returns a function that is called when the element is later removed.\n\nIt can be attached to an element with an `{@attach ...}` tag, or by spreading an object containing\na property created with [`createAttachmentKey`](/docs/svelte/svelte-attachments#createAttachmentKey).\n\n<div class=\"ts-block\">\n\n```dts\ninterface Attachment<T extends EventTarget = Element> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n(element: T): void | (() => void);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>","size_bytes":2441,"metadata":{"tags":"attachments","title":"svelte/attachments"},"created_at":"2025-07-18T15:47:39.025Z","updated_at":"2026-02-14T01:33:24.884Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md","title":"svelte/compiler","filename":"21-svelte-compiler.md","content":"```js\n// @noErrors\nimport {\n\tVERSION,\n\tcompile,\n\tcompileModule,\n\tmigrate,\n\tparse,\n\tparseCss,\n\tpreprocess,\n\tprint,\n\twalk\n} from 'svelte/compiler';\n```\n\n## VERSION\n\nThe current version, as set in package.json.\n\n<div class=\"ts-block\">\n\n```dts\nconst VERSION: string;\n```\n\n</div>\n\n\n\n## compile\n\n`compile` converts your `.svelte` source code into a JavaScript module that exports a component\n\n<div class=\"ts-block\">\n\n```dts\nfunction compile(\n\tsource: string,\n\toptions: CompileOptions\n): CompileResult;\n```\n\n</div>\n\n\n\n## compileModule\n\n`compileModule` takes your JavaScript source code containing runes, and turns it into a JavaScript module.\n\n<div class=\"ts-block\">\n\n```dts\nfunction compileModule(\n\tsource: string,\n\toptions: ModuleCompileOptions\n): CompileResult;\n```\n\n</div>\n\n\n\n## migrate\n\nDoes a best-effort migration of Svelte code towards using runes, event attributes and render tags.\nMay throw an error if the code is too complex to migrate automatically.\n\n<div class=\"ts-block\">\n\n```dts\nfunction migrate(\n\tsource: string,\n\t{\n\t\tfilename,\n\t\tuse_ts\n\t}?:\n\t\t| {\n\t\t\t\tfilename?: string;\n\t\t\t\tuse_ts?: boolean;\n\t\t  }\n\t\t| undefined\n): {\n\tcode: string;\n};\n```\n\n</div>\n\n\n\n## parse\n\nThe parse function parses a component, returning only its abstract syntax tree.\n\nThe `modern` option (`false` by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST.\n`modern` will become `true` by default in Svelte 6, and the option will be removed in Svelte 7.\n\n<div class=\"ts-block\">\n\n```dts\nfunction parse(\n\tsource: string,\n\toptions: {\n\t\tfilename?: string;\n\t\tmodern: true;\n\t\tloose?: boolean;\n\t}\n): AST.Root;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction parse(\n\tsource: string,\n\toptions?:\n\t\t| {\n\t\t\t\tfilename?: string;\n\t\t\t\tmodern?: false;\n\t\t\t\tloose?: boolean;\n\t\t  }\n\t\t| undefined\n): Record<string, any>;\n```\n\n</div>\n\n\n\n## parseCss\n\nThe parseCss function parses a CSS stylesheet, returning its abstract syntax tree.\n\n<div class=\"ts-block\">\n\n```dts\nfunction parseCss(source: string): AST.CSS.StyleSheetFile;\n```\n\n</div>\n\n\n\n## preprocess\n\nThe preprocess function provides convenient hooks for arbitrarily transforming component source code.\nFor example, it can be used to convert a `<style lang=\"sass\">` block into vanilla CSS.\n\n<div class=\"ts-block\">\n\n```dts\nfunction preprocess(\n\tsource: string,\n\tpreprocessor: PreprocessorGroup | PreprocessorGroup[],\n\toptions?:\n\t\t| {\n\t\t\t\tfilename?: string;\n\t\t  }\n\t\t| undefined\n): Promise<Processed>;\n```\n\n</div>\n\n\n\n## print\n\n`print` converts a Svelte AST node back into Svelte source code.\nIt is primarily intended for tools that parse and transform components using the compiler’s modern AST representation.\n\n`print(ast)` requires an AST node produced by parse with modern: true, or any sub-node within that modern AST.\nThe result contains the generated source and a corresponding source map.\nThe output is valid Svelte, but formatting details such as whitespace or quoting may differ from the original.\n\n<div class=\"ts-block\">\n\n```dts\nfunction print(\n\tast: AST.SvelteNode,\n\toptions?: Options | undefined\n): {\n\tcode: string;\n\tmap: any;\n};\n```\n\n</div>\n\n\n\n## walk\n\n<blockquote class=\"tag deprecated note\">\n\nReplace this with `import { walk } from 'estree-walker'`\n\n</blockquote>\n\n<div class=\"ts-block\">\n\n```dts\nfunction walk(): never;\n```\n\n</div>\n\n\n\n## AST\n\n<div class=\"ts-block\">\n\n```dts\nnamespace AST {\n\texport interface BaseNode {\n\t\ttype: string;\n\t\tstart: number;\n\t\tend: number;\n\t}\n\n\texport interface Fragment {\n\t\ttype: 'Fragment';\n\t\tnodes: Array<\n\t\t\tText | Tag | ElementLike | Block | Comment\n\t\t>;\n\t}\n\n\texport interface Root extends BaseNode {\n\t\ttype: 'Root';\n\t\t/**\n\t\t * Inline options provided by `<svelte:options>` — these override options passed to `compile(...)`\n\t\t */\n\t\toptions: SvelteOptions | null;\n\t\tfragment: Fragment;\n\t\t/** The parsed `<style>` element, if exists */\n\t\tcss: AST.CSS.StyleSheet | null;\n\t\t/** The parsed `<script>` element, if exists */\n\t\tinstance: Script | null;\n\t\t/** The parsed `<script module>` element, if exists */\n\t\tmodule: Script | null;\n\t\t/** Comments found in <script> and {expressions} */\n\t\tcomments: JSComment[];\n\t}\n\n\texport interface SvelteOptions {\n\t\t// start/end info (needed for warnings and for our Prettier plugin)\n\t\tstart: number;\n\t\tend: number;\n\t\t// options\n\t\trunes?: boolean;\n\t\timmutable?: boolean;\n\t\taccessors?: boolean;\n\t\tpreserveWhitespace?: boolean;\n\t\tnamespace?: Namespace;\n\t\tcss?: 'injected';\n\t\tcustomElement?: {\n\t\t\ttag?: string;\n\t\t\tshadow?:\n\t\t\t\t| 'open'\n\t\t\t\t| 'none'\n\t\t\t\t| ObjectExpression\n\t\t\t\t| undefined;\n\t\t\tprops?: Record<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\tattribute?: string;\n\t\t\t\t\treflect?: boolean;\n\t\t\t\t\ttype?:\n\t\t\t\t\t\t| 'Array'\n\t\t\t\t\t\t| 'Boolean'\n\t\t\t\t\t\t| 'Number'\n\t\t\t\t\t\t| 'Object'\n\t\t\t\t\t\t| 'String';\n\t\t\t\t}\n\t\t\t>;\n\t\t\t/**\n\t\t\t * Is of type\n\t\t\t * ```ts\n\t\t\t * (ceClass: new () => HTMLElement) => new () => HTMLElement\n\t\t\t * ```\n\t\t\t */\n\t\t\textend?: ArrowFunctionExpression | Identifier;\n\t\t};\n\t\tattributes: Attribute[];\n\t}\n\n\t/** Static text */\n\texport interface Text extends BaseNode {\n\t\ttype: 'Text';\n\t\t/** Text with decoded HTML entities */\n\t\tdata: string;\n\t\t/** The original text, with undecoded HTML entities */\n\t\traw: string;\n\t}\n\n\t/** A (possibly reactive) template expression — `{...}` */\n\texport interface ExpressionTag extends BaseNode {\n\t\ttype: 'ExpressionTag';\n\t\texpression: Expression;\n\t}\n\n\t/** A (possibly reactive) HTML template expression — `{@html ...}` */\n\texport interface HtmlTag extends BaseNode {\n\t\ttype: 'HtmlTag';\n\t\texpression: Expression;\n\t}\n\n\t/** An HTML comment */\n\t// TODO rename to disambiguate\n\texport interface Comment extends BaseNode {\n\t\ttype: 'Comment';\n\t\t/** the contents of the comment */\n\t\tdata: string;\n\t}\n\n\t/** A `{@const ...}` tag */\n\texport interface ConstTag extends BaseNode {\n\t\ttype: 'ConstTag';\n\t\tdeclaration: VariableDeclaration & {\n\t\t\tdeclarations: [\n\t\t\t\tVariableDeclarator & {\n\t\t\t\t\tid: Pattern;\n\t\t\t\t\tinit: Expression;\n\t\t\t\t}\n\t\t\t];\n\t\t};\n\t}\n\n\t/** A `{@debug ...}` tag */\n\texport interface DebugTag extends BaseNode {\n\t\ttype: 'DebugTag';\n\t\tidentifiers: Identifier[];\n\t}\n\n\t/** A `{@render foo(...)} tag */\n\texport interface RenderTag extends BaseNode {\n\t\ttype: 'RenderTag';\n\t\texpression:\n\t\t\t| SimpleCallExpression\n\t\t\t| (ChainExpression & {\n\t\t\t\t\texpression: SimpleCallExpression;\n\t\t\t  });\n\t}\n\n\t/** A `{@attach foo(...)} tag */\n\texport interface AttachTag extends BaseNode {\n\t\ttype: 'AttachTag';\n\t\texpression: Expression;\n\t}\n\n\t/** An `animate:` directive */\n\texport interface AnimateDirective extends BaseAttribute {\n\t\ttype: 'AnimateDirective';\n\t\t/** The 'x' in `animate:x` */\n\t\tname: string;\n\t\t/** The y in `animate:x={y}` */\n\t\texpression: null | Expression;\n\t}\n\n\t/** A `bind:` directive */\n\texport interface BindDirective extends BaseAttribute {\n\t\ttype: 'BindDirective';\n\t\t/** The 'x' in `bind:x` */\n\t\tname: string;\n\t\t/** The y in `bind:x={y}` */\n\t\texpression:\n\t\t\t| Identifier\n\t\t\t| MemberExpression\n\t\t\t| SequenceExpression;\n\t}\n\n\t/** A `class:` directive */\n\texport interface ClassDirective extends BaseAttribute {\n\t\ttype: 'ClassDirective';\n\t\t/** The 'x' in `class:x` */\n\t\tname: 'class';\n\t\t/** The 'y' in `class:x={y}`, or the `x` in `class:x` */\n\t\texpression: Expression;\n\t}\n\n\t/** A `let:` directive */\n\texport interface LetDirective extends BaseAttribute {\n\t\ttype: 'LetDirective';\n\t\t/** The 'x' in `let:x` */\n\t\tname: string;\n\t\t/** The 'y' in `let:x={y}` */\n\t\texpression:\n\t\t\t| null\n\t\t\t| Identifier\n\t\t\t| ArrayExpression\n\t\t\t| ObjectExpression;\n\t}\n\n\t/** An `on:` directive */\n\texport interface OnDirective extends BaseAttribute {\n\t\ttype: 'OnDirective';\n\t\t/** The 'x' in `on:x` */\n\t\tname: string;\n\t\t/** The 'y' in `on:x={y}` */\n\t\texpression: null | Expression;\n\t\tmodifiers: Array<\n\t\t\t| 'capture'\n\t\t\t| 'nonpassive'\n\t\t\t| 'once'\n\t\t\t| 'passive'\n\t\t\t| 'preventDefault'\n\t\t\t| 'self'\n\t\t\t| 'stopImmediatePropagation'\n\t\t\t| 'stopPropagation'\n\t\t\t| 'trusted'\n\t\t>;\n\t}\n\n\t/** A `style:` directive */\n\texport interface StyleDirective extends BaseAttribute {\n\t\ttype: 'StyleDirective';\n\t\t/** The 'x' in `style:x` */\n\t\tname: string;\n\t\t/** The 'y' in `style:x={y}` */\n\t\tvalue:\n\t\t\t| true\n\t\t\t| ExpressionTag\n\t\t\t| Array<ExpressionTag | Text>;\n\t\tmodifiers: Array<'important'>;\n\t}\n\n\t// TODO have separate in/out/transition directives\n\t/** A `transition:`, `in:` or `out:` directive */\n\texport interface TransitionDirective extends BaseAttribute {\n\t\ttype: 'TransitionDirective';\n\t\t/** The 'x' in `transition:x` */\n\t\tname: string;\n\t\t/** The 'y' in `transition:x={y}` */\n\t\texpression: null | Expression;\n\t\tmodifiers: Array<'local' | 'global'>;\n\t\t/** True if this is a `transition:` or `in:` directive */\n\t\tintro: boolean;\n\t\t/** True if this is a `transition:` or `out:` directive */\n\t\toutro: boolean;\n\t}\n\n\t/** A `use:` directive */\n\texport interface UseDirective extends BaseAttribute {\n\t\ttype: 'UseDirective';\n\t\t/** The 'x' in `use:x` */\n\t\tname: string;\n\t\t/** The 'y' in `use:x={y}` */\n\t\texpression: null | Expression;\n\t}\n\n\texport interface BaseElement extends BaseNode {\n\t\tname: string;\n\t\tname_loc: SourceLocation;\n\t\tattributes: Array<\n\t\t\tAttribute | SpreadAttribute | Directive | AttachTag\n\t\t>;\n\t\tfragment: Fragment;\n\t}\n\n\texport interface Component extends BaseElement {\n\t\ttype: 'Component';\n\t}\n\n\texport interface TitleElement extends BaseElement {\n\t\ttype: 'TitleElement';\n\t\tname: 'title';\n\t}\n\n\texport interface SlotElement extends BaseElement {\n\t\ttype: 'SlotElement';\n\t\tname: 'slot';\n\t}\n\n\texport interface RegularElement extends BaseElement {\n\t\ttype: 'RegularElement';\n\t}\n\n\texport interface SvelteBody extends BaseElement {\n\t\ttype: 'SvelteBody';\n\t\tname: 'svelte:body';\n\t}\n\n\texport interface SvelteComponent extends BaseElement {\n\t\ttype: 'SvelteComponent';\n\t\tname: 'svelte:component';\n\t\texpression: Expression;\n\t}\n\n\texport interface SvelteDocument extends BaseElement {\n\t\ttype: 'SvelteDocument';\n\t\tname: 'svelte:document';\n\t}\n\n\texport interface SvelteElement extends BaseElement {\n\t\ttype: 'SvelteElement';\n\t\tname: 'svelte:element';\n\t\ttag: Expression;\n\t}\n\n\texport interface SvelteFragment extends BaseElement {\n\t\ttype: 'SvelteFragment';\n\t\tname: 'svelte:fragment';\n\t}\n\n\texport interface SvelteBoundary extends BaseElement {\n\t\ttype: 'SvelteBoundary';\n\t\tname: 'svelte:boundary';\n\t}\n\n\texport interface SvelteHead extends BaseElement {\n\t\ttype: 'SvelteHead';\n\t\tname: 'svelte:head';\n\t}\n\n\t/** This is only an intermediate representation while parsing, it doesn't exist in the final AST */\n\texport interface SvelteOptionsRaw extends BaseElement {\n\t\ttype: 'SvelteOptions';\n\t\tname: 'svelte:options';\n\t}\n\n\texport interface SvelteSelf extends BaseElement {\n\t\ttype: 'SvelteSelf';\n\t\tname: 'svelte:self';\n\t}\n\n\texport interface SvelteWindow extends BaseElement {\n\t\ttype: 'SvelteWindow';\n\t\tname: 'svelte:window';\n\t}\n\n\t/** An `{#each ...}` block */\n\texport interface EachBlock extends BaseNode {\n\t\ttype: 'EachBlock';\n\t\texpression: Expression;\n\t\t/** The `entry` in `{#each item as entry}`. `null` if `as` part is omitted */\n\t\tcontext: Pattern | null;\n\t\tbody: Fragment;\n\t\tfallback?: Fragment;\n\t\tindex?: string;\n\t\tkey?: Expression;\n\t}\n\n\t/** An `{#if ...}` block */\n\texport interface IfBlock extends BaseNode {\n\t\ttype: 'IfBlock';\n\t\telseif: boolean;\n\t\ttest: Expression;\n\t\tconsequent: Fragment;\n\t\talternate: Fragment | null;\n\t}\n\n\t/** An `{#await ...}` block */\n\texport interface AwaitBlock extends BaseNode {\n\t\ttype: 'AwaitBlock';\n\t\texpression: Expression;\n\t\t// TODO can/should we move these inside the ThenBlock and CatchBlock?\n\t\t/** The resolved value inside the `then` block */\n\t\tvalue: Pattern | null;\n\t\t/** The rejection reason inside the `catch` block */\n\t\terror: Pattern | null;\n\t\tpending: Fragment | null;\n\t\tthen: Fragment | null;\n\t\tcatch: Fragment | null;\n\t}\n\n\texport interface KeyBlock extends BaseNode {\n\t\ttype: 'KeyBlock';\n\t\texpression: Expression;\n\t\tfragment: Fragment;\n\t}\n\n\texport interface SnippetBlock extends BaseNode {\n\t\ttype: 'SnippetBlock';\n\t\texpression: Identifier;\n\t\tparameters: Pattern[];\n\t\ttypeParams?: string;\n\t\tbody: Fragment;\n\t}\n\n\texport interface BaseAttribute extends BaseNode {\n\t\tname: string;\n\t\tname_loc: SourceLocation | null;\n\t}\n\n\texport interface Attribute extends BaseAttribute {\n\t\ttype: 'Attribute';\n\t\t/**\n\t\t * Quoted/string values are represented by an array, even if they contain a single expression like `\"{x}\"`\n\t\t */\n\t\tvalue:\n\t\t\t| true\n\t\t\t| ExpressionTag\n\t\t\t| Array<Text | ExpressionTag>;\n\t}\n\n\texport interface SpreadAttribute extends BaseNode {\n\t\ttype: 'SpreadAttribute';\n\t\texpression: Expression;\n\t}\n\n\texport interface Script extends BaseNode {\n\t\ttype: 'Script';\n\t\tcontext: 'default' | 'module';\n\t\tcontent: Program;\n\t\tattributes: Attribute[];\n\t}\n\n\texport interface JSComment {\n\t\ttype: 'Line' | 'Block';\n\t\tvalue: string;\n\t\tstart: number;\n\t\tend: number;\n\t\tloc: {\n\t\t\tstart: { line: number; column: number };\n\t\t\tend: { line: number; column: number };\n\t\t};\n\t}\n\n\texport type AttributeLike =\n\t\t| Attribute\n\t\t| SpreadAttribute\n\t\t| Directive;\n\n\texport type Directive =\n\t\t| AST.AnimateDirective\n\t\t| AST.BindDirective\n\t\t| AST.ClassDirective\n\t\t| AST.LetDirective\n\t\t| AST.OnDirective\n\t\t| AST.StyleDirective\n\t\t| AST.TransitionDirective\n\t\t| AST.UseDirective;\n\n\texport type Block =\n\t\t| AST.EachBlock\n\t\t| AST.IfBlock\n\t\t| AST.AwaitBlock\n\t\t| AST.KeyBlock\n\t\t| AST.SnippetBlock;\n\n\texport type ElementLike =\n\t\t| AST.Component\n\t\t| AST.TitleElement\n\t\t| AST.SlotElement\n\t\t| AST.RegularElement\n\t\t| AST.SvelteBody\n\t\t| AST.SvelteBoundary\n\t\t| AST.SvelteComponent\n\t\t| AST.SvelteDocument\n\t\t| AST.SvelteElement\n\t\t| AST.SvelteFragment\n\t\t| AST.SvelteHead\n\t\t| AST.SvelteOptionsRaw\n\t\t| AST.SvelteSelf\n\t\t| AST.SvelteWindow\n\t\t| AST.SvelteBoundary;\n\n\texport type Tag =\n\t\t| AST.AttachTag\n\t\t| AST.ConstTag\n\t\t| AST.DebugTag\n\t\t| AST.ExpressionTag\n\t\t| AST.HtmlTag\n\t\t| AST.RenderTag;\n\n\texport type TemplateNode =\n\t\t| AST.Root\n\t\t| AST.Text\n\t\t| Tag\n\t\t| ElementLike\n\t\t| AST.Attribute\n\t\t| AST.SpreadAttribute\n\t\t| Directive\n\t\t| AST.AttachTag\n\t\t| AST.Comment\n\t\t| Block;\n\n\texport type SvelteNode =\n\t\t| Node\n\t\t| TemplateNode\n\t\t| AST.Fragment\n\t\t| _CSS.Node\n\t\t| Script;\n\n\texport type { _CSS as CSS };\n}\n```\n\n</div>\n\n## CompileError\n\n<div class=\"ts-block\">\n\n```dts\ninterface CompileError extends ICompileDiagnostic {}\n```\n\n</div>\n\n## CompileOptions\n\n<div class=\"ts-block\">\n\n```dts\ninterface CompileOptions extends ModuleCompileOptions {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nname?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nSets the name of the resulting JavaScript class (though the compiler will rename it if it would otherwise conflict with other variables in scope).\nIf unspecified, will be inferred from `filename`\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncustomElement?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nIf `true`, tells the compiler to generate a custom element constructor instead of a regular Svelte component.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\naccessors?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n- <span class=\"tag deprecated\">deprecated</span> This will have no effect in runes mode\n\n</div>\n\nIf `true`, getters and setters will be created for the component's props. If `false`, they will only be created for readonly exported values (i.e. those declared with `const`, `class` and `function`). If compiling with `customElement: true` this option defaults to `true`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nnamespace?: Namespace;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `'html'`\n\n</div>\n\nThe namespace of the element; e.g., `\"html\"`, `\"svg\"`, `\"mathml\"`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nimmutable?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n- <span class=\"tag deprecated\">deprecated</span> This will have no effect in runes mode\n\n</div>\n\nIf `true`, tells the compiler that you promise not to mutate any objects.\nThis allows it to be less conservative about checking whether values have changed.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncss?: 'injected' | 'external';\n```\n\n<div class=\"ts-block-property-details\">\n\n- `'injected'`: styles will be included in the `head` when using `render(...)`, and injected into the document (if not already present) when the component mounts. For components compiled as custom elements, styles are injected to the shadow root.\n- `'external'`: the CSS will only be returned in the `css` field of the compilation result. Most Svelte bundler plugins will set this to `'external'` and use the CSS that is statically generated for better performance, as it will result in smaller JavaScript bundles and the output can be served as cacheable `.css` files.\nThis is always `'injected'` when compiling with `customElement` mode.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncssHash?: CssHashGetter;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `undefined`\n\n</div>\n\nA function that takes a `{ hash, css, name, filename }` argument and returns the string that is used as a classname for scoped CSS.\nIt defaults to returning `svelte-${hash(filename ?? css)}`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\npreserveComments?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nIf `true`, your HTML comments will be preserved in the output. By default, they are stripped out.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\npreserveWhitespace?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nIf `true`, whitespace inside and between elements is kept as you typed it, rather than removed or collapsed to a single space where possible.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nfragments?: 'html' | 'tree';\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `'html'`\n- <span class=\"tag since\">available since</span> v5.33\n\n</div>\n\nWhich strategy to use when cloning DOM fragments:\n\n- `html` populates a `<template>` with `innerHTML` and clones it. This is faster, but cannot be used if your app's [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) includes [`require-trusted-types-for 'script'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/require-trusted-types-for)\n- `tree` creates the fragment one element at a time and _then_ clones it. This is slower, but works everywhere\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrunes?: boolean | undefined;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `undefined`\n\n</div>\n\nSet to `true` to force the compiler into runes mode, even if there are no indications of runes usage.\nSet to `false` to force the compiler into ignoring runes, even if there are indications of runes usage.\nSet to `undefined` (the default) to infer runes mode from the component code.\nIs always `true` for JS/TS modules compiled with Svelte.\nWill be `true` by default in Svelte 6.\nNote that setting this to `true` in your `svelte.config.js` will force runes mode for your entire project, including components in `node_modules`,\nwhich is likely not what you want. If you're using Vite, consider using [dynamicCompileOptions](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#dynamiccompileoptions) instead.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndiscloseVersion?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `true`\n\n</div>\n\nIf `true`, exposes the Svelte major version in the browser by adding it to a `Set` stored in the global `window.__svelte.v`.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncompatibility?: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> Use these only as a temporary solution before migrating your code\n\n</div>\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\ncomponentApi?: 4 | 5;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `5`\n\n</div>\n\nApplies a transformation so that the default export of Svelte files can still be instantiated the same way as in Svelte 4 —\nas a class when compiling for the browser (as though using `createClassComponent(MyComponent, {...})` from `svelte/legacy`)\nor as an object with a `.render(...)` method when compiling for the server\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsourcemap?: object | string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `null`\n\n</div>\n\nAn initial sourcemap that will be merged into the final output sourcemap.\nThis is usually the preprocessor sourcemap.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\noutputFilename?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `null`\n\n</div>\n\nUsed for your JavaScript sourcemap.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncssOutputFilename?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `null`\n\n</div>\n\nUsed for your CSS sourcemap.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nhmr?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nIf `true`, compiles components with hot reloading support.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nmodernAst?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nIf `true`, returns the modern version of the AST.\nWill become `true` by default in Svelte 6, and the option will be removed in Svelte 7.\n\n</div>\n</div></div>\n\n## CompileResult\n\nThe return value of `compile` from `svelte/compiler`\n\n<div class=\"ts-block\">\n\n```dts\ninterface CompileResult {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\njs: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\nThe compiled JavaScript\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\ncode: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe generated code\n\n</div>\n</div>\n<div class=\"ts-block-property\">\n\n```dts\nmap: SourceMap;\n```\n\n<div class=\"ts-block-property-details\">\n\nA source map\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncss: null | {\n\t/** The generated code */\n\tcode: string;\n\t/** A source map */\n\tmap: SourceMap;\n\t/** Whether or not the CSS includes global rules */\n\thasGlobal: boolean;\n};\n```\n\n<div class=\"ts-block-property-details\">\n\nThe compiled CSS\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nwarnings: Warning[];\n```\n\n<div class=\"ts-block-property-details\">\n\nAn array of warning objects that were generated during compilation. Each warning has several properties:\n- `code` is a string identifying the category of warning\n- `message` describes the issue in human-readable terms\n- `start` and `end`, if the warning relates to a specific location, are objects with `line`, `column` and `character` properties\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nmetadata: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\nMetadata about the compiled component\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nrunes: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\nWhether the file was compiled in runes mode, either because of an explicit option or inferred from usage.\nFor `compileModule`, this is always `true`\n\n</div>\n</div></div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nast: any;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe AST\n\n</div>\n</div></div>\n\n## MarkupPreprocessor\n\nA markup preprocessor that takes a string of code and returns a processed version.\n\n<div class=\"ts-block\">\n\n```dts\ntype MarkupPreprocessor = (options: {\n\t/**\n\t * The whole Svelte file content\n\t */\n\tcontent: string;\n\t/**\n\t * The filename of the Svelte file\n\t */\n\tfilename?: string;\n}) => Processed | void | Promise<Processed | void>;\n```\n\n</div>\n\n## ModuleCompileOptions\n\n<div class=\"ts-block\">\n\n```dts\ninterface ModuleCompileOptions {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndev?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `false`\n\n</div>\n\nIf `true`, causes extra code to be added that will perform runtime checks and provide debugging information during development.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ngenerate?: 'client' | 'server' | false;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `'client'`\n\n</div>\n\nIf `\"client\"`, Svelte emits code designed to run in the browser.\nIf `\"server\"`, Svelte emits code suitable for server-side rendering.\nIf `false`, nothing is generated. Useful for tooling that is only interested in warnings.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nfilename?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nUsed for debugging hints and sourcemaps. Your bundler plugin will set it automatically.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nrootDir?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag\">default</span> `process.cwd() on node-like environments, undefined elsewhere`\n\n</div>\n\nUsed for ensuring filenames don't leak filesystem information. Your bundler plugin will set it automatically.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nwarningFilter?: (warning: Warning) => boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\nA function that gets a `Warning` as an argument and returns a boolean.\nUse this to filter out warnings. Return `true` to keep the warning, `false` to discard it.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nexperimental?: {/*…*/}\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag since\">available since</span> v5.36\n\n</div>\n\nExperimental options\n\n<div class=\"ts-block-property-children\"><div class=\"ts-block-property\">\n\n```dts\nasync?: boolean;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag since\">available since</span> v5.36\n\n</div>\n\nAllow `await` keyword in deriveds, template expressions, and the top level of components\n\n</div>\n</div></div>\n\n</div>\n</div></div>\n\n## Preprocessor\n\nA script/style preprocessor that takes a string of code and returns a processed version.\n\n<div class=\"ts-block\">\n\n```dts\ntype Preprocessor = (options: {\n\t/**\n\t * The script/style tag content\n\t */\n\tcontent: string;\n\t/**\n\t * The attributes on the script/style tag\n\t */\n\tattributes: Record<string, string | boolean>;\n\t/**\n\t * The whole Svelte file content\n\t */\n\tmarkup: string;\n\t/**\n\t * The filename of the Svelte file\n\t */\n\tfilename?: string;\n}) => Processed | void | Promise<Processed | void>;\n```\n\n</div>\n\n## PreprocessorGroup\n\nA preprocessor group is a set of preprocessors that are applied to a Svelte file.\n\n<div class=\"ts-block\">\n\n```dts\ninterface PreprocessorGroup {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nname?: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nName of the preprocessor. Will be a required option in the next major version\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nmarkup?: MarkupPreprocessor;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nstyle?: Preprocessor;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nscript?: Preprocessor;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## Processed\n\nThe result of a preprocessor run. If the preprocessor does not return a result, it is assumed that the code is unchanged.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Processed {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ncode: string;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe new code\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nmap?: string | object;\n```\n\n<div class=\"ts-block-property-details\">\n\nA source map mapping back to the original code\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndependencies?: string[];\n```\n\n<div class=\"ts-block-property-details\">\n\nA list of additional files to watch for changes\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nattributes?: Record<string, string | boolean>;\n```\n\n<div class=\"ts-block-property-details\">\n\nOnly for script/style preprocessors: The updated attributes to set on the tag. If undefined, attributes stay unchanged.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ntoString?: () => string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## Warning\n\n<div class=\"ts-block\">\n\n```dts\ninterface Warning extends ICompileDiagnostic {}\n```\n\n</div>","size_bytes":29647,"metadata":{"title":"svelte/compiler"},"created_at":"2025-07-18T15:47:39.027Z","updated_at":"2026-02-28T02:00:03.914Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-easing.md","title":"svelte/easing","filename":"21-svelte-easing.md","content":"```js\n// @noErrors\nimport {\n\tbackIn,\n\tbackInOut,\n\tbackOut,\n\tbounceIn,\n\tbounceInOut,\n\tbounceOut,\n\tcircIn,\n\tcircInOut,\n\tcircOut,\n\tcubicIn,\n\tcubicInOut,\n\tcubicOut,\n\telasticIn,\n\telasticInOut,\n\telasticOut,\n\texpoIn,\n\texpoInOut,\n\texpoOut,\n\tlinear,\n\tquadIn,\n\tquadInOut,\n\tquadOut,\n\tquartIn,\n\tquartInOut,\n\tquartOut,\n\tquintIn,\n\tquintInOut,\n\tquintOut,\n\tsineIn,\n\tsineInOut,\n\tsineOut\n} from 'svelte/easing';\n```\n\n## backIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction backIn(t: number): number;\n```\n\n</div>\n\n\n\n## backInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction backInOut(t: number): number;\n```\n\n</div>\n\n\n\n## backOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction backOut(t: number): number;\n```\n\n</div>\n\n\n\n## bounceIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction bounceIn(t: number): number;\n```\n\n</div>\n\n\n\n## bounceInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction bounceInOut(t: number): number;\n```\n\n</div>\n\n\n\n## bounceOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction bounceOut(t: number): number;\n```\n\n</div>\n\n\n\n## circIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction circIn(t: number): number;\n```\n\n</div>\n\n\n\n## circInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction circInOut(t: number): number;\n```\n\n</div>\n\n\n\n## circOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction circOut(t: number): number;\n```\n\n</div>\n\n\n\n## cubicIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction cubicIn(t: number): number;\n```\n\n</div>\n\n\n\n## cubicInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction cubicInOut(t: number): number;\n```\n\n</div>\n\n\n\n## cubicOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction cubicOut(t: number): number;\n```\n\n</div>\n\n\n\n## elasticIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction elasticIn(t: number): number;\n```\n\n</div>\n\n\n\n## elasticInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction elasticInOut(t: number): number;\n```\n\n</div>\n\n\n\n## elasticOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction elasticOut(t: number): number;\n```\n\n</div>\n\n\n\n## expoIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction expoIn(t: number): number;\n```\n\n</div>\n\n\n\n## expoInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction expoInOut(t: number): number;\n```\n\n</div>\n\n\n\n## expoOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction expoOut(t: number): number;\n```\n\n</div>\n\n\n\n## linear\n\n<div class=\"ts-block\">\n\n```dts\nfunction linear(t: number): number;\n```\n\n</div>\n\n\n\n## quadIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction quadIn(t: number): number;\n```\n\n</div>\n\n\n\n## quadInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction quadInOut(t: number): number;\n```\n\n</div>\n\n\n\n## quadOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction quadOut(t: number): number;\n```\n\n</div>\n\n\n\n## quartIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction quartIn(t: number): number;\n```\n\n</div>\n\n\n\n## quartInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction quartInOut(t: number): number;\n```\n\n</div>\n\n\n\n## quartOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction quartOut(t: number): number;\n```\n\n</div>\n\n\n\n## quintIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction quintIn(t: number): number;\n```\n\n</div>\n\n\n\n## quintInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction quintInOut(t: number): number;\n```\n\n</div>\n\n\n\n## quintOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction quintOut(t: number): number;\n```\n\n</div>\n\n\n\n## sineIn\n\n<div class=\"ts-block\">\n\n```dts\nfunction sineIn(t: number): number;\n```\n\n</div>\n\n\n\n## sineInOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction sineInOut(t: number): number;\n```\n\n</div>\n\n\n\n## sineOut\n\n<div class=\"ts-block\">\n\n```dts\nfunction sineOut(t: number): number;\n```\n\n</div>","size_bytes":3439,"metadata":{"title":"svelte/easing"},"created_at":"2025-07-18T15:47:39.029Z","updated_at":"2025-07-18T15:47:40.329Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-events.md","title":"svelte/events","filename":"21-svelte-events.md","content":"```js\n// @noErrors\nimport { on } from 'svelte/events';\n```\n\n## on\n\nAttaches an event handler to the window and returns a function that removes the handler. Using this\nrather than `addEventListener` will preserve the correct order relative to handlers added declaratively\n(with attributes like `onclick`), which use event delegation for performance reasons\n\n<div class=\"ts-block\">\n\n```dts\nfunction on<Type extends keyof WindowEventMap>(\n\twindow: Window,\n\ttype: Type,\n\thandler: (\n\t\tthis: Window,\n\t\tevent: WindowEventMap[Type] & { currentTarget: Window }\n\t) => any,\n\toptions?: AddEventListenerOptions | undefined\n): () => void;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction on<Type extends keyof DocumentEventMap>(\n\tdocument: Document,\n\ttype: Type,\n\thandler: (\n\t\tthis: Document,\n\t\tevent: DocumentEventMap[Type] & {\n\t\t\tcurrentTarget: Document;\n\t\t}\n\t) => any,\n\toptions?: AddEventListenerOptions | undefined\n): () => void;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction on<\n\tElement extends HTMLElement,\n\tType extends keyof HTMLElementEventMap\n>(\n\telement: Element,\n\ttype: Type,\n\thandler: (\n\t\tthis: Element,\n\t\tevent: HTMLElementEventMap[Type] & {\n\t\t\tcurrentTarget: Element;\n\t\t}\n\t) => any,\n\toptions?: AddEventListenerOptions | undefined\n): () => void;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction on<\n\tElement extends MediaQueryList,\n\tType extends keyof MediaQueryListEventMap\n>(\n\telement: Element,\n\ttype: Type,\n\thandler: (\n\t\tthis: Element,\n\t\tevent: MediaQueryListEventMap[Type] & {\n\t\t\tcurrentTarget: Element;\n\t\t}\n\t) => any,\n\toptions?: AddEventListenerOptions | undefined\n): () => void;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction on(\n\telement: EventTarget,\n\ttype: string,\n\thandler: EventListener,\n\toptions?: AddEventListenerOptions | undefined\n): () => void;\n```\n\n</div>","size_bytes":1827,"metadata":{"title":"svelte/events"},"created_at":"2025-07-18T15:47:39.031Z","updated_at":"2025-12-23T14:00:04.133Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-legacy.md","title":"svelte/legacy","filename":"21-svelte-legacy.md","content":"This module provides various functions for use during the migration, since some features can't be replaced one to one with new features. All imports are marked as deprecated and should be migrated away from over time.\n\n\n\n```js\n// @noErrors\nimport {\n\tasClassComponent,\n\tcreateBubbler,\n\tcreateClassComponent,\n\thandlers,\n\tnonpassive,\n\tonce,\n\tpassive,\n\tpreventDefault,\n\trun,\n\tself,\n\tstopImmediatePropagation,\n\tstopPropagation,\n\ttrusted\n} from 'svelte/legacy';\n```\n\n## asClassComponent\n\n<blockquote class=\"tag deprecated note\">\n\nUse this only as a temporary solution to migrate your imperative component code to Svelte 5.\n\n</blockquote>\n\nTakes the component function and returns a Svelte 4 compatible component constructor.\n\n<div class=\"ts-block\">\n\n```dts\nfunction asClassComponent<\n\tProps extends Record<string, any>,\n\tExports extends Record<string, any>,\n\tEvents extends Record<string, any>,\n\tSlots extends Record<string, any>\n>(\n\tcomponent:\n\t\t| SvelteComponent<Props, Events, Slots>\n\t\t| Component<Props>\n): ComponentType<\n\tSvelteComponent<Props, Events, Slots> & Exports\n>;\n```\n\n</div>\n\n\n\n## createBubbler\n\n<blockquote class=\"tag deprecated note\">\n\nUse this only as a temporary solution to migrate your automatically delegated events in Svelte 5.\n\n</blockquote>\n\nFunction to create a `bubble` function that mimic the behavior of `on:click` without handler available in svelte 4.\n\n<div class=\"ts-block\">\n\n```dts\nfunction createBubbler(): (\n\ttype: string\n) => (event: Event) => boolean;\n```\n\n</div>\n\n\n\n## createClassComponent\n\n<blockquote class=\"tag deprecated note\">\n\nUse this only as a temporary solution to migrate your imperative component code to Svelte 5.\n\n</blockquote>\n\nTakes the same options as a Svelte 4 component and the component function and returns a Svelte 4 compatible component.\n\n<div class=\"ts-block\">\n\n```dts\nfunction createClassComponent<\n\tProps extends Record<string, any>,\n\tExports extends Record<string, any>,\n\tEvents extends Record<string, any>,\n\tSlots extends Record<string, any>\n>(\n\toptions: ComponentConstructorOptions<Props> & {\n\t\tcomponent:\n\t\t\t| ComponentType<SvelteComponent<Props, Events, Slots>>\n\t\t\t| Component<Props>;\n\t}\n): SvelteComponent<Props, Events, Slots> & Exports;\n```\n\n</div>\n\n\n\n## handlers\n\nFunction to mimic the multiple listeners available in svelte 4\n\n<div class=\"ts-block\">\n\n```dts\nfunction handlers(\n\t...handlers: EventListener[]\n): EventListener;\n```\n\n</div>\n\n\n\n## nonpassive\n\nSubstitute for the `nonpassive` event modifier, implemented as an action\n\n<div class=\"ts-block\">\n\n```dts\nfunction nonpassive(\n\tnode: HTMLElement,\n\t[event, handler]: [\n\t\tevent: string,\n\t\thandler: () => EventListener\n\t]\n): void;\n```\n\n</div>\n\n\n\n## once\n\nSubstitute for the `once` event modifier\n\n<div class=\"ts-block\">\n\n```dts\nfunction once(\n\tfn: (event: Event, ...args: Array<unknown>) => void\n): (event: Event, ...args: unknown[]) => void;\n```\n\n</div>\n\n\n\n## passive\n\nSubstitute for the `passive` event modifier, implemented as an action\n\n<div class=\"ts-block\">\n\n```dts\nfunction passive(\n\tnode: HTMLElement,\n\t[event, handler]: [\n\t\tevent: string,\n\t\thandler: () => EventListener\n\t]\n): void;\n```\n\n</div>\n\n\n\n## preventDefault\n\nSubstitute for the `preventDefault` event modifier\n\n<div class=\"ts-block\">\n\n```dts\nfunction preventDefault(\n\tfn: (event: Event, ...args: Array<unknown>) => void\n): (event: Event, ...args: unknown[]) => void;\n```\n\n</div>\n\n\n\n## run\n\n<blockquote class=\"tag deprecated note\">\n\nUse this only as a temporary solution to migrate your component code to Svelte 5.\n\n</blockquote>\n\nRuns the given function once immediately on the server, and works like `$effect.pre` on the client.\n\n<div class=\"ts-block\">\n\n```dts\nfunction run(fn: () => void | (() => void)): void;\n```\n\n</div>\n\n\n\n## self\n\nSubstitute for the `self` event modifier\n\n<div class=\"ts-block\">\n\n```dts\nfunction self(\n\tfn: (event: Event, ...args: Array<unknown>) => void\n): (event: Event, ...args: unknown[]) => void;\n```\n\n</div>\n\n\n\n## stopImmediatePropagation\n\nSubstitute for the `stopImmediatePropagation` event modifier\n\n<div class=\"ts-block\">\n\n```dts\nfunction stopImmediatePropagation(\n\tfn: (event: Event, ...args: Array<unknown>) => void\n): (event: Event, ...args: unknown[]) => void;\n```\n\n</div>\n\n\n\n## stopPropagation\n\nSubstitute for the `stopPropagation` event modifier\n\n<div class=\"ts-block\">\n\n```dts\nfunction stopPropagation(\n\tfn: (event: Event, ...args: Array<unknown>) => void\n): (event: Event, ...args: unknown[]) => void;\n```\n\n</div>\n\n\n\n## trusted\n\nSubstitute for the `trusted` event modifier\n\n<div class=\"ts-block\">\n\n```dts\nfunction trusted(\n\tfn: (event: Event, ...args: Array<unknown>) => void\n): (event: Event, ...args: unknown[]) => void;\n```\n\n</div>\n\n\n\n## LegacyComponentType\n\nSupport using the component as both a class and function during the transition period\n\n<div class=\"ts-block\">\n\n```dts\ntype LegacyComponentType = {\n\tnew (o: ComponentConstructorOptions): SvelteComponent;\n\t(\n\t\t...args: Parameters<Component<Record<string, any>>>\n\t): ReturnType<\n\t\tComponent<Record<string, any>, Record<string, any>>\n\t>;\n};\n```\n\n</div>","size_bytes":5066,"metadata":{"title":"svelte/legacy"},"created_at":"2025-07-18T15:47:39.034Z","updated_at":"2025-07-18T15:47:40.339Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-motion.md","title":"svelte/motion","filename":"21-svelte-motion.md","content":"```js\n// @noErrors\nimport {\n\tSpring,\n\tTween,\n\tprefersReducedMotion,\n\tspring,\n\ttweened\n} from 'svelte/motion';\n```\n\n## Spring\n\n<blockquote class=\"since note\">\n\nAvailable since 5.8.0\n\n</blockquote>\n\nA wrapper for a value that behaves in a spring-like fashion. Changes to `spring.target` will cause `spring.current` to\nmove towards it over time, taking account of the `spring.stiffness` and `spring.damping` parameters.\n\n```svelte\n<script>\n\timport { Spring } from 'svelte/motion';\n\n\tconst spring = new Spring(0);\n</script>\n\n<input type=\"range\" bind:value={spring.target} />\n<input type=\"range\" bind:value={spring.current} disabled />\n```\n\n<div class=\"ts-block\">\n\n```dts\nclass Spring<T> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nconstructor(value: T, options?: SpringOpts);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nstatic of<U>(fn: () => U, options?: SpringOpts): Spring<U>;\n```\n\n<div class=\"ts-block-property-details\">\n\nCreate a spring whose value is bound to the return value of `fn`. This must be called\ninside an effect root (for example, during component initialisation).\n\n```svelte\n<script>\n\timport { Spring } from 'svelte/motion';\n\n\tlet { number } = $props();\n\n\tconst spring = Spring.of(() => number);\n</script>\n```\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nset(value: T, options?: SpringUpdateOpts): Promise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\nSets `spring.target` to `value` and returns a `Promise` that resolves if and when `spring.current` catches up to it.\n\nIf `options.instant` is `true`, `spring.current` immediately matches `spring.target`.\n\nIf `options.preserveMomentum` is provided, the spring will continue on its current trajectory for\nthe specified number of milliseconds. This is useful for things like 'fling' gestures.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndamping: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nprecision: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nstiffness: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ntarget: T;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe end value of the spring.\nThis property only exists on the `Spring` class, not the legacy `spring` store.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nget current(): T;\n```\n\n<div class=\"ts-block-property-details\">\n\nThe current value of the spring.\nThis property only exists on the `Spring` class, not the legacy `spring` store.\n\n</div>\n</div></div>\n\n\n\n## Tween\n\n<blockquote class=\"since note\">\n\nAvailable since 5.8.0\n\n</blockquote>\n\nA wrapper for a value that tweens smoothly to its target value. Changes to `tween.target` will cause `tween.current` to\nmove towards it over time, taking account of the `delay`, `duration` and `easing` options.\n\n```svelte\n<script>\n\timport { Tween } from 'svelte/motion';\n\n\tconst tween = new Tween(0);\n</script>\n\n<input type=\"range\" bind:value={tween.target} />\n<input type=\"range\" bind:value={tween.current} disabled />\n```\n\n<div class=\"ts-block\">\n\n```dts\nclass Tween<T> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nstatic of<U>(fn: () => U, options?: TweenedOptions<U> | undefined): Tween<U>;\n```\n\n<div class=\"ts-block-property-details\">\n\nCreate a tween whose value is bound to the return value of `fn`. This must be called\ninside an effect root (for example, during component initialisation).\n\n```svelte\n<script>\n\timport { Tween } from 'svelte/motion';\n\n\tlet { number } = $props();\n\n\tconst tween = Tween.of(() => number);\n</script>\n```\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nconstructor(value: T, options?: TweenedOptions<T>);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nset(value: T, options?: TweenedOptions<T> | undefined): Promise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\nSets `tween.target` to `value` and returns a `Promise` that resolves if and when `tween.current` catches up to it.\n\nIf `options` are provided, they will override the tween's defaults.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nget current(): T;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nset target(v: T);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nget target(): T;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n\n\n## prefersReducedMotion\n\n<blockquote class=\"since note\">\n\nAvailable since 5.7.0\n\n</blockquote>\n\nA [media query](/docs/svelte/svelte-reactivity#MediaQuery) that matches if the user [prefers reduced motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion).\n\n```svelte\n<script>\n\timport { prefersReducedMotion } from 'svelte/motion';\n\timport { fly } from 'svelte/transition';\n\n\tlet visible = $state(false);\n</script>\n\n<button onclick={() => visible = !visible}>\n\ttoggle\n</button>\n\n{#if visible}\n\t<p transition:fly={{ y: prefersReducedMotion.current ? 0 : 200 }}>\n\t\tflies in, unless the user prefers reduced motion\n\t</p>\n{/if}\n```\n\n<div class=\"ts-block\">\n\n```dts\nconst prefersReducedMotion: MediaQuery;\n```\n\n</div>\n\n\n\n## spring\n\n<blockquote class=\"tag deprecated note\">\n\nUse [`Spring`](/docs/svelte/svelte-motion#Spring) instead\n\n</blockquote>\n\nThe spring function in Svelte creates a store whose value is animated, with a motion that simulates the behavior of a spring. This means when the value changes, instead of transitioning at a steady rate, it \"bounces\" like a spring would, depending on the physics parameters provided. This adds a level of realism to the transitions and can enhance the user experience.\n\n<div class=\"ts-block\">\n\n```dts\nfunction spring<T = any>(\n\tvalue?: T | undefined,\n\topts?: SpringOpts | undefined\n): Spring<T>;\n```\n\n</div>\n\n\n\n## tweened\n\n<blockquote class=\"tag deprecated note\">\n\nUse [`Tween`](/docs/svelte/svelte-motion#Tween) instead\n\n</blockquote>\n\nA tweened store in Svelte is a special type of store that provides smooth transitions between state values over time.\n\n<div class=\"ts-block\">\n\n```dts\nfunction tweened<T>(\n\tvalue?: T | undefined,\n\tdefaults?: TweenedOptions<T> | undefined\n): Tweened<T>;\n```\n\n</div>\n\n\n\n## Spring\n\n<div class=\"ts-block\">\n\n```dts\ninterface Spring<T> extends Readable<T> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nset(new_value: T, opts?: SpringUpdateOpts): Promise<void>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nupdate: (fn: Updater<T>, opts?: SpringUpdateOpts) => Promise<void>;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> Only exists on the legacy `spring` store, not the `Spring` class\n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nsubscribe(fn: (value: T) => void): Unsubscriber;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- <span class=\"tag deprecated\">deprecated</span> Only exists on the legacy `spring` store, not the `Spring` class\n\n</div>\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nprecision: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ndamping: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nstiffness: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## Tweened\n\n<div class=\"ts-block\">\n\n```dts\ninterface Tweened<T> extends Readable<T> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nset(value: T, opts?: TweenedOptions<T>): Promise<void>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nupdate(updater: Updater<T>, opts?: TweenedOptions<T>): Promise<void>;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>","size_bytes":8077,"metadata":{"title":"svelte/motion"},"created_at":"2025-07-18T15:47:39.037Z","updated_at":"2025-07-18T15:47:40.340Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-reactivity-window.md","title":"svelte/reactivity/window","filename":"21-svelte-reactivity-window.md","content":"This module exports reactive versions of various `window` values, each of which has a reactive `current` property that you can reference in reactive contexts (templates, [deriveds]($derived) and [effects]($effect)) without using [`<svelte:window>`](svelte-window) bindings or manually creating your own event listeners.\n\n```svelte\n<script>\n\timport { innerWidth, innerHeight } from 'svelte/reactivity/window';\n</script>\n\n<p>{innerWidth.current}x{innerHeight.current}</p>\n```\n\n\n\n```js\n// @noErrors\nimport {\n\tdevicePixelRatio,\n\tinnerHeight,\n\tinnerWidth,\n\tonline,\n\touterHeight,\n\touterWidth,\n\tscreenLeft,\n\tscreenTop,\n\tscrollX,\n\tscrollY\n} from 'svelte/reactivity/window';\n```\n\n## devicePixelRatio\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`devicePixelRatio.current` is a reactive view of `window.devicePixelRatio`. On the server it is `undefined`.\nNote that behaviour differs between browsers — on Chrome it will respond to the current zoom level,\non Firefox and Safari it won't.\n\n<div class=\"ts-block\">\n\n```dts\nconst devicePixelRatio: {\n\tget current(): number | undefined;\n};\n```\n\n</div>\n\n\n\n## innerHeight\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`innerHeight.current` is a reactive view of `window.innerHeight`. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst innerHeight: ReactiveValue<number | undefined>;\n```\n\n</div>\n\n\n\n## innerWidth\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`innerWidth.current` is a reactive view of `window.innerWidth`. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst innerWidth: ReactiveValue<number | undefined>;\n```\n\n</div>\n\n\n\n## online\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`online.current` is a reactive view of `navigator.onLine`. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst online: ReactiveValue<boolean | undefined>;\n```\n\n</div>\n\n\n\n## outerHeight\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`outerHeight.current` is a reactive view of `window.outerHeight`. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst outerHeight: ReactiveValue<number | undefined>;\n```\n\n</div>\n\n\n\n## outerWidth\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`outerWidth.current` is a reactive view of `window.outerWidth`. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst outerWidth: ReactiveValue<number | undefined>;\n```\n\n</div>\n\n\n\n## screenLeft\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`screenLeft.current` is a reactive view of `window.screenLeft`. It is updated inside a `requestAnimationFrame` callback. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst screenLeft: ReactiveValue<number | undefined>;\n```\n\n</div>\n\n\n\n## screenTop\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`screenTop.current` is a reactive view of `window.screenTop`. It is updated inside a `requestAnimationFrame` callback. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst screenTop: ReactiveValue<number | undefined>;\n```\n\n</div>\n\n\n\n## scrollX\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`scrollX.current` is a reactive view of `window.scrollX`. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst scrollX: ReactiveValue<number | undefined>;\n```\n\n</div>\n\n\n\n## scrollY\n\n<blockquote class=\"since note\">\n\nAvailable since 5.11.0\n\n</blockquote>\n\n`scrollY.current` is a reactive view of `window.scrollY`. On the server it is `undefined`.\n\n<div class=\"ts-block\">\n\n```dts\nconst scrollY: ReactiveValue<number | undefined>;\n```\n\n</div>","size_bytes":3795,"metadata":{"title":"svelte/reactivity/window"},"created_at":"2025-07-18T15:47:39.039Z","updated_at":"2025-07-18T15:47:40.344Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-reactivity.md","title":"svelte/reactivity","filename":"21-svelte-reactivity.md","content":"Svelte provides reactive versions of various built-ins like [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) that can be used just like their native counterparts, as well as a handful of additional utilities for handling reactivity.\n\n\n\n```js\n// @noErrors\nimport {\n\tMediaQuery,\n\tSvelteDate,\n\tSvelteMap,\n\tSvelteSet,\n\tSvelteURL,\n\tSvelteURLSearchParams,\n\tcreateSubscriber\n} from 'svelte/reactivity';\n```\n\n## MediaQuery\n\n<blockquote class=\"since note\">\n\nAvailable since 5.7.0\n\n</blockquote>\n\nCreates a media query and provides a `current` property that reflects whether or not it matches.\n\nUse it carefully — during server-side rendering, there is no way to know what the correct value should be, potentially causing content to change upon hydration.\nIf you can use the media query in CSS to achieve the same effect, do that.\n\n```svelte\n<script>\n\timport { MediaQuery } from 'svelte/reactivity';\n\n\tconst large = new MediaQuery('min-width: 800px');\n</script>\n\n<h1>{large.current ? 'large screen' : 'small screen'}</h1>\n```\n\n<div class=\"ts-block\">\n\n```dts\nclass MediaQuery extends ReactiveValue<boolean> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nconstructor(query: string, fallback?: boolean | undefined);\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `query` A media query string\n- `fallback` Fallback value for the server\n\n</div>\n\n</div>\n</div></div>\n\n\n\n## SvelteDate\n\nA reactive version of the built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object.\nReading the date (whether with methods like `date.getTime()` or `date.toString()`, or via things like [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat))\nin an [effect](/docs/svelte/$effect) or [derived](/docs/svelte/$derived)\nwill cause it to be re-evaluated when the value of the date changes.\n\n```svelte\n<script>\n\timport { SvelteDate } from 'svelte/reactivity';\n\n\tconst date = new SvelteDate();\n\n\tconst formatter = new Intl.DateTimeFormat(undefined, {\n\t  hour: 'numeric',\n\t  minute: 'numeric',\n\t  second: 'numeric'\n\t});\n\n\t$effect(() => {\n\t\tconst interval = setInterval(() => {\n\t\t\tdate.setTime(Date.now());\n\t\t}, 1000);\n\n\t\treturn () => {\n\t\t\tclearInterval(interval);\n\t\t};\n\t});\n</script>\n\n<p>The time is {formatter.format(date)}</p>\n```\n\n<div class=\"ts-block\">\n\n```dts\nclass SvelteDate extends Date {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nconstructor(...params: any[]);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n\n\n## SvelteMap\n\nA reactive version of the built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object.\nReading contents of the map (by iterating, or by reading `map.size` or calling `map.get(...)` or `map.has(...)` as in the [tic-tac-toe example](/playground/0b0ff4aa49c9443f9b47fe5203c78293) below) in an [effect](/docs/svelte/$effect) or [derived](/docs/svelte/$derived)\nwill cause it to be re-evaluated as necessary when the map is updated.\n\nNote that values in a reactive map are _not_ made [deeply reactive](/docs/svelte/$state#Deep-state).\n\n```svelte\n<script>\n\timport { SvelteMap } from 'svelte/reactivity';\n\timport { result } from './game.js';\n\n\tlet board = new SvelteMap();\n\tlet player = $state('x');\n\tlet winner = $derived(result(board));\n\n\tfunction reset() {\n\t\tplayer = 'x';\n\t\tboard.clear();\n\t}\n</script>\n\n<div class=\"board\">\n\t{#each Array(9), i}\n\t\t<button\n\t\t\tdisabled={board.has(i) || winner}\n\t\t\tonclick={() => {\n\t\t\t\tboard.set(i, player);\n\t\t\t\tplayer = player === 'x' ? 'o' : 'x';\n\t\t\t}}\n\t\t>{board.get(i)}</button>\n\t{/each}\n</div>\n\n{#if winner}\n\t<p>{winner} wins!</p>\n\t<button onclick={reset}>reset</button>\n{:else}\n\t<p>{player} is next</p>\n{/if}\n```\n\n<div class=\"ts-block\">\n\n```dts\nclass SvelteMap<K, V> extends Map<K, V> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nconstructor(value?: Iterable<readonly [K, V]> | null | undefined);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nset(key: K, value: V): this;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n\n\n## SvelteSet\n\nA reactive version of the built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) object.\nReading contents of the set (by iterating, or by reading `set.size` or calling `set.has(...)` as in the [example](/playground/53438b51194b4882bcc18cddf9f96f15) below) in an [effect](/docs/svelte/$effect) or [derived](/docs/svelte/$derived)\nwill cause it to be re-evaluated as necessary when the set is updated.\n\nNote that values in a reactive set are _not_ made [deeply reactive](/docs/svelte/$state#Deep-state).\n\n```svelte\n<script>\n\timport { SvelteSet } from 'svelte/reactivity';\n\tlet monkeys = new SvelteSet();\n\n\tfunction toggle(monkey) {\n\t\tif (monkeys.has(monkey)) {\n\t\t\tmonkeys.delete(monkey);\n\t\t} else {\n\t\t\tmonkeys.add(monkey);\n\t\t}\n\t}\n</script>\n\n{#each ['🙈', '🙉', '🙊'] as monkey}\n\t<button onclick={() => toggle(monkey)}>{monkey}</button>\n{/each}\n\n<button onclick={() => monkeys.clear()}>clear</button>\n\n{#if monkeys.has('🙈')}<p>see no evil</p>{/if}\n{#if monkeys.has('🙉')}<p>hear no evil</p>{/if}\n{#if monkeys.has('🙊')}<p>speak no evil</p>{/if}\n```\n\n<div class=\"ts-block\">\n\n```dts\nclass SvelteSet<T> extends Set<T> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nconstructor(value?: Iterable<T> | null | undefined);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nadd(value: T): this;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n\n\n## SvelteURL\n\nA reactive version of the built-in [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) object.\nReading properties of the URL (such as `url.href` or `url.pathname`) in an [effect](/docs/svelte/$effect) or [derived](/docs/svelte/$derived)\nwill cause it to be re-evaluated as necessary when the URL changes.\n\nThe `searchParams` property is an instance of [SvelteURLSearchParams](/docs/svelte/svelte-reactivity#SvelteURLSearchParams).\n\n[Example](/playground/5a694758901b448c83dc40dc31c71f2a):\n\n```svelte\n<script>\n\timport { SvelteURL } from 'svelte/reactivity';\n\n\tconst url = new SvelteURL('https://example.com/path');\n</script>\n\n<!-- changes to these... -->\n<input bind:value={url.protocol} />\n<input bind:value={url.hostname} />\n<input bind:value={url.pathname} />\n\n<hr />\n\n<!-- will update `href` and vice versa -->\n<input bind:value={url.href} size=\"65\" />\n```\n\n<div class=\"ts-block\">\n\n```dts\nclass SvelteURL extends URL {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nget searchParams(): SvelteURLSearchParams;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n\n\n## SvelteURLSearchParams\n\nA reactive version of the built-in [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object.\nReading its contents (by iterating, or by calling `params.get(...)` or `params.getAll(...)` as in the [example](/playground/b3926c86c5384bab9f2cf993bc08c1c8) below) in an [effect](/docs/svelte/$effect) or [derived](/docs/svelte/$derived)\nwill cause it to be re-evaluated as necessary when the params are updated.\n\n```svelte\n<script>\n\timport { SvelteURLSearchParams } from 'svelte/reactivity';\n\n\tconst params = new SvelteURLSearchParams('message=hello');\n\n\tlet key = $state('key');\n\tlet value = $state('value');\n</script>\n\n<input bind:value={key} />\n<input bind:value={value} />\n<button onclick={() => params.append(key, value)}>append</button>\n\n<p>?{params.toString()}</p>\n\n{#each params as [key, value]}\n\t<p>{key}: {value}</p>\n{/each}\n```\n\n<div class=\"ts-block\">\n\n```dts\nclass SvelteURLSearchParams extends URLSearchParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\n[REPLACE](params: URLSearchParams): void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n\n\n## createSubscriber\n\n<blockquote class=\"since note\">\n\nAvailable since 5.7.0\n\n</blockquote>\n\nReturns a `subscribe` function that integrates external event-based systems with Svelte's reactivity.\nIt's particularly useful for integrating with web APIs like `MediaQuery`, `IntersectionObserver`, or `WebSocket`.\n\nIf `subscribe` is called inside an effect (including indirectly, for example inside a getter),\nthe `start` callback will be called with an `update` function. Whenever `update` is called, the effect re-runs.\n\nIf `start` returns a cleanup function, it will be called when the effect is destroyed.\n\nIf `subscribe` is called in multiple effects, `start` will only be called once as long as the effects\nare active, and the returned teardown function will only be called when all effects are destroyed.\n\nIt's best understood with an example. Here's an implementation of [`MediaQuery`](/docs/svelte/svelte-reactivity#MediaQuery):\n\n```js\n// @errors: 7031\nimport { createSubscriber } from 'svelte/reactivity';\nimport { on } from 'svelte/events';\n\nexport class MediaQuery {\n\t#query;\n\t#subscribe;\n\n\tconstructor(query) {\n\t\tthis.#query = window.matchMedia(`(${query})`);\n\n\t\tthis.#subscribe = createSubscriber((update) => {\n\t\t\t// when the `change` event occurs, re-run any effects that read `this.current`\n\t\t\tconst off = on(this.#query, 'change', update);\n\n\t\t\t// stop listening when all the effects are destroyed\n\t\t\treturn () => off();\n\t\t});\n\t}\n\n\tget current() {\n\t\t// This makes the getter reactive, if read in an effect\n\t\tthis.#subscribe();\n\n\t\t// Return the current state of the query, whether or not we're in an effect\n\t\treturn this.#query.matches;\n\t}\n}\n```\n\n<div class=\"ts-block\">\n\n```dts\nfunction createSubscriber(\n\tstart: (update: () => void) => (() => void) | void\n): () => void;\n```\n\n</div>","size_bytes":9950,"metadata":{"title":"svelte/reactivity"},"created_at":"2025-07-18T15:47:39.040Z","updated_at":"2025-07-18T15:47:40.347Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-server.md","title":"svelte/server","filename":"21-svelte-server.md","content":"```js\n// @noErrors\nimport { render } from 'svelte/server';\n```\n\n## render\n\nOnly available on the server and when compiling with the `server` option.\nTakes a component and returns an object with `body` and `head` properties on it, which you can use to populate the HTML when server-rendering your app.\n\n<div class=\"ts-block\">\n\n```dts\nfunction render<\n\tComp extends SvelteComponent<any> | Component<any>,\n\tProps extends ComponentProps<Comp> = ComponentProps<Comp>\n>(\n\t...args: {} extends Props\n\t\t? [\n\t\t\t\tcomponent: Comp extends SvelteComponent<any>\n\t\t\t\t\t? ComponentType<Comp>\n\t\t\t\t\t: Comp,\n\t\t\t\toptions?: {\n\t\t\t\t\tprops?: Omit<Props, '$$slots' | '$$events'>;\n\t\t\t\t\tcontext?: Map<any, any>;\n\t\t\t\t\tidPrefix?: string;\n\t\t\t\t\tcsp?: Csp;\n\t\t\t\t\ttransformError?: (\n\t\t\t\t\t\terror: unknown\n\t\t\t\t\t) => unknown | Promise<unknown>;\n\t\t\t\t}\n\t\t\t]\n\t\t: [\n\t\t\t\tcomponent: Comp extends SvelteComponent<any>\n\t\t\t\t\t? ComponentType<Comp>\n\t\t\t\t\t: Comp,\n\t\t\t\toptions: {\n\t\t\t\t\tprops: Omit<Props, '$$slots' | '$$events'>;\n\t\t\t\t\tcontext?: Map<any, any>;\n\t\t\t\t\tidPrefix?: string;\n\t\t\t\t\tcsp?: Csp;\n\t\t\t\t\ttransformError?: (\n\t\t\t\t\t\terror: unknown\n\t\t\t\t\t) => unknown | Promise<unknown>;\n\t\t\t\t}\n\t\t\t]\n): RenderOutput;\n```\n\n</div>","size_bytes":1201,"metadata":{"title":"svelte/server"},"created_at":"2025-07-18T15:47:39.042Z","updated_at":"2026-02-20T02:00:04.584Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-store.md","title":"svelte/store","filename":"21-svelte-store.md","content":"```js\n// @noErrors\nimport {\n\tderived,\n\tfromStore,\n\tget,\n\treadable,\n\treadonly,\n\ttoStore,\n\twritable\n} from 'svelte/store';\n```\n\n## derived\n\nDerived value store by synchronizing one or more readable stores and\napplying an aggregation function over its input values.\n\n<div class=\"ts-block\">\n\n```dts\nfunction derived<S extends Stores, T>(\n\tstores: S,\n\tfn: (\n\t\tvalues: StoresValues<S>,\n\t\tset: (value: T) => void,\n\t\tupdate: (fn: Updater<T>) => void\n\t) => Unsubscriber | void,\n\tinitial_value?: T | undefined\n): Readable<T>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction derived<S extends Stores, T>(\n\tstores: S,\n\tfn: (values: StoresValues<S>) => T,\n\tinitial_value?: T | undefined\n): Readable<T>;\n```\n\n</div>\n\n\n\n## fromStore\n\n<div class=\"ts-block\">\n\n```dts\nfunction fromStore<V>(store: Writable<V>): {\n\tcurrent: V;\n};\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction fromStore<V>(store: Readable<V>): {\n\treadonly current: V;\n};\n```\n\n</div>\n\n\n\n## get\n\nGet the current value from a store by subscribing and immediately unsubscribing.\n\n<div class=\"ts-block\">\n\n```dts\nfunction get<T>(store: Readable<T>): T;\n```\n\n</div>\n\n\n\n## readable\n\nCreates a `Readable` store that allows reading by subscription.\n\n<div class=\"ts-block\">\n\n```dts\nfunction readable<T>(\n\tvalue?: T | undefined,\n\tstart?: StartStopNotifier<T> | undefined\n): Readable<T>;\n```\n\n</div>\n\n\n\n## readonly\n\nTakes a store and returns a new one derived from the old one that is readable.\n\n<div class=\"ts-block\">\n\n```dts\nfunction readonly<T>(store: Readable<T>): Readable<T>;\n```\n\n</div>\n\n\n\n## toStore\n\n<div class=\"ts-block\">\n\n```dts\nfunction toStore<V>(\n\tget: () => V,\n\tset: (v: V) => void\n): Writable<V>;\n```\n\n</div>\n\n<div class=\"ts-block\">\n\n```dts\nfunction toStore<V>(get: () => V): Readable<V>;\n```\n\n</div>\n\n\n\n## writable\n\nCreate a `Writable` store that allows both updating and reading by subscription.\n\n<div class=\"ts-block\">\n\n```dts\nfunction writable<T>(\n\tvalue?: T | undefined,\n\tstart?: StartStopNotifier<T> | undefined\n): Writable<T>;\n```\n\n</div>\n\n\n\n## Readable\n\nReadable interface for subscribing.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Readable<T> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nsubscribe(this: void, run: Subscriber<T>, invalidate?: () => void): Unsubscriber;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `run` subscription callback\n- `invalidate` cleanup callback\n\n</div>\n\nSubscribe on value changes.\n\n</div>\n</div></div>\n\n## StartStopNotifier\n\nStart and stop notification callbacks.\nThis function is called when the first subscriber subscribes.\n\n<div class=\"ts-block\">\n\n```dts\ntype StartStopNotifier<T> = (\n\tset: (value: T) => void,\n\tupdate: (fn: Updater<T>) => void\n) => void | (() => void);\n```\n\n</div>\n\n## Subscriber\n\nCallback to inform of a value updates.\n\n<div class=\"ts-block\">\n\n```dts\ntype Subscriber<T> = (value: T) => void;\n```\n\n</div>\n\n## Unsubscriber\n\nUnsubscribes from value updates.\n\n<div class=\"ts-block\">\n\n```dts\ntype Unsubscriber = () => void;\n```\n\n</div>\n\n## Updater\n\nCallback to update a value.\n\n<div class=\"ts-block\">\n\n```dts\ntype Updater<T> = (value: T) => T;\n```\n\n</div>\n\n## Writable\n\nWritable interface for both updating and subscribing.\n\n<div class=\"ts-block\">\n\n```dts\ninterface Writable<T> extends Readable<T> {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\nset(this: void, value: T): void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `value` to set\n\n</div>\n\nSet value and inform subscribers.\n\n</div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nupdate(this: void, updater: Updater<T>): void;\n```\n\n<div class=\"ts-block-property-details\">\n\n<div class=\"ts-block-property-bullets\">\n\n- `updater` callback\n\n</div>\n\nUpdate value using callback and inform subscribers.\n\n</div>\n</div></div>","size_bytes":3830,"metadata":{"title":"svelte/store"},"created_at":"2025-07-18T15:47:39.043Z","updated_at":"2025-07-18T15:47:40.355Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-transition.md","title":"svelte/transition","filename":"21-svelte-transition.md","content":"```js\n// @noErrors\nimport {\n\tblur,\n\tcrossfade,\n\tdraw,\n\tfade,\n\tfly,\n\tscale,\n\tslide\n} from 'svelte/transition';\n```\n\n## blur\n\nAnimates a `blur` filter alongside an element's opacity.\n\n<div class=\"ts-block\">\n\n```dts\nfunction blur(\n\tnode: Element,\n\t{\n\t\tdelay,\n\t\tduration,\n\t\teasing,\n\t\tamount,\n\t\topacity\n\t}?: BlurParams | undefined\n): TransitionConfig;\n```\n\n</div>\n\n\n\n## crossfade\n\nThe `crossfade` function creates a pair of [transitions](/docs/svelte/transition) called `send` and `receive`. When an element is 'sent', it looks for a corresponding element being 'received', and generates a transition that transforms the element to its counterpart's position and fades it out. When an element is 'received', the reverse happens. If there is no counterpart, the `fallback` transition is used.\n\n<div class=\"ts-block\">\n\n```dts\nfunction crossfade({\n\tfallback,\n\t...defaults\n}: CrossfadeParams & {\n\tfallback?: (\n\t\tnode: Element,\n\t\tparams: CrossfadeParams,\n\t\tintro: boolean\n\t) => TransitionConfig;\n}): [\n\t(\n\t\tnode: any,\n\t\tparams: CrossfadeParams & {\n\t\t\tkey: any;\n\t\t}\n\t) => () => TransitionConfig,\n\t(\n\t\tnode: any,\n\t\tparams: CrossfadeParams & {\n\t\t\tkey: any;\n\t\t}\n\t) => () => TransitionConfig\n];\n```\n\n</div>\n\n\n\n## draw\n\nAnimates the stroke of an SVG element, like a snake in a tube. `in` transitions begin with the path invisible and draw the path to the screen over time. `out` transitions start in a visible state and gradually erase the path. `draw` only works with elements that have a `getTotalLength` method, like `<path>` and `<polyline>`.\n\n<div class=\"ts-block\">\n\n```dts\nfunction draw(\n\tnode: SVGElement & {\n\t\tgetTotalLength(): number;\n\t},\n\t{\n\t\tdelay,\n\t\tspeed,\n\t\tduration,\n\t\teasing\n\t}?: DrawParams | undefined\n): TransitionConfig;\n```\n\n</div>\n\n\n\n## fade\n\nAnimates the opacity of an element from 0 to the current opacity for `in` transitions and from the current opacity to 0 for `out` transitions.\n\n<div class=\"ts-block\">\n\n```dts\nfunction fade(\n\tnode: Element,\n\t{ delay, duration, easing }?: FadeParams | undefined\n): TransitionConfig;\n```\n\n</div>\n\n\n\n## fly\n\nAnimates the x and y positions and the opacity of an element. `in` transitions animate from the provided values, passed as parameters to the element's default values. `out` transitions animate from the element's default values to the provided values.\n\n<div class=\"ts-block\">\n\n```dts\nfunction fly(\n\tnode: Element,\n\t{\n\t\tdelay,\n\t\tduration,\n\t\teasing,\n\t\tx,\n\t\ty,\n\t\topacity\n\t}?: FlyParams | undefined\n): TransitionConfig;\n```\n\n</div>\n\n\n\n## scale\n\nAnimates the opacity and scale of an element. `in` transitions animate from the provided values, passed as parameters, to an element's current (default) values. `out` transitions animate from an element's default values to the provided values.\n\n<div class=\"ts-block\">\n\n```dts\nfunction scale(\n\tnode: Element,\n\t{\n\t\tdelay,\n\t\tduration,\n\t\teasing,\n\t\tstart,\n\t\topacity\n\t}?: ScaleParams | undefined\n): TransitionConfig;\n```\n\n</div>\n\n\n\n## slide\n\nSlides an element in and out.\n\n<div class=\"ts-block\">\n\n```dts\nfunction slide(\n\tnode: Element,\n\t{\n\t\tdelay,\n\t\tduration,\n\t\teasing,\n\t\taxis\n\t}?: SlideParams | undefined\n): TransitionConfig;\n```\n\n</div>\n\n\n\n## BlurParams\n\n<div class=\"ts-block\">\n\n```dts\ninterface BlurParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: EasingFunction;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\namount?: number | string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nopacity?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## CrossfadeParams\n\n<div class=\"ts-block\">\n\n```dts\ninterface CrossfadeParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number | ((len: number) => number);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: EasingFunction;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## DrawParams\n\n<div class=\"ts-block\">\n\n```dts\ninterface DrawParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nspeed?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number | ((len: number) => number);\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: EasingFunction;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## EasingFunction\n\n<div class=\"ts-block\">\n\n```dts\ntype EasingFunction = (t: number) => number;\n```\n\n</div>\n\n## FadeParams\n\n<div class=\"ts-block\">\n\n```dts\ninterface FadeParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: EasingFunction;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## FlyParams\n\n<div class=\"ts-block\">\n\n```dts\ninterface FlyParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: EasingFunction;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nx?: number | string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ny?: number | string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nopacity?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## ScaleParams\n\n<div class=\"ts-block\">\n\n```dts\ninterface ScaleParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: EasingFunction;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nstart?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nopacity?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## SlideParams\n\n<div class=\"ts-block\">\n\n```dts\ninterface SlideParams {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: EasingFunction;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\naxis?: 'x' | 'y';\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>\n\n## TransitionConfig\n\n<div class=\"ts-block\">\n\n```dts\ninterface TransitionConfig {/*…*/}\n```\n\n<div class=\"ts-block-property\">\n\n```dts\ndelay?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\nduration?: number;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\neasing?: EasingFunction;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ncss?: (t: number, u: number) => string;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div>\n\n<div class=\"ts-block-property\">\n\n```dts\ntick?: (t: number, u: number) => void;\n```\n\n<div class=\"ts-block-property-details\"></div>\n</div></div>","size_bytes":8268,"metadata":{"tags":"transitions","title":"svelte/transition"},"created_at":"2025-07-18T15:47:39.045Z","updated_at":"2026-02-14T01:33:24.887Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/30-compiler-errors.md","title":"Compiler errors","filename":"30-compiler-errors.md","content":"<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n### animation_duplicate\n\n```\nAn element can only have one 'animate' directive\n```\n\n### animation_invalid_placement\n\n```\nAn element that uses the `animate:` directive must be the only child of a keyed `{#each ...}` block\n```\n\n### animation_missing_key\n\n```\nAn element that uses the `animate:` directive must be the only child of a keyed `{#each ...}` block. Did you forget to add a key to your each block?\n```\n\n### attribute_contenteditable_dynamic\n\n```\n'contenteditable' attribute cannot be dynamic if element uses two-way binding\n```\n\n### attribute_contenteditable_missing\n\n```\n'contenteditable' attribute is required for textContent, innerHTML and innerText two-way bindings\n```\n\n### attribute_duplicate\n\n```\nAttributes need to be unique\n```\n\n### attribute_empty_shorthand\n\n```\nAttribute shorthand cannot be empty\n```\n\n### attribute_invalid_event_handler\n\n```\nEvent attribute must be a JavaScript expression, not a string\n```\n\n### attribute_invalid_multiple\n\n```\n'multiple' attribute must be static if select uses two-way binding\n```\n\n### attribute_invalid_name\n\n```\n'%name%' is not a valid attribute name\n```\n\n### attribute_invalid_sequence_expression\n\n```\nComma-separated expressions are not allowed as attribute/directive values in runes mode, unless wrapped in parentheses\n```\n\nAn attribute value cannot be a comma-separated sequence of expressions — in other words this is disallowed:\n\n```svelte\n<div class={size, color}>...</div>\n```\n\nInstead, make sure that the attribute value contains a single expression. In the example above it's likely that this was intended (see the [class documentation](class) for more details):\n\n```svelte\n<div class={[size, color]}>...</div>\n```\n\nIf you _do_ need to use the comma operator for some reason, wrap the sequence in parentheses:\n\n```svelte\n<div class={(size, color)}>...</div>\n```\n\nNote that this will evaluate to `color`, ignoring `size`.\n\n### attribute_invalid_type\n\n```\n'type' attribute must be a static text value if input uses two-way binding\n```\n\n### attribute_unquoted_sequence\n\n```\nAttribute values containing `{...}` must be enclosed in quote marks, unless the value only contains the expression\n```\n\n### bind_group_invalid_expression\n\n```\n`bind:group` can only bind to an Identifier or MemberExpression\n```\n\n### bind_group_invalid_snippet_parameter\n\n```\nCannot `bind:group` to a snippet parameter\n```\n\n### bind_invalid_expression\n\n```\nCan only bind to an Identifier or MemberExpression or a `{get, set}` pair\n```\n\n### bind_invalid_name\n\n```\n`bind:%name%` is not a valid binding\n```\n\n```\n`bind:%name%` is not a valid binding. %explanation%\n```\n\n### bind_invalid_parens\n\n```\n`bind:%name%={get, set}` must not have surrounding parentheses\n```\n\n### bind_invalid_target\n\n```\n`bind:%name%` can only be used with %elements%\n```\n\n### bind_invalid_value\n\n```\nCan only bind to state or props\n```\n\n### bindable_invalid_location\n\n```\n`$bindable()` can only be used inside a `$props()` declaration\n```\n\n### block_duplicate_clause\n\n```\n%name% cannot appear more than once within a block\n```\n\n### block_invalid_continuation_placement\n\n```\n{:...} block is invalid at this position (did you forget to close the preceding element or block?)\n```\n\n### block_invalid_elseif\n\n```\n'elseif' should be 'else if'\n```\n\n### block_invalid_placement\n\n```\n{#%name% ...} block cannot be %location%\n```\n\n### block_unclosed\n\n```\nBlock was left open\n```\n\n### block_unexpected_character\n\n```\nExpected a `%character%` character immediately following the opening bracket\n```\n\n### block_unexpected_close\n\n```\nUnexpected block closing tag\n```\n\n### component_invalid_directive\n\n```\nThis type of directive is not valid on components\n```\n\n### const_tag_cycle\n\n```\nCyclical dependency detected: %cycle%\n```\n\n### const_tag_invalid_expression\n\n```\n{@const ...} must consist of a single variable declaration\n```\n\n### const_tag_invalid_placement\n\n```\n`{@const}` must be the immediate child of `{#snippet}`, `{#if}`, `{:else if}`, `{:else}`, `{#each}`, `{:then}`, `{:catch}`, `<svelte:fragment>`, `<svelte:boundary>` or `<Component>`\n```\n\n### const_tag_invalid_reference\n\n```\nThe `{@const %name% = ...}` declaration is not available in this snippet\n```\n\nThe following is an error:\n\n```svelte\n<svelte:boundary>\n    {@const foo = 'bar'}\n\n    {#snippet failed()}\n        {foo}\n    {/snippet}\n</svelte:boundary>\n```\n\nHere, `foo` is not available inside `failed`. The top level code inside `<svelte:boundary>` becomes part of the implicit `children` snippet, in other words the above code is equivalent to this:\n\n```svelte\n<svelte:boundary>\n    {#snippet children()}\n        {@const foo = 'bar'}\n    {/snippet}\n\n    {#snippet failed()}\n        {foo}\n    {/snippet}\n</svelte:boundary>\n```\n\nThe same applies to components:\n\n```svelte\n<Component>\n    {@const foo = 'bar'}\n\n    {#snippet someProp()}\n        <!-- error -->\n        {foo}\n    {/snippet}\n</Component>\n```\n\n### constant_assignment\n\n```\nCannot assign to %thing%\n```\n\n### constant_binding\n\n```\nCannot bind to %thing%\n```\n\n### css_empty_declaration\n\n```\nDeclaration cannot be empty\n```\n\n### css_expected_identifier\n\n```\nExpected a valid CSS identifier\n```\n\n### css_global_block_invalid_combinator\n\n```\nA `:global` selector cannot follow a `%name%` combinator\n```\n\n### css_global_block_invalid_declaration\n\n```\nA top-level `:global {...}` block can only contain rules, not declarations\n```\n\n### css_global_block_invalid_list\n\n```\nA `:global` selector cannot be part of a selector list with entries that don't contain `:global`\n```\n\nThe following CSS is invalid:\n\n```css\n:global, x {\n    y {\n        color: red;\n    }\n}\n```\n\nThis is mixing a `:global` block, which means \"everything in here is unscoped\", with a scoped selector (`x` in this case). As a result it's not possible to transform the inner selector (`y` in this case) into something that satisfies both requirements. You therefore have to split this up into two selectors:\n\n```css\n:global {\n    y {\n        color: red;\n    }\n}\n\nx y {\n    color: red;\n}\n```\n\n### css_global_block_invalid_modifier\n\n```\nA `:global` selector cannot modify an existing selector\n```\n\n### css_global_block_invalid_modifier_start\n\n```\nA `:global` selector can only be modified if it is a descendant of other selectors\n```\n\n### css_global_block_invalid_placement\n\n```\nA `:global` selector cannot be inside a pseudoclass\n```\n\n### css_global_invalid_placement\n\n```\n`:global(...)` can be at the start or end of a selector sequence, but not in the middle\n```\n\n### css_global_invalid_selector\n\n```\n`:global(...)` must contain exactly one selector\n```\n\n### css_global_invalid_selector_list\n\n```\n`:global(...)` must not contain type or universal selectors when used in a compound selector\n```\n\n### css_nesting_selector_invalid_placement\n\n```\nNesting selectors can only be used inside a rule or as the first selector inside a lone `:global(...)`\n```\n\n### css_selector_invalid\n\n```\nInvalid selector\n```\n\n### css_type_selector_invalid_placement\n\n```\n`:global(...)` must not be followed by a type selector\n```\n\n### debug_tag_invalid_arguments\n\n```\n{@debug ...} arguments must be identifiers, not arbitrary expressions\n```\n\n### declaration_duplicate\n\n```\n`%name%` has already been declared\n```\n\n### declaration_duplicate_module_import\n\n```\nCannot declare a variable with the same name as an import inside `<script module>`\n```\n\n### derived_invalid_export\n\n```\nCannot export derived state from a module. To expose the current derived value, export a function returning its value\n```\n\n### directive_invalid_value\n\n```\nDirective value must be a JavaScript expression enclosed in curly braces\n```\n\n### directive_missing_name\n\n```\n`%type%` name cannot be empty\n```\n\n### dollar_binding_invalid\n\n```\nThe $ name is reserved, and cannot be used for variables and imports\n```\n\n### dollar_prefix_invalid\n\n```\nThe $ prefix is reserved, and cannot be used for variables and imports\n```\n\n### duplicate_class_field\n\n```\n`%name%` has already been declared\n```\n\n### each_item_invalid_assignment\n\n```\nCannot reassign or bind to each block argument in runes mode. Use the array and index variables instead (e.g. `array[i] = value` instead of `entry = value`, or `bind:value={array[i]}` instead of `bind:value={entry}`)\n```\n\nIn legacy mode, it was possible to reassign or bind to the each block argument itself:\n\n```svelte\n<script>\n\tlet array = [1, 2, 3];\n</script>\n\n{#each array as entry}\n\t<!-- reassignment -->\n\t<button on:click={() => entry = 4}>change</button>\n\n\t<!-- binding -->\n\t<input bind:value={entry}>\n{/each}\n```\n\nThis turned out to be buggy and unpredictable, particularly when working with derived values (such as `array.map(...)`), and as such is forbidden in runes mode. You can achieve the same outcome by using the index instead:\n\n```svelte\n<script>\n\tlet array = $state([1, 2, 3]);\n</script>\n\n{#each array as entry, i}\n\t<!-- reassignment -->\n\t<button onclick={() => array[i] = 4}>change</button>\n\n\t<!-- binding -->\n\t<input bind:value={array[i]}>\n{/each}\n```\n\n### each_key_without_as\n\n```\nAn `{#each ...}` block without an `as` clause cannot have a key\n```\n\n### effect_invalid_placement\n\n```\n`$effect()` can only be used as an expression statement\n```\n\n### element_invalid_closing_tag\n\n```\n`</%name%>` attempted to close an element that was not open\n```\n\n### element_invalid_closing_tag_autoclosed\n\n```\n`</%name%>` attempted to close element that was already automatically closed by `<%reason%>` (cannot nest `<%reason%>` inside `<%name%>`)\n```\n\n### element_unclosed\n\n```\n`<%name%>` was left open\n```\n\n### event_handler_invalid_component_modifier\n\n```\nEvent modifiers other than 'once' can only be used on DOM elements\n```\n\n### event_handler_invalid_modifier\n\n```\nValid event modifiers are %list%\n```\n\n### event_handler_invalid_modifier_combination\n\n```\nThe '%modifier1%' and '%modifier2%' modifiers cannot be used together\n```\n\n### expected_attribute_value\n\n```\nExpected attribute value\n```\n\n### expected_block_type\n\n```\nExpected 'if', 'each', 'await', 'key' or 'snippet'\n```\n\n### expected_identifier\n\n```\nExpected an identifier\n```\n\n### expected_pattern\n\n```\nExpected identifier or destructure pattern\n```\n\n### expected_tag\n\n```\nExpected 'html', 'render', 'attach', 'const', or 'debug'\n```\n\n### expected_token\n\n```\nExpected token %token%\n```\n\n### expected_whitespace\n\n```\nExpected whitespace\n```\n\n### experimental_async\n\n```\nCannot use `await` in deriveds and template expressions, or at the top level of a component, unless the `experimental.async` compiler option is `true`\n```\n\n### export_undefined\n\n```\n`%name%` is not defined\n```\n\n### global_reference_invalid\n\n```\n`%name%` is an illegal variable name. To reference a global variable called `%name%`, use `globalThis.%name%`\n```\n\n### host_invalid_placement\n\n```\n`$host()` can only be used inside custom element component instances\n```\n\n### illegal_await_expression\n\n```\n`use:`, `transition:` and `animate:` directives, attachments and bindings do not support await expressions\n```\n\n### illegal_element_attribute\n\n```\n`<%name%>` does not support non-event attributes or spread attributes\n```\n\n### import_svelte_internal_forbidden\n\n```\nImports of `svelte/internal/*` are forbidden. It contains private runtime code which is subject to change without notice. If you're importing from `svelte/internal/*` to work around a limitation of Svelte, please open an issue at https://github.com/sveltejs/svelte and explain your use case\n```\n\n### inspect_trace_generator\n\n```\n`$inspect.trace(...)` cannot be used inside a generator function\n```\n\n### inspect_trace_invalid_placement\n\n```\n`$inspect.trace(...)` must be the first statement of a function body\n```\n\n### invalid_arguments_usage\n\n```\nThe arguments keyword cannot be used within the template or at the top level of a component\n```\n\n### js_parse_error\n\n```\n%message%\n```\n\n### legacy_await_invalid\n\n```\nCannot use `await` in deriveds and template expressions, or at the top level of a component, unless in runes mode\n```\n\n### legacy_export_invalid\n\n```\nCannot use `export let` in runes mode — use `$props()` instead\n```\n\n### legacy_props_invalid\n\n```\nCannot use `$$props` in runes mode\n```\n\n### legacy_reactive_statement_invalid\n\n```\n`$:` is not allowed in runes mode, use `$derived` or `$effect` instead\n```\n\n### legacy_rest_props_invalid\n\n```\nCannot use `$$restProps` in runes mode\n```\n\n### let_directive_invalid_placement\n\n```\n`let:` directive at invalid position\n```\n\n### mixed_event_handler_syntaxes\n\n```\nMixing old (on:%name%) and new syntaxes for event handling is not allowed. Use only the on%name% syntax\n```\n\n### module_illegal_default_export\n\n```\nA component cannot have a default export\n```\n\n### node_invalid_placement\n\n```\n%message%. The browser will 'repair' the HTML (by moving, removing, or inserting elements) which breaks Svelte's assumptions about the structure of your components.\n```\n\nHTML restricts where certain elements can appear. In case of a violation the browser will 'repair' the HTML in a way that breaks Svelte's assumptions about the structure of your components. Some examples:\n\n- `<p>hello <div>world</div></p>` will result in `<p>hello </p><div>world</div><p></p>` (the `<div>` autoclosed the `<p>` because `<p>` cannot contain block-level elements)\n- `<option><div>option a</div></option>` will result in `<option>option a</option>` (the `<div>` is removed)\n- `<table><tr><td>cell</td></tr></table>` will result in `<table><tbody><tr><td>cell</td></tr></tbody></table>` (a `<tbody>` is auto-inserted)\n\n### options_invalid_value\n\n```\nInvalid compiler option: %details%\n```\n\n### options_removed\n\n```\nInvalid compiler option: %details%\n```\n\n### options_unrecognised\n\n```\nUnrecognised compiler option %keypath%\n```\n\n### props_duplicate\n\n```\nCannot use `%rune%()` more than once\n```\n\n### props_id_invalid_placement\n\n```\n`$props.id()` can only be used at the top level of components as a variable declaration initializer\n```\n\n### props_illegal_name\n\n```\nDeclaring or accessing a prop starting with `$$` is illegal (they are reserved for Svelte internals)\n```\n\n### props_invalid_identifier\n\n```\n`$props()` can only be used with an object destructuring pattern\n```\n\n### props_invalid_pattern\n\n```\n`$props()` assignment must not contain nested properties or computed keys\n```\n\n### props_invalid_placement\n\n```\n`$props()` can only be used at the top level of components as a variable declaration initializer\n```\n\n### reactive_declaration_cycle\n\n```\nCyclical dependency detected: %cycle%\n```\n\n### render_tag_invalid_call_expression\n\n```\nCalling a snippet function using apply, bind or call is not allowed\n```\n\n### render_tag_invalid_expression\n\n```\n`{@render ...}` tags can only contain call expressions\n```\n\n### render_tag_invalid_spread_argument\n\n```\ncannot use spread arguments in `{@render ...}` tags\n```\n\n### rune_invalid_arguments\n\n```\n`%rune%` cannot be called with arguments\n```\n\n### rune_invalid_arguments_length\n\n```\n`%rune%` must be called with %args%\n```\n\n### rune_invalid_computed_property\n\n```\nCannot access a computed property of a rune\n```\n\n### rune_invalid_name\n\n```\n`%name%` is not a valid rune\n```\n\n### rune_invalid_spread\n\n```\n`%rune%` cannot be called with a spread argument\n```\n\n### rune_invalid_usage\n\n```\nCannot use `%rune%` rune in non-runes mode\n```\n\n### rune_missing_parentheses\n\n```\nCannot use rune without parentheses\n```\n\n### rune_removed\n\n```\nThe `%name%` rune has been removed\n```\n\n### rune_renamed\n\n```\n`%name%` is now `%replacement%`\n```\n\n### runes_mode_invalid_import\n\n```\n%name% cannot be used in runes mode\n```\n\n### script_duplicate\n\n```\nA component can have a single top-level `<script>` element and/or a single top-level `<script module>` element\n```\n\n### script_invalid_attribute_value\n\n```\nIf the `%name%` attribute is supplied, it must be a boolean attribute\n```\n\n### script_invalid_context\n\n```\nIf the context attribute is supplied, its value must be \"module\"\n```\n\n### script_reserved_attribute\n\n```\nThe `%name%` attribute is reserved and cannot be used\n```\n\n### slot_attribute_duplicate\n\n```\nDuplicate slot name '%name%' in <%component%>\n```\n\n### slot_attribute_invalid\n\n```\nslot attribute must be a static value\n```\n\n### slot_attribute_invalid_placement\n\n```\nElement with a slot='...' attribute must be a child of a component or a descendant of a custom element\n```\n\n### slot_default_duplicate\n\n```\nFound default slot content alongside an explicit slot=\"default\"\n```\n\n### slot_element_invalid_attribute\n\n```\n`<slot>` can only receive attributes and (optionally) let directives\n```\n\n### slot_element_invalid_name\n\n```\nslot attribute must be a static value\n```\n\n### slot_element_invalid_name_default\n\n```\n`default` is a reserved word — it cannot be used as a slot name\n```\n\n### slot_snippet_conflict\n\n```\nCannot use `<slot>` syntax and `{@render ...}` tags in the same component. Migrate towards `{@render ...}` tags completely\n```\n\n### snippet_conflict\n\n```\nCannot use explicit children snippet at the same time as implicit children content. Remove either the non-whitespace content or the children snippet block\n```\n\n### snippet_invalid_export\n\n```\nAn exported snippet can only reference things declared in a `<script module>`, or other exportable snippets\n```\n\nIt's possible to export a snippet from a `<script module>` block, but only if it doesn't reference anything defined inside a non-module-level `<script>`. For example you can't do this...\n\n```svelte\n<script module>\n\texport { greeting };\n</script>\n\n<script>\n\tlet message = 'hello';\n</script>\n\n{#snippet greeting(name)}\n\t<p>{message} {name}!</p>\n{/snippet}\n```\n\n...because `greeting` references `message`, which is defined in the second `<script>`.\n\n### snippet_invalid_rest_parameter\n\n```\nSnippets do not support rest parameters; use an array instead\n```\n\n### snippet_parameter_assignment\n\n```\nCannot reassign or bind to snippet parameter\n```\n\n### snippet_shadowing_prop\n\n```\nThis snippet is shadowing the prop `%prop%` with the same name\n```\n\n### state_field_duplicate\n\n```\n`%name%` has already been declared on this class\n```\n\nAn assignment to a class field that uses a `$state` or `$derived` rune is considered a _state field declaration_. The declaration can happen in the class body...\n\n```js\nclass Counter {\n\tcount = $state(0);\n}\n```\n\n...or inside the constructor...\n\n```js\nclass Counter {\n\tconstructor() {\n\t\tthis.count = $state(0);\n\t}\n}\n```\n\n...but it can only happen once.\n\n### state_field_invalid_assignment\n\n```\nCannot assign to a state field before its declaration\n```\n\n### state_invalid_export\n\n```\nCannot export state from a module if it is reassigned. Either export a function returning the state value or only mutate the state value's properties\n```\n\n### state_invalid_placement\n\n```\n`%rune%(...)` can only be used as a variable declaration initializer, a class field declaration, or the first assignment to a class field at the top level of the constructor.\n```\n\n### store_invalid_scoped_subscription\n\n```\nCannot subscribe to stores that are not declared at the top level of the component\n```\n\n### store_invalid_subscription\n\n```\nCannot reference store value inside `<script module>`\n```\n\n### store_invalid_subscription_module\n\n```\nCannot reference store value outside a `.svelte` file\n```\n\nUsing a `$` prefix to refer to the value of a store is only possible inside `.svelte` files, where Svelte can automatically create subscriptions when a component is mounted and unsubscribe when the component is unmounted. Consider migrating to runes instead.\n\n### style_directive_invalid_modifier\n\n```\n`style:` directive can only use the `important` modifier\n```\n\n### style_duplicate\n\n```\nA component can have a single top-level `<style>` element\n```\n\n### svelte_body_illegal_attribute\n\n```\n`<svelte:body>` does not support non-event attributes or spread attributes\n```\n\n### svelte_boundary_invalid_attribute\n\n```\nValid attributes on `<svelte:boundary>` are `onerror` and `failed`\n```\n\n### svelte_boundary_invalid_attribute_value\n\n```\nAttribute value must be a non-string expression\n```\n\n### svelte_component_invalid_this\n\n```\nInvalid component definition — must be an `{expression}`\n```\n\n### svelte_component_missing_this\n\n```\n`<svelte:component>` must have a 'this' attribute\n```\n\n### svelte_element_missing_this\n\n```\n`<svelte:element>` must have a 'this' attribute with a value\n```\n\n### svelte_fragment_invalid_attribute\n\n```\n`<svelte:fragment>` can only have a slot attribute and (optionally) a let: directive\n```\n\n### svelte_fragment_invalid_placement\n\n```\n`<svelte:fragment>` must be the direct child of a component\n```\n\n### svelte_head_illegal_attribute\n\n```\n`<svelte:head>` cannot have attributes nor directives\n```\n\n### svelte_meta_duplicate\n\n```\nA component can only have one `<%name%>` element\n```\n\n### svelte_meta_invalid_content\n\n```\n<%name%> cannot have children\n```\n\n### svelte_meta_invalid_placement\n\n```\n`<%name%>` tags cannot be inside elements or blocks\n```\n\n### svelte_meta_invalid_tag\n\n```\nValid `<svelte:...>` tag names are %list%\n```\n\n### svelte_options_deprecated_tag\n\n```\n\"tag\" option is deprecated — use \"customElement\" instead\n```\n\n### svelte_options_invalid_attribute\n\n```\n`<svelte:options>` can only receive static attributes\n```\n\n### svelte_options_invalid_attribute_value\n\n```\nValue must be %list%, if specified\n```\n\n### svelte_options_invalid_customelement\n\n```\n\"customElement\" must be a string literal defining a valid custom element name or an object of the form { tag?: string; shadow?: \"open\" | \"none\" | `ShadowRootInit`; props?: { [key: string]: { attribute?: string; reflect?: boolean; type: .. } } }\n```\n\n### svelte_options_invalid_customelement_props\n\n```\n\"props\" must be a statically analyzable object literal of the form \"{ [key: string]: { attribute?: string; reflect?: boolean; type?: \"String\" | \"Boolean\" | \"Number\" | \"Array\" | \"Object\" }\"\n```\n\n### svelte_options_invalid_customelement_shadow\n\n```\n\"shadow\" must be either \"open\", \"none\" or `ShadowRootInit` object.\n```\n\nSee https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow#options for more information on valid shadow root constructor options\n\n### svelte_options_invalid_tagname\n\n```\nTag name must be lowercase and hyphenated\n```\n\nSee https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name for more information on valid tag names\n\n### svelte_options_reserved_tagname\n\n```\nTag name is reserved\n```\n\nSee https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name for more information on valid tag names\n\n### svelte_options_unknown_attribute\n\n```\n`<svelte:options>` unknown attribute '%name%'\n```\n\n### svelte_self_invalid_placement\n\n```\n`<svelte:self>` components can only exist inside `{#if}` blocks, `{#each}` blocks, `{#snippet}` blocks or slots passed to components\n```\n\n### tag_invalid_name\n\n```\nExpected a valid element or component name. Components must have a valid variable name or dot notation expression\n```\n\n### tag_invalid_placement\n\n```\n{@%name% ...} tag cannot be %location%\n```\n\n### textarea_invalid_content\n\n```\nA `<textarea>` can have either a value attribute or (equivalently) child content, but not both\n```\n\n### title_illegal_attribute\n\n```\n`<title>` cannot have attributes nor directives\n```\n\n### title_invalid_content\n\n```\n`<title>` can only contain text and {tags}\n```\n\n### transition_conflict\n\n```\nCannot use `%type%:` alongside existing `%existing%:` directive\n```\n\n### transition_duplicate\n\n```\nCannot use multiple `%type%:` directives on a single element\n```\n\n### typescript_invalid_feature\n\n```\nTypeScript language features like %feature% are not natively supported, and their use is generally discouraged. Outside of `<script>` tags, these features are not supported. For use within `<script>` tags, you will need to use a preprocessor to convert it to JavaScript before it gets passed to the Svelte compiler. If you are using `vitePreprocess`, make sure to specifically enable preprocessing script tags (`vitePreprocess({ script: true })`)\n```\n\n### unexpected_eof\n\n```\nUnexpected end of input\n```\n\n### unexpected_reserved_word\n\n```\n'%word%' is a reserved word in JavaScript and cannot be used here\n```\n\n### unterminated_string_constant\n\n```\nUnterminated string constant\n```\n\n### void_element_invalid_content\n\n```\nVoid elements cannot have children or closing tags\n```","size_bytes":24314,"metadata":{"title":"Compiler errors"},"created_at":"2025-07-18T15:47:39.047Z","updated_at":"2026-02-28T02:00:03.914Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/30-compiler-warnings.md","title":"Compiler warnings","filename":"30-compiler-warnings.md","content":"Svelte warns you at compile time if it catches potential mistakes, such as writing inaccessible markup.\n\nSome warnings may be incorrect in your concrete use case. You can disable such false positives by placing a `<!-- svelte-ignore <code> -->` comment above the line that causes the warning. Example:\n\n```svelte\n<!-- svelte-ignore a11y_autofocus -->\n<input autofocus />\n```\n\nYou can list multiple rules in a single comment (separated by commas), and add an explanatory note (in parentheses) alongside them:\n\n```svelte\n<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions (because of reasons) -->\n<div onclick>...</div>\n```\n\n<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n### a11y_accesskey\n\n```\nAvoid using accesskey\n```\n\nEnforce no `accesskey` on element. Access keys are HTML attributes that allow web developers to assign keyboard shortcuts to elements. Inconsistencies between keyboard shortcuts and keyboard commands used by screen reader and keyboard-only users create accessibility complications. To avoid complications, access keys should not be used.\n\n```svelte\n<!-- A11y: Avoid using accesskey -->\n<div accesskey=\"z\"></div>\n```\n\n### a11y_aria_activedescendant_has_tabindex\n\n```\nAn element with an aria-activedescendant attribute should have a tabindex value\n```\n\nAn element with `aria-activedescendant` must be tabbable, so it must either have an inherent `tabindex` or declare `tabindex` as an attribute.\n\n```svelte\n<!-- A11y: Elements with attribute aria-activedescendant should have tabindex value -->\n<div aria-activedescendant=\"some-id\"></div>\n```\n\n### a11y_aria_attributes\n\n```\n`<%name%>` should not have aria-* attributes\n```\n\nCertain reserved DOM elements do not support ARIA roles, states and properties. This is often because they are not visible, for example `meta`, `html`, `script`, `style`. This rule enforces that these DOM elements do not contain the `aria-*` props.\n\n```svelte\n<!-- A11y: <meta> should not have aria-* attributes -->\n<meta aria-hidden=\"false\" />\n```\n\n### a11y_autocomplete_valid\n\n```\n'%value%' is an invalid value for 'autocomplete' on `<input type=\"%type%\">`\n```\n\n### a11y_autofocus\n\n```\nAvoid using autofocus\n```\n\nEnforce that `autofocus` is not used on elements. Autofocusing elements can cause usability issues for sighted and non-sighted users alike.\n\n```svelte\n<!-- A11y: Avoid using autofocus -->\n<input autofocus />\n```\n\n### a11y_click_events_have_key_events\n\n```\nVisible, non-interactive elements with a click event must be accompanied by a keyboard event handler. Consider whether an interactive element such as `<button type=\"button\">` or `<a>` might be more appropriate\n```\n\nEnforce that visible, non-interactive elements with an `onclick` event are accompanied by a keyboard event handler.\n\nUsers should first consider whether an interactive element might be more appropriate such as a `<button type=\"button\">` element for actions or `<a>` element for navigations. These elements are more semantically meaningful and will have built-in key handling. E.g. `Space` and `Enter` will trigger a `<button>` and `Enter` will trigger an `<a>` element.\n\nIf a non-interactive element is required then `onclick` should be accompanied by an `onkeyup` or `onkeydown` handler that enables the user to perform equivalent actions via the keyboard. In order for the user to be able to trigger a key press, the element will also need to be focusable by adding a [`tabindex`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex). While an `onkeypress` handler will also silence this warning, it should be noted that the `keypress` event is deprecated.\n\n```svelte\n<!-- A11y: visible, non-interactive elements with an onclick event must be accompanied by a keyboard event handler. -->\n<div onclick={() => {}}></div>\n```\n\nCoding for the keyboard is important for users with physical disabilities who cannot use a mouse, AT compatibility, and screenreader users.\n\n### a11y_consider_explicit_label\n\n```\nButtons and links should either contain text or have an `aria-label`, `aria-labelledby` or `title` attribute\n```\n\n### a11y_distracting_elements\n\n```\nAvoid `<%name%>` elements\n```\n\nEnforces that no distracting elements are used. Elements that can be visually distracting can cause accessibility issues with visually impaired users. Such elements are most likely deprecated, and should be avoided.\n\nThe following elements are visually distracting: `<marquee>` and `<blink>`.\n\n```svelte\n<!-- A11y: Avoid <marquee> elements -->\n<marquee></marquee>\n```\n\n### a11y_figcaption_index\n\n```\n`<figcaption>` must be first or last child of `<figure>`\n```\n\n### a11y_figcaption_parent\n\n```\n`<figcaption>` must be an immediate child of `<figure>`\n```\n\nEnforce that certain DOM elements have the correct structure.\n\n```svelte\n<!-- A11y: <figcaption> must be an immediate child of <figure> -->\n<div>\n\t<figcaption>Image caption</figcaption>\n</div>\n```\n\n### a11y_hidden\n\n```\n`<%name%>` element should not be hidden\n```\n\nCertain DOM elements are useful for screen reader navigation and should not be hidden.\n\n```svelte\n<!-- A11y: <h2> element should not be hidden -->\n<h2 aria-hidden=\"true\">invisible header</h2>\n```\n\n### a11y_img_redundant_alt\n\n```\nScreenreaders already announce `<img>` elements as an image\n```\n\nEnforce img alt attribute does not contain the word image, picture, or photo. Screen readers already announce `img` elements as an image. There is no need to use words such as _image_, _photo_, and/or _picture_.\n\n```svelte\n<img src=\"foo\" alt=\"Foo eating a sandwich.\" />\n\n<!-- aria-hidden, won't be announced by screen reader -->\n<img src=\"bar\" aria-hidden=\"true\" alt=\"Picture of me taking a photo of an image\" />\n\n<!-- A11y: Screen readers already announce <img> elements as an image. -->\n<img src=\"foo\" alt=\"Photo of foo being weird.\" />\n\n<!-- A11y: Screen readers already announce <img> elements as an image. -->\n<img src=\"bar\" alt=\"Image of me at a bar!\" />\n\n<!-- A11y: Screen readers already announce <img> elements as an image. -->\n<img src=\"foo\" alt=\"Picture of baz fixing a bug.\" />\n```\n\n### a11y_incorrect_aria_attribute_type\n\n```\nThe value of '%attribute%' must be a %type%\n```\n\nEnforce that only the correct type of value is used for aria attributes. For example, `aria-hidden`\nshould only receive a boolean.\n\n```svelte\n<!-- A11y: The value of 'aria-hidden' must be exactly one of true or false -->\n<div aria-hidden=\"yes\"></div>\n```\n\n### a11y_incorrect_aria_attribute_type_boolean\n\n```\nThe value of '%attribute%' must be either 'true' or 'false'. It cannot be empty\n```\n\n### a11y_incorrect_aria_attribute_type_id\n\n```\nThe value of '%attribute%' must be a string that represents a DOM element ID\n```\n\n### a11y_incorrect_aria_attribute_type_idlist\n\n```\nThe value of '%attribute%' must be a space-separated list of strings that represent DOM element IDs\n```\n\n### a11y_incorrect_aria_attribute_type_integer\n\n```\nThe value of '%attribute%' must be an integer\n```\n\n### a11y_incorrect_aria_attribute_type_token\n\n```\nThe value of '%attribute%' must be exactly one of %values%\n```\n\n### a11y_incorrect_aria_attribute_type_tokenlist\n\n```\nThe value of '%attribute%' must be a space-separated list of one or more of %values%\n```\n\n### a11y_incorrect_aria_attribute_type_tristate\n\n```\nThe value of '%attribute%' must be exactly one of true, false, or mixed\n```\n\n### a11y_interactive_supports_focus\n\n```\nElements with the '%role%' interactive role must have a tabindex value\n```\n\nEnforce that elements with an interactive role and interactive handlers (mouse or key press) must be focusable or tabbable.\n\n```svelte\n<!-- A11y: Elements with the 'button' interactive role must have a tabindex value. -->\n<div role=\"button\" onkeypress={() => {}} />\n```\n\n### a11y_invalid_attribute\n\n```\n'%href_value%' is not a valid %href_attribute% attribute\n```\n\nEnforce that attributes important for accessibility have a valid value. For example, `href` should not be empty, `'#'`, or `javascript:`.\n\n```svelte\n<!-- A11y: '' is not a valid href attribute -->\n<a href=\"\">invalid</a>\n```\n\n### a11y_label_has_associated_control\n\n```\nA form label must be associated with a control\n```\n\nEnforce that a label tag has a text label and an associated control.\n\nThere are two supported ways to associate a label with a control:\n\n- Wrapping a control in a label tag.\n- Adding `for` to a label and assigning it the ID of an input on the page.\n\n```svelte\n<label for=\"id\">B</label>\n\n<label>C <input type=\"text\" /></label>\n\n<!-- A11y: A form label must be associated with a control. -->\n<label>A</label>\n```\n\n### a11y_media_has_caption\n\n```\n`<video>` elements must have a `<track kind=\"captions\">`\n```\n\nProviding captions for media is essential for deaf users to follow along. Captions should be a transcription or translation of the dialogue, sound effects, relevant musical cues, and other relevant audio information. Not only is this important for accessibility, but can also be useful for all users in the case that the media is unavailable (similar to `alt` text on an image when an image is unable to load).\n\nThe captions should contain all important and relevant information to understand the corresponding media. This may mean that the captions are not a 1:1 mapping of the dialogue in the media content. However, captions are not necessary for video components with the `muted` attribute.\n\n```svelte\n<video><track kind=\"captions\" /></video>\n\n<audio muted></audio>\n\n<!-- A11y: Media elements must have a <track kind=\\\"captions\\\"> -->\n<video></video>\n\n<!-- A11y: Media elements must have a <track kind=\\\"captions\\\"> -->\n<video><track /></video>\n```\n\n### a11y_misplaced_role\n\n```\n`<%name%>` should not have role attribute\n```\n\nCertain reserved DOM elements do not support ARIA roles, states and properties. This is often because they are not visible, for example `meta`, `html`, `script`, `style`. This rule enforces that these DOM elements do not contain the `role` props.\n\n```svelte\n<!-- A11y: <meta> should not have role attribute -->\n<meta role=\"tooltip\" />\n```\n\n### a11y_misplaced_scope\n\n```\nThe scope attribute should only be used with `<th>` elements\n```\n\nThe scope attribute should only be used on `<th>` elements.\n\n```svelte\n<!-- A11y: The scope attribute should only be used with <th> elements -->\n<div scope=\"row\" />\n```\n\n### a11y_missing_attribute\n\n```\n`<%name%>` element should have %article% %sequence% attribute\n```\n\nEnforce that attributes required for accessibility are present on an element. This includes the following checks:\n\n- `<a>` should have an href (unless it's a [fragment-defining tag](https://github.com/sveltejs/svelte/issues/4697))\n- `<area>` should have alt, aria-label, or aria-labelledby\n- `<html>` should have lang\n- `<iframe>` should have title\n- `<img>` should have alt\n- `<object>` should have title, aria-label, or aria-labelledby\n- `<input type=\"image\">` should have alt, aria-label, or aria-labelledby\n\n```svelte\n<!-- A11y: <input type=\\\"image\\\"> element should have an alt, aria-label or aria-labelledby attribute -->\n<input type=\"image\" />\n\n<!-- A11y: <html> element should have a lang attribute -->\n<html></html>\n\n<!-- A11y: <a> element should have an href attribute -->\n<a>text</a>\n```\n\n### a11y_missing_content\n\n```\n`<%name%>` element should contain text\n```\n\nEnforce that heading elements (`h1`, `h2`, etc.) and anchors have content and that the content is accessible to screen readers\n\n```svelte\n<!-- A11y: <a> element should have child content -->\n<a href=\"/foo\"></a>\n\n<!-- A11y: <h1> element should have child content -->\n<h1></h1>\n```\n\n### a11y_mouse_events_have_key_events\n\n```\n'%event%' event must be accompanied by '%accompanied_by%' event\n```\n\nEnforce that `onmouseover` and `onmouseout` are accompanied by `onfocus` and `onblur`, respectively. This helps to ensure that any functionality triggered by these mouse events is also accessible to keyboard users.\n\n```svelte\n<!-- A11y: onmouseover must be accompanied by onfocus -->\n<div onmouseover={handleMouseover} />\n\n<!-- A11y: onmouseout must be accompanied by onblur -->\n<div onmouseout={handleMouseout} />\n```\n\n### a11y_no_abstract_role\n\n```\nAbstract role '%role%' is forbidden\n```\n\n### a11y_no_interactive_element_to_noninteractive_role\n\n```\n`<%element%>` cannot have role '%role%'\n```\n\n[WAI-ARIA](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) roles should not be used to convert an interactive element to a non-interactive element. Non-interactive ARIA roles include `article`, `banner`, `complementary`, `img`, `listitem`, `main`, `region` and `tooltip`.\n\n```svelte\n<!-- A11y: <textarea> cannot have role 'listitem' -->\n<textarea role=\"listitem\"></textarea>\n```\n\n### a11y_no_noninteractive_element_interactions\n\n```\nNon-interactive element `<%element%>` should not be assigned mouse or keyboard event listeners\n```\n\nA non-interactive element does not support event handlers (mouse and key handlers). Non-interactive elements include `<main>`, `<area>`, `<h1>` (,`<h2>`, etc), `<p>`, `<img>`, `<li>`, `<ul>` and `<ol>`. Non-interactive [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) include `article`, `banner`, `complementary`, `img`, `listitem`, `main`, `region` and `tooltip`.\n\n```sv\n<!-- `A11y: Non-interactive element <li> should not be assigned mouse or keyboard event listeners.` -->\n<li onclick={() => {}}></li>\n\n<!-- `A11y: Non-interactive element <div> should not be assigned mouse or keyboard event listeners.` -->\n<div role=\"listitem\" onclick={() => {}}></div>\n```\n\n### a11y_no_noninteractive_element_to_interactive_role\n\n```\nNon-interactive element `<%element%>` cannot have interactive role '%role%'\n```\n\n[WAI-ARIA](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) roles should not be used to convert a non-interactive element to an interactive element. Interactive ARIA roles include `button`, `link`, `checkbox`, `menuitem`, `menuitemcheckbox`, `menuitemradio`, `option`, `radio`, `searchbox`, `switch` and `textbox`.\n\n```svelte\n<!-- A11y: Non-interactive element <h3> cannot have interactive role 'searchbox' -->\n<h3 role=\"searchbox\">Button</h3>\n```\n\n### a11y_no_noninteractive_tabindex\n\n```\nnoninteractive element cannot have nonnegative tabIndex value\n```\n\nTab key navigation should be limited to elements on the page that can be interacted with.\n\n```svelte\n<!-- A11y: noninteractive element cannot have nonnegative tabIndex value -->\n<div tabindex=\"0\"></div>\n```\n\n### a11y_no_redundant_roles\n\n```\nRedundant role '%role%'\n```\n\nSome HTML elements have default ARIA roles. Giving these elements an ARIA role that is already set by the browser [has no effect](https://www.w3.org/TR/using-aria/#aria-does-nothing) and is redundant.\n\n```svelte\n<!-- A11y: Redundant role 'button' -->\n<button role=\"button\">...</button>\n\n<!-- A11y: Redundant role 'img' -->\n<img role=\"img\" src=\"foo.jpg\" />\n```\n\n### a11y_no_static_element_interactions\n\n```\n`<%element%>` with a %handler% handler must have an ARIA role\n```\n\nElements like `<div>` with interactive handlers like `click` must have an ARIA role.\n\n```svelte\n<!-- A11y: <div> with click handler must have an ARIA role -->\n<div onclick={() => ''}></div>\n```\n\n### a11y_positive_tabindex\n\n```\nAvoid tabindex values above zero\n```\n\nAvoid positive `tabindex` property values. This will move elements out of the expected tab order, creating a confusing experience for keyboard users.\n\n```svelte\n<!-- A11y: avoid tabindex values above zero -->\n<div tabindex=\"1\"></div>\n```\n\n### a11y_role_has_required_aria_props\n\n```\nElements with the ARIA role \"%role%\" must have the following attributes defined: %props%\n```\n\nElements with ARIA roles must have all required attributes for that role.\n\n```svelte\n<!-- A11y: A11y: Elements with the ARIA role \"checkbox\" must have the following attributes defined: \"aria-checked\" -->\n<span role=\"checkbox\" aria-labelledby=\"foo\" tabindex=\"0\"></span>\n```\n\n### a11y_role_supports_aria_props\n\n```\nThe attribute '%attribute%' is not supported by the role '%role%'\n```\n\nElements with explicit or implicit roles defined contain only `aria-*` properties supported by that role.\n\n```svelte\n<!-- A11y: The attribute 'aria-multiline' is not supported by the role 'link'. -->\n<div role=\"link\" aria-multiline></div>\n\n<!-- A11y: The attribute 'aria-required' is not supported by the role 'listitem'. This role is implicit on the element <li>. -->\n<li aria-required></li>\n```\n\n### a11y_role_supports_aria_props_implicit\n\n```\nThe attribute '%attribute%' is not supported by the role '%role%'. This role is implicit on the element `<%name%>`\n```\n\nElements with explicit or implicit roles defined contain only `aria-*` properties supported by that role.\n\n```svelte\n<!-- A11y: The attribute 'aria-multiline' is not supported by the role 'link'. -->\n<div role=\"link\" aria-multiline></div>\n\n<!-- A11y: The attribute 'aria-required' is not supported by the role 'listitem'. This role is implicit on the element <li>. -->\n<li aria-required></li>\n```\n\n### a11y_unknown_aria_attribute\n\n```\nUnknown aria attribute 'aria-%attribute%'\n```\n\n```\nUnknown aria attribute 'aria-%attribute%'. Did you mean '%suggestion%'?\n```\n\nEnforce that only known ARIA attributes are used. This is based on the [WAI-ARIA States and Properties spec](https://www.w3.org/WAI/PF/aria-1.1/states_and_properties).\n\n```svelte\n<!-- A11y: Unknown aria attribute 'aria-labeledby' (did you mean 'labelledby'?) -->\n<input type=\"image\" aria-labeledby=\"foo\" />\n```\n\n### a11y_unknown_role\n\n```\nUnknown role '%role%'\n```\n\n```\nUnknown role '%role%'. Did you mean '%suggestion%'?\n```\n\nElements with ARIA roles must use a valid, non-abstract ARIA role. A reference to role definitions can be found at [WAI-ARIA](https://www.w3.org/TR/wai-aria/#role_definitions) site.\n\n```svelte\n<!-- A11y: Unknown role 'toooltip' (did you mean 'tooltip'?) -->\n<div role=\"toooltip\"></div>\n```\n\n### attribute_avoid_is\n\n```\nThe \"is\" attribute is not supported cross-browser and should be avoided\n```\n\n### attribute_global_event_reference\n\n```\nYou are referencing `globalThis.%name%`. Did you forget to declare a variable with that name?\n```\n\n### attribute_illegal_colon\n\n```\nAttributes should not contain ':' characters to prevent ambiguity with Svelte directives\n```\n\n### attribute_invalid_property_name\n\n```\n'%wrong%' is not a valid HTML attribute. Did you mean '%right%'?\n```\n\n### attribute_quoted\n\n```\nQuoted attributes on components and custom elements will be stringified in a future version of Svelte. If this isn't what you want, remove the quotes\n```\n\n### bidirectional_control_characters\n\n```\nA bidirectional control character was detected in your code. These characters can be used to alter the visual direction of your code and could have unintended consequences\n```\n\nBidirectional control characters can alter the direction in which text appears to be in. For example, via control characters, you can make `defabc` look like `abcdef`. As a result, if you were to unknowingly copy and paste some code that has these control characters, they may alter the behavior of your code in ways you did not intend. See [trojansource.codes](https://trojansource.codes/) for more information.\n\n### bind_invalid_each_rest\n\n```\nThe rest operator (...) will create a new object and binding '%name%' with the original object will not work\n```\n\n### block_empty\n\n```\nEmpty block\n```\n\n### component_name_lowercase\n\n```\n`<%name%>` will be treated as an HTML element unless it begins with a capital letter\n```\n\n### css_unused_selector\n\n```\nUnused CSS selector \"%name%\"\n```\n\nSvelte traverses both the template and the `<style>` tag to find out which of the CSS selectors are not used within the template, so it can remove them.\n\nIn some situations a selector may target an element that is not 'visible' to the compiler, for example because it is part of an `{@html ...}` tag or you're overriding styles in a child component. In these cases, use [`:global`](/docs/svelte/global-styles) to preserve the selector as-is:\n\n```svelte\n<div class=\"post\">{@html content}</div>\n\n<style>\n  .post :global {\n    p {...}\n  }\n</style>\n```\n\n### custom_element_props_identifier\n\n```\nUsing a rest element or a non-destructured declaration with `$props()` means that Svelte can't infer what properties to expose when creating a custom element. Consider destructuring all the props or explicitly specifying the `customElement.props` option.\n```\n\n### element_implicitly_closed\n\n```\nThis element is implicitly closed by the following `%tag%`, which can cause an unexpected DOM structure. Add an explicit `%closing%` to avoid surprises.\n```\n\nIn HTML, some elements are implicitly closed by another element. For example, you cannot nest a `<p>` inside another `<p>`:\n\n```html\n<!-- this HTML... -->\n<p><p>hello</p>\n\n<!-- results in this DOM structure -->\n<p></p>\n<p>hello</p>\n```\n\nSimilarly, a parent element's closing tag will implicitly close all child elements, even if the `</` was a typo and you meant to create a _new_ element. To avoid ambiguity, it's always a good idea to have an explicit closing tag.\n\n### element_invalid_self_closing_tag\n\n```\nSelf-closing HTML tags for non-void elements are ambiguous — use `<%name% ...></%name%>` rather than `<%name% ... />`\n```\n\nIn HTML, there's [no such thing as a self-closing tag](https://jakearchibald.com/2023/against-self-closing-tags-in-html/). While this _looks_ like a self-contained element with some text next to it...\n\n```html\n<div>\n\t<span class=\"icon\" /> some text!\n</div>\n```\n\n...a spec-compliant HTML parser (such as a browser) will in fact parse it like this, with the text _inside_ the icon:\n\n```html\n<div>\n\t<span class=\"icon\"> some text! </span>\n</div>\n```\n\nSome templating languages (including Svelte) will 'fix' HTML by turning `<span />` into `<span></span>`. Others adhere to the spec. Both result in ambiguity and confusion when copy-pasting code between different contexts, so Svelte prompts you to resolve the ambiguity directly by having an explicit closing tag.\n\nTo automate this, run the dedicated migration:\n\n```sh\nnpx sv migrate self-closing-tags\n```\n\nIn a future version of Svelte, self-closing tags may be upgraded from a warning to an error.\n\n### event_directive_deprecated\n\n```\nUsing `on:%name%` to listen to the %name% event is deprecated. Use the event attribute `on%name%` instead\n```\n\nSee [the migration guide](v5-migration-guide#Event-changes) for more info.\n\n### export_let_unused\n\n```\nComponent has unused export property '%name%'. If it is for external reference only, please consider using `export const %name%`\n```\n\n### legacy_code\n\n```\n`%code%` is no longer valid — please use `%suggestion%` instead\n```\n\n### legacy_component_creation\n\n```\nSvelte 5 components are no longer classes. Instantiate them using `mount` or `hydrate` (imported from 'svelte') instead.\n```\n\nSee the [migration guide](v5-migration-guide#Components-are-no-longer-classes) for more info.\n\n### node_invalid_placement_ssr\n\n```\n%message%. When rendering this component on the server, the resulting HTML will be modified by the browser (by moving, removing, or inserting elements), likely resulting in a `hydration_mismatch` warning\n```\n\nHTML restricts where certain elements can appear. In case of a violation the browser will 'repair' the HTML in a way that breaks Svelte's assumptions about the structure of your components. Some examples:\n\n- `<p>hello <div>world</div></p>` will result in `<p>hello </p><div>world</div><p></p>` (the `<div>` autoclosed the `<p>` because `<p>` cannot contain block-level elements)\n- `<option><div>option a</div></option>` will result in `<option>option a</option>` (the `<div>` is removed)\n- `<table><tr><td>cell</td></tr></table>` will result in `<table><tbody><tr><td>cell</td></tr></tbody></table>` (a `<tbody>` is auto-inserted)\n\nThis code will work when the component is rendered on the client (which is why this is a warning rather than an error), but if you use server rendering it will cause hydration to fail.\n\n### non_reactive_update\n\n```\n`%name%` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates\n```\n\nThis warning is thrown when the compiler detects the following:\n- a variable was declared without `$state` or `$state.raw`\n- the variable is reassigned\n- the variable is read in a reactive context\n\nIn this case, changing the value will not correctly trigger updates. Example:\n\n```svelte\n<script>\n\tlet reactive = $state('reactive');\n\tlet stale = 'stale';\n</script>\n\n<p>This value updates: {reactive}</p>\n<p>This value does not update: {stale}</p>\n\n<button onclick={() => {\n\tstale = 'updated';\n\treactive = 'updated';\n}}>update</button>\n```\n\nTo fix this, wrap your variable declaration with `$state`.\n\n### options_deprecated_accessors\n\n```\nThe `accessors` option has been deprecated. It will have no effect in runes mode\n```\n\n### options_deprecated_immutable\n\n```\nThe `immutable` option has been deprecated. It will have no effect in runes mode\n```\n\n### options_missing_custom_element\n\n```\nThe `customElement` option is used when generating a custom element. Did you forget the `customElement: true` compile option?\n```\n\n### options_removed_enable_sourcemap\n\n```\nThe `enableSourcemap` option has been removed. Source maps are always generated now, and tooling can choose to ignore them\n```\n\n### options_removed_hydratable\n\n```\nThe `hydratable` option has been removed. Svelte components are always hydratable now\n```\n\n### options_removed_loop_guard_timeout\n\n```\nThe `loopGuardTimeout` option has been removed\n```\n\n### options_renamed_ssr_dom\n\n```\n`generate: \"dom\"` and `generate: \"ssr\"` options have been renamed to \"client\" and \"server\" respectively\n```\n\n### perf_avoid_inline_class\n\n```\nAvoid 'new class' — instead, declare the class at the top level scope\n```\n\n### perf_avoid_nested_class\n\n```\nAvoid declaring classes below the top level scope\n```\n\n### reactive_declaration_invalid_placement\n\n```\nReactive declarations only exist at the top level of the instance script\n```\n\n### reactive_declaration_module_script_dependency\n\n```\nReassignments of module-level declarations will not cause reactive statements to update\n```\n\n### script_context_deprecated\n\n```\n`context=\"module\"` is deprecated, use the `module` attribute instead\n```\n\n```svelte\n<scriptcontext=\"module\"module>\n\tlet foo = 'bar';\n</script>\n```\n\n### script_unknown_attribute\n\n```\nUnrecognized attribute — should be one of `generics`, `lang` or `module`. If this exists for a preprocessor, ensure that the preprocessor removes it\n```\n\n### slot_element_deprecated\n\n```\nUsing `<slot>` to render parent content is deprecated. Use `{@render ...}` tags instead\n```\n\nSee [the migration guide](v5-migration-guide#Snippets-instead-of-slots) for more info.\n\n### state_referenced_locally\n\n```\nThis reference only captures the initial value of `%name%`. Did you mean to reference it inside a %type% instead?\n```\n\nThis warning is thrown when the compiler detects the following:\n\n- A reactive variable is declared\n- ...and later reassigned...\n- ...and referenced in the same scope\n\nThis 'breaks the link' to the original state declaration. For example, if you pass the state to a function, the function loses access to the state once it is reassigned:\n\n```svelte\n<!file: Parent.svelte>\n<script>\n\timport { setContext } from 'svelte';\n\n\tlet count = $state(0);\n\n\t// warning: state_referenced_locally\n\tsetContext('count', count);\n</script>\n\n<button onclick={() => count++}>\n\tincrement\n</button>\n```\n\n```svelte\n<!file: Child.svelte>\n<script>\n\timport { getContext } from 'svelte';\n\n\tconst count = getContext('count');\n</script>\n\n<!-- This will never update -->\n<p>The count is {count}</p>\n```\n\nTo fix this, reference the variable such that it is lazily evaluated. For the above example, this can be achieved by wrapping `count` in a function:\n\n```svelte\n<!file: Parent.svelte>\n<script>\n\timport { setContext } from 'svelte';\n\n\tlet count = $state(0);\n\tsetContext('count',() => count);\n</script>\n\n<button onclick={() => count++}>\n\tincrement\n</button>\n```\n\n```svelte\n<!file: Child.svelte>\n<script>\n\timport { getContext } from 'svelte';\n\n\tconst count = getContext('count');\n</script>\n\n<!-- This will update -->\n<p>The count is {count()}</p>\n```\n\nFor more info, see [Passing state into functions]($state#Passing-state-into-functions).\n\n### store_rune_conflict\n\n```\nIt looks like you're using the `$%name%` rune, but there is a local binding called `%name%`. Referencing a local variable with a `$` prefix will create a store subscription. Please rename `%name%` to avoid the ambiguity\n```\n\n### svelte_component_deprecated\n\n```\n`<svelte:component>` is deprecated in runes mode — components are dynamic by default\n```\n\nIn previous versions of Svelte, the component constructor was fixed when the component was rendered. In other words, if you wanted `<X>` to re-render when `X` changed, you would either have to use `<svelte:component this={X}>` or put the component inside a `{#key X}...{/key}` block.\n\nIn Svelte 5 this is no longer true — if `X` changes, `<X>` re-renders.\n\nIn some cases `<object.property>` syntax can be used as a replacement; a lowercased variable with property access is recognized as a component in Svelte 5.\n\nFor complex component resolution logic, an intermediary, capitalized variable may be necessary. E.g. in places where `@const` can be used:\n\n```svelte\n{#each items as item}\n\t<svelte:component this={item.condition ? Y : Z} />\n\t{@const Component = item.condition ? Y : Z}\n\t<Component />\n{/each}\n```\n\nA derived value may be used in other contexts:\n\n```svelte\n<script>\n\t// ...\n\tlet condition = $state(false);\n\tconst Component = $derived(condition ? Y : Z);\n</script>\n\n<svelte:component this={condition ? Y : Z} />\n<Component />\n```\n\n### svelte_element_invalid_this\n\n```\n`this` should be an `{expression}`. Using a string attribute value will cause an error in future versions of Svelte\n```\n\n### svelte_self_deprecated\n\n```\n`<svelte:self>` is deprecated — use self-imports (e.g. `import %name% from './%basename%'`) instead\n```\n\nSee [the note in the docs](legacy-svelte-self) for more info.\n\n### unknown_code\n\n```\n`%code%` is not a recognised code\n```\n\n```\n`%code%` is not a recognised code (did you mean `%suggestion%`?)\n```","size_bytes":30189,"metadata":{"title":"Compiler warnings"},"created_at":"2025-07-18T15:47:39.048Z","updated_at":"2025-10-01T02:00:06.115Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-errors.md","title":"Runtime errors","filename":"30-runtime-errors.md","content":"## Client errors\n\n<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n### async_derived_orphan\n\n```\nCannot create a `$derived(...)` with an `await` expression outside of an effect tree\n```\n\nIn Svelte there are two types of reaction — [`$derived`](/docs/svelte/$derived) and [`$effect`](/docs/svelte/$effect). Deriveds can be created anywhere, because they run _lazily_ and can be [garbage collected](https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection) if nothing references them. Effects, by contrast, keep running eagerly whenever their dependencies change, until they are destroyed.\n\nBecause of this, effects can only be created inside other effects (or [effect roots](/docs/svelte/$effect#$effect.root), such as the one that is created when you first mount a component) so that Svelte knows when to destroy them.\n\nSome sleight of hand occurs when a derived contains an `await` expression: Since waiting until we read `{await getPromise()}` to call `getPromise` would be too late, we use an effect to instead call it proactively, notifying Svelte when the value is available. But since we're using an effect, we can only create asynchronous deriveds inside another effect.\n\n### bind_invalid_checkbox_value\n\n```\nUsing `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\n```\n\n### bind_invalid_export\n\n```\nComponent %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`)\n```\n\n### bind_not_bindable\n\n```\nA component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()`\n```\n\n### component_api_changed\n\n```\nCalling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5\n```\n\nSee the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information.\n\n### component_api_invalid_new\n\n```\nAttempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working.\n```\n\nSee the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information.\n\n### derived_references_self\n\n```\nA derived value cannot reference itself recursively\n```\n\n### each_key_duplicate\n\n```\nKeyed each block has duplicate key at indexes %a% and %b%\n```\n\n```\nKeyed each block has duplicate key `%value%` at indexes %a% and %b%\n```\n\n### each_key_volatile\n\n```\nKeyed each block has key that is not idempotent — the key for item at index %index% was `%a%` but is now `%b%`. Keys must be the same each time for a given item\n```\n\nThe key expression in a keyed each block must return the same value when called multiple times for the same item. Using expressions like `[item.a, item.b]` creates a new array each time, which will never be equal to itself. Instead, use a primitive value or create a stable key like `item.a + '-' + item.b`.\n\n### effect_in_teardown\n\n```\n`%rune%` cannot be used inside an effect cleanup function\n```\n\n### effect_in_unowned_derived\n\n```\nEffect cannot be created inside a `$derived` value that was not itself created inside an effect\n```\n\n### effect_orphan\n\n```\n`%rune%` can only be used inside an effect (e.g. during component initialisation)\n```\n\n### effect_pending_outside_reaction\n\n```\n`$effect.pending()` can only be called inside an effect or derived\n```\n\n### effect_update_depth_exceeded\n\n```\nMaximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\n```\n\nIf an effect updates some state that it also depends on, it will re-run, potentially in a loop:\n\n```js\nlet count = $state(0);\n\n$effect(() => {\n\t// this both reads and writes `count`,\n\t// so will run in an infinite loop\n\tcount += 1;\n});\n```\n\n(Svelte intervenes before this can crash your browser tab.)\n\nThe same applies to array mutations, since these both read and write to the array:\n\n```js\nlet array = $state(['hello']);\n\n$effect(() => {\n\tarray.push('goodbye');\n});\n```\n\nNote that it's fine for an effect to re-run itself as long as it 'settles':\n\n```js\nlet array = ['a', 'b', 'c'];\n//cut\n$effect(() => {\n\t// this is okay, because sorting an already-sorted array\n\t// won't result in a mutation\n\tarray.sort();\n});\n```\n\nOften when encountering this issue, the value in question shouldn't be state (for example, if you are pushing to a `logs` array in an effect, make `logs` a normal array rather than `$state([])`). In the rare cases where you really _do_ need to write to state in an effect — [which you should avoid]($effect#When-not-to-use-$effect) — you can read the state with [untrack](svelte#untrack) to avoid adding it as a dependency.\n\n### flush_sync_in_effect\n\n```\nCannot use `flushSync` inside an effect\n```\n\nThe `flushSync()` function can be used to flush any pending effects synchronously. It cannot be used if effects are currently being flushed — in other words, you can call it after a state change but _not_ inside an effect.\n\nThis restriction only applies when using the `experimental.async` option, which will be active by default in Svelte 6.\n\n### fork_discarded\n\n```\nCannot commit a fork that was already discarded\n```\n\n### fork_timing\n\n```\nCannot create a fork inside an effect or when state changes are pending\n```\n\n### get_abort_signal_outside_reaction\n\n```\n`getAbortSignal()` can only be called inside an effect or derived\n```\n\n### hydratable_missing_but_required\n\n```\nExpected to find a hydratable with key `%key%` during hydration, but did not.\n```\n\nThis can happen if you render a hydratable on the client that was not rendered on the server, and means that it was forced to fall back to running its function blockingly during hydration. This is bad for performance, as it blocks hydration until the asynchronous work completes.\n\n```svelte\n<script>\n  import { hydratable } from 'svelte';\n\n\tif (BROWSER) {\n\t\t// bad! nothing can become interactive until this asynchronous work is done\n\t\tawait hydratable('foo', get_slow_random_number);\n\t}\n</script>\n```\n\n### hydration_failed\n\n```\nFailed to hydrate the application\n```\n\n### invalid_snippet\n\n```\nCould not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`\n```\n\n### lifecycle_legacy_only\n\n```\n`%name%(...)` cannot be used in runes mode\n```\n\n### props_invalid_value\n\n```\nCannot do `bind:%key%={undefined}` when `%key%` has a fallback value\n```\n\n### props_rest_readonly\n\n```\nRest element properties of `$props()` such as `%property%` are readonly\n```\n\n### rune_outside_svelte\n\n```\nThe `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files\n```\n\n### set_context_after_init\n\n```\n`setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression\n```\n\nThis restriction only applies when using the `experimental.async` option, which will be active by default in Svelte 6.\n\n### state_descriptors_fixed\n\n```\nProperty descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\n```\n\n### state_prototype_fixed\n\n```\nCannot set prototype of `$state` object\n```\n\n### state_unsafe_mutation\n\n```\nUpdating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\n```\n\nThis error occurs when state is updated while evaluating a `$derived`. You might encounter it while trying to 'derive' two pieces of state in one go:\n\n```svelte\n<script>\n\tlet count = $state(0);\n\n\tlet even = $state(true);\n\n\tlet odd = $derived.by(() => {\n\t\teven = count % 2 === 0;\n\t\treturn !even;\n\t});\n</script>\n\n<button onclick={() => count++}>{count}</button>\n\n<p>{count} is even: {even}</p>\n<p>{count} is odd: {odd}</p>\n```\n\nThis is forbidden because it introduces instability: if `<p>{count} is even: {even}</p>` is updated before `odd` is recalculated, `even` will be stale. In most cases the solution is to make everything derived:\n\n```js\nlet count = 0;\n//cut\nlet even = $derived(count % 2 === 0);\nlet odd = $derived(!even);\n```\n\nIf side-effects are unavoidable, use [`$effect`]($effect) instead.\n\n### svelte_boundary_reset_onerror\n\n```\nA `<svelte:boundary>` `reset` function cannot be called while an error is still being handled\n```\n\nIf a [`<svelte:boundary>`](https://svelte.dev/docs/svelte/svelte-boundary) has an `onerror` function, it must not call the provided `reset` function synchronously since the boundary is still in a broken state. Typically, `reset()` is called later, once the error has been resolved.\n\nIf it's possible to resolve the error inside the `onerror` callback, you must at least wait for the boundary to settle before calling `reset()`, for example using [`tick`](https://svelte.dev/docs/svelte/lifecycle-hooks#tick):\n\n```svelte\n<svelte:boundary onerror={async (error, reset) => {\n\tfixTheError();\n\tawait tick();\n\treset();\n}}>\n\n</svelte:boundary>\n```\n\n\n## Server errors\n\n<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n### async_local_storage_unavailable\n\n```\nThe node API `AsyncLocalStorage` is not available, but is required to use async server rendering.\n```\n\nSome platforms require configuration flags to enable this API. Consult your platform's documentation.\n\n### await_invalid\n\n```\nEncountered asynchronous work while rendering synchronously.\n```\n\nYou (or the framework you're using) called [`render(...)`](svelte-server#render) with a component containing an `await` expression. Either `await` the result of `render` or wrap the `await` (or the component containing it) in a [`<svelte:boundary>`](svelte-boundary) with a `pending` snippet.\n\n### dynamic_element_invalid_tag\n\n```\n`<svelte:element this=\"%tag%\">` is not a valid element name — the element will not be rendered\n```\n\nThe value passed to the `this` prop of `<svelte:element>` must be a valid HTML element, SVG element, MathML element, or custom element name. A value containing invalid characters (such as whitespace or special characters) was provided, which could be a security risk. Ensure only valid tag names are passed.\n\n### html_deprecated\n\n```\nThe `html` property of server render results has been deprecated. Use `body` instead.\n```\n\n### hydratable_clobbering\n\n```\nAttempted to set `hydratable` with key `%key%` twice with different values.\n\n%stack%\n```\n\nThis error occurs when using `hydratable` multiple times with the same key. To avoid this, you can:\n- Ensure all invocations with the same key result in the same value\n- Update the keys to make both instances unique\n\n```svelte\n<script>\n  import { hydratable } from 'svelte';\n\n  // which one should \"win\" and be serialized in the rendered response?\n  const one = hydratable('not-unique', () => 1);\n  const two = hydratable('not-unique', () => 2);\n</script>\n```\n\n### hydratable_serialization_failed\n\n```\nFailed to serialize `hydratable` data for key `%key%`.\n\n`hydratable` can serialize anything [`uneval` from `devalue`](https://npmjs.com/package/uneval) can, plus Promises.\n\nCause:\n%stack%\n```\n\n### invalid_csp\n\n```\n`csp.nonce` was set while `csp.hash` was `true`. These options cannot be used simultaneously.\n```\n\n### lifecycle_function_unavailable\n\n```\n`%name%(...)` is not available on the server\n```\n\nCertain methods such as `mount` cannot be invoked while running in a server context. Avoid calling them eagerly, i.e. not during render.\n\n### server_context_required\n\n```\nCould not resolve `render` context.\n```\n\nCertain functions such as `hydratable` cannot be invoked outside of a `render(...)` call, such as at the top level of a module.\n\n\n## Shared errors\n\n<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n### experimental_async_required\n\n```\nCannot use `%name%(...)` unless the `experimental.async` compiler option is `true`\n```\n\n### invalid_default_snippet\n\n```\nCannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead\n```\n\nThis error would be thrown in a setup like this:\n\n```svelte\n<!file: Parent.svelte>\n<List {items} let:entry>\n    <span>{entry}</span>\n</List>\n```\n\n```svelte\n<!file: List.svelte>\n<script>\n    let { items, children } = $props();\n</script>\n\n<ul>\n    {#each items as item}\n        <li>{@render children(item)}</li>\n    {/each}\n</ul>\n```\n\nHere, `List.svelte` is using `{@render children(item)` which means it expects `Parent.svelte` to use snippets. Instead, `Parent.svelte` uses the deprecated `let:` directive. This combination of APIs is incompatible, hence the error.\n\n### invalid_snippet_arguments\n\n```\nA snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}`\n```\n\n### lifecycle_outside_component\n\n```\n`%name%(...)` can only be used during component initialisation\n```\n\nCertain lifecycle methods can only be used during component initialisation. To fix this, make sure you're invoking the method inside the _top level of the instance script_ of your component.\n\n```svelte\n<script>\n    import { onMount } from 'svelte';\n\n    function handleClick() {\n        // This is wrong\n        onMount(() => {})\n    }\n\n    // This is correct\n    onMount(() => {})\n</script>\n\n<button onclick={handleClick}>click me</button>\n```\n\n### missing_context\n\n```\nContext was not set in a parent component\n```\n\nThe [`createContext()`](svelte#createContext) utility returns a `[get, set]` pair of functions. `get` will throw an error if `set` was not used to set the context in a parent component.\n\n### snippet_without_render_tag\n\n```\nAttempted to render a snippet without a `{@render}` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change `{snippet}` to `{@render snippet()}`.\n```\n\nA component throwing this error will look something like this (`children` is not being rendered):\n\n```svelte\n<script>\n    let { children } = $props();\n</script>\n\n{children}\n```\n\n...or like this (a parent component is passing a snippet where a non-snippet value is expected):\n\n```svelte\n<!file: Parent.svelte>\n<ChildComponent>\n  {#snippet label()}\n    <span>Hi!</span>\n  {/snippet}\n</ChildComponent>\n```\n\n```svelte\n<!file: Child.svelte>\n<script>\n  let { label } = $props();\n</script>\n\n<!-- This component doesn't expect a snippet, but the parent provided one -->\n<p>{label}</p>\n```\n\n### store_invalid_shape\n\n```\n`%name%` is not a store with a `subscribe` method\n```\n\n### svelte_element_invalid_this_value\n\n```\nThe `this` prop on `<svelte:element>` must be a string, if defined\n```","size_bytes":14974,"metadata":{"title":"Runtime errors"},"created_at":"2025-07-18T15:47:39.052Z","updated_at":"2026-02-20T02:00:04.586Z"},{"path":"apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-warnings.md","title":"Runtime warnings","filename":"30-runtime-warnings.md","content":"## Client warnings\n\n<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n### assignment_value_stale\n\n```\nAssignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour.\n```\n\nGiven a case like this...\n\n```svelte\n<script>\n\tlet object = $state({ array: null });\n\n\tfunction add() {\n\t\t(object.array ??= []).push(object.array.length);\n\t}\n</script>\n\n<button onclick={add}>add</button>\n<p>items: {JSON.stringify(object.items)}</p>\n```\n\n...the array being pushed to when the button is first clicked is the `[]` on the right-hand side of the assignment, but the resulting value of `object.array` is an empty state proxy. As a result, the pushed value will be discarded.\n\nYou can fix this by separating it into two statements:\n\n```js\nlet object = { array: [0] };\n//cut\nfunction add() {\n\tobject.array ??= [];\n\tobject.array.push(object.array.length);\n}\n```\n\n### await_reactivity_loss\n\n```\nDetected reactivity loss when reading `%name%`. This happens when state is read in an async function after an earlier `await`\n```\n\nSvelte's signal-based reactivity works by tracking which bits of state are read when a template or `$derived(...)` expression executes. If an expression contains an `await`, Svelte transforms it such that any state _after_ the `await` is also tracked — in other words, in a case like this...\n\n```js\nlet a = Promise.resolve(1);\nlet b = 2;\n//cut\nlet total = $derived(await a + b);\n```\n\n...both `a` and `b` are tracked, even though `b` is only read once `a` has resolved, after the initial execution.\n\nThis does _not_ apply to an `await` that is not 'visible' inside the expression. In a case like this...\n\n```js\nlet a = Promise.resolve(1);\nlet b = 2;\n//cut\nasync function sum() {\n\treturn await a + b;\n}\n\nlet total = $derived(await sum());\n```\n\n...`total` will depend on `a` (which is read immediately) but not `b` (which is not). The solution is to pass the values into the function:\n\n```js\nlet a = Promise.resolve(1);\nlet b = 2;\n//cut\n/**\n * @param {Promise<number>} a\n * @param {number} b\n */\nasync function sum(a, b) {\n\treturn await a + b;\n}\n\nlet total = $derived(await sum(a, b));\n```\n\n### await_waterfall\n\n```\nAn async derived, `%name%` (%location%) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app\n```\n\nIn a case like this...\n\n```js\nasync function one() { return 1 }\nasync function two() { return 2 }\n//cut\nlet a = $derived(await one());\nlet b = $derived(await two());\n```\n\n...the second `$derived` will not be created until the first one has resolved. Since `await two()` does not depend on the value of `a`, this delay, often described as a 'waterfall', is unnecessary.\n\n(Note that if the values of `await one()` and `await two()` subsequently change, they can do so concurrently — the waterfall only occurs when the deriveds are first created.)\n\nYou can solve this by creating the promises first and _then_ awaiting them:\n\n```js\nasync function one() { return 1 }\nasync function two() { return 2 }\n//cut\nlet aPromise = $derived(one());\nlet bPromise = $derived(two());\n\nlet a = $derived(await aPromise);\nlet b = $derived(await bPromise);\n```\n\n### binding_property_non_reactive\n\n```\n`%binding%` is binding to a non-reactive property\n```\n\n```\n`%binding%` (%location%) is binding to a non-reactive property\n```\n\n### console_log_state\n\n```\nYour `console.%method%` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead\n```\n\nWhen logging a [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), browser devtools will log the proxy itself rather than the value it represents. In the case of Svelte, the 'target' of a `$state` proxy might not resemble its current value, which can be confusing.\n\nThe easiest way to log a value as it changes over time is to use the [`$inspect`](/docs/svelte/$inspect) rune. Alternatively, to log things on a one-off basis (for example, inside an event handler) you can use [`$state.snapshot`](/docs/svelte/$state#$state.snapshot) to take a snapshot of the current value.\n\n### event_handler_invalid\n\n```\n%handler% should be a function. Did you mean to %suggestion%?\n```\n\n### hydratable_missing_but_expected\n\n```\nExpected to find a hydratable with key `%key%` during hydration, but did not.\n```\n\nThis can happen if you render a hydratable on the client that was not rendered on the server, and means that it was forced to fall back to running its function blockingly during hydration. This is bad for performance, as it blocks hydration until the asynchronous work completes.\n\n```svelte\n<script>\n  import { hydratable } from 'svelte';\n\n\tif (BROWSER) {\n\t\t// bad! nothing can become interactive until this asynchronous work is done\n\t\tawait hydratable('foo', get_slow_random_number);\n\t}\n</script>\n```\n\n### hydration_attribute_changed\n\n```\nThe `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value\n```\n\nCertain attributes like `src` on an `<img>` element will not be repaired during hydration, i.e. the server value will be kept. That's because updating these attributes can cause the image to be refetched (or in the case of an `<iframe>`, for the frame to be reloaded), even if they resolve to the same resource.\n\nTo fix this, either silence the warning with a [`svelte-ignore`](basic-markup#Comments) comment, or ensure that the value stays the same between server and client. If you really need the value to change on hydration, you can force an update like this:\n\n```svelte\n<script>\n\tlet { src } = $props();\n\n\tif (typeof window !== 'undefined') {\n\t\t// stash the value...\n\t\tconst initial = src;\n\n\t\t// unset it...\n\t\tsrc = undefined;\n\n\t\t$effect(() => {\n\t\t\t// ...and reset after we've mounted\n\t\t\tsrc = initial;\n\t\t});\n\t}\n</script>\n\n<img {src} />\n```\n\n### hydration_html_changed\n\n```\nThe value of an `{@html ...}` block changed between server and client renders. The client value will be ignored in favour of the server value\n```\n\n```\nThe value of an `{@html ...}` block %location% changed between server and client renders. The client value will be ignored in favour of the server value\n```\n\nIf the `{@html ...}` value changes between the server and the client, it will not be repaired during hydration, i.e. the server value will be kept. That's because change detection during hydration is expensive and usually unnecessary.\n\nTo fix this, either silence the warning with a [`svelte-ignore`](basic-markup#Comments) comment, or ensure that the value stays the same between server and client. If you really need the value to change on hydration, you can force an update like this:\n\n```svelte\n<script>\n\tlet { markup } = $props();\n\n\tif (typeof window !== 'undefined') {\n\t\t// stash the value...\n\t\tconst initial = markup;\n\n\t\t// unset it...\n\t\tmarkup = undefined;\n\n\t\t$effect(() => {\n\t\t\t// ...and reset after we've mounted\n\t\t\tmarkup = initial;\n\t\t});\n\t}\n</script>\n\n{@html markup}\n```\n\n### hydration_mismatch\n\n```\nHydration failed because the initial UI does not match what was rendered on the server\n```\n\n```\nHydration failed because the initial UI does not match what was rendered on the server. The error occurred near %location%\n```\n\nThis warning is thrown when Svelte encounters an error while hydrating the HTML from the server. During hydration, Svelte walks the DOM, expecting a certain structure. If that structure is different (for example because the HTML was repaired by the DOM because of invalid HTML), then Svelte will run into issues, resulting in this warning.\n\nDuring development, this error is often preceded by a `console.error` detailing the offending HTML, which needs fixing.\n\n### invalid_raw_snippet_render\n\n```\nThe `render` function passed to `createRawSnippet` should return HTML for a single element\n```\n\n### legacy_recursive_reactive_block\n\n```\nDetected a migrated `$:` reactive block in `%filename%` that both accesses and updates the same reactive value. This may cause recursive updates when converted to an `$effect`.\n```\n\n### lifecycle_double_unmount\n\n```\nTried to unmount a component that was not mounted\n```\n\n### ownership_invalid_binding\n\n```\n%parent% passed property `%prop%` to %child% with `bind:`, but its parent component %owner% did not declare `%prop%` as a binding. Consider creating a binding between %owner% and %parent% (e.g. `bind:%prop%={...}` instead of `%prop%={...}`)\n```\n\nConsider three components `GrandParent`, `Parent` and `Child`. If you do `<GrandParent bind:value>`, inside `GrandParent` pass on the variable via `<Parent {value} />` (note the missing `bind:`) and then do `<Child bind:value>` inside `Parent`, this warning is thrown.\n\nTo fix it, `bind:` to the value instead of just passing a property (i.e. in this example do `<Parent bind:value />`).\n\n### ownership_invalid_mutation\n\n```\nMutating unbound props (`%name%`, at %location%) is strongly discouraged. Consider using `bind:%prop%={...}` in %parent% (or using a callback) instead\n```\n\nConsider the following code:\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Child from './Child.svelte';\n\tlet person = $state({ name: 'Florida', surname: 'Man' });\n</script>\n\n<Child {person} />\n```\n\n```svelte\n<!file: Child.svelte>\n<script>\n\tlet { person } = $props();\n</script>\n\n<input bind:value={person.name}>\n<input bind:value={person.surname}>\n```\n\n`Child` is mutating `person` which is owned by `App` without being explicitly \"allowed\" to do so. This is strongly discouraged since it can create code that is hard to reason about at scale (\"who mutated this value?\"), hence the warning.\n\nTo fix it, either create callback props to communicate changes, or mark `person` as [`$bindable`]($bindable).\n\n### select_multiple_invalid_value\n\n```\nThe `value` property of a `<select multiple>` element should be an array, but it received a non-array value. The selection will be kept as is.\n```\n\nWhen using `<select multiple value={...}>`, Svelte will mark all selected `<option>` elements as selected by iterating over the array passed to `value`. If `value` is not an array, Svelte will emit this warning and keep the selected options as they are.\n\nTo silence the warning, ensure that `value`:\n\n- is an array for an explicit selection\n- is `null` or `undefined` to keep the selection as is\n\n### state_proxy_equality_mismatch\n\n```\nReactive `$state(...)` proxies and the values they proxy have different identities. Because of this, comparisons with `%operator%` will produce unexpected results\n```\n\n`$state(...)` creates a [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) of the value it is passed. The proxy and the value have different identities, meaning equality checks will always return `false`:\n\n```svelte\n<script>\n\tlet value = { foo: 'bar' };\n\tlet proxy = $state(value);\n\n\tvalue === proxy; // always false\n</script>\n```\n\nTo resolve this, ensure you're comparing values where both values were created with `$state(...)`, or neither were. Note that `$state.raw(...)` will _not_ create a state proxy.\n\n### state_proxy_unmount\n\n```\nTried to unmount a state proxy, rather than a component\n```\n\n`unmount` was called with a state proxy:\n\n```js\nimport { mount, unmount } from 'svelte';\nimport Component from './Component.svelte';\nlet target = document.body;\n//cut\nlet component = $state(mount(Component, { target }));\n\n// later...\nunmount(component);\n```\n\nAvoid using `$state` here. If `component` _does_ need to be reactive for some reason, use `$state.raw` instead.\n\n### svelte_boundary_reset_noop\n\n```\nA `<svelte:boundary>` `reset` function only resets the boundary the first time it is called\n```\n\nWhen an error occurs while rendering the contents of a [`<svelte:boundary>`](https://svelte.dev/docs/svelte/svelte-boundary), the `onerror` handler is called with the error plus a `reset` function that attempts to re-render the contents.\n\nThis `reset` function should only be called once. After that, it has no effect — in a case like this, where a reference to `reset` is stored outside the boundary, clicking the button while `<Contents />` is rendered will _not_ cause the contents to be rendered again.\n\n```svelte\n<script>\n\tlet reset;\n</script>\n\n<button onclick={reset}>reset</button>\n\n<svelte:boundary onerror={(e, r) => (reset = r)}>\n\t<!-- contents -->\n\n\t{#snippet failed(e)}\n\t\t<p>oops! {e.message}</p>\n\t{/snippet}\n</svelte:boundary>\n```\n\n### transition_slide_display\n\n```\nThe `slide` transition does not work correctly for elements with `display: %value%`\n```\n\nThe [slide](/docs/svelte/svelte-transition#slide) transition works by animating the `height` of the element, which requires a `display` style like `block`, `flex` or `grid`. It does not work for:\n\n- `display: inline` (which is the default for elements like `<span>`), and its variants like `inline-block`, `inline-flex` and `inline-grid`\n- `display: table` and `table-[name]`, which are the defaults for elements like `<table>` and `<tr>`\n- `display: contents`\n\n\n## Shared warnings\n\n<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n### dynamic_void_element_content\n\n```\n`<svelte:element this=\"%tag%\">` is a void element — it cannot have content\n```\n\nElements such as `<input>` cannot have content, any children passed to these elements will be ignored.\n\n### state_snapshot_uncloneable\n\n```\nValue cannot be cloned with `$state.snapshot` — the original value was returned\n```\n\n```\nThe following properties cannot be cloned with `$state.snapshot` — the return value contains the originals:\n\n%properties%\n```\n\n`$state.snapshot` tries to clone the given value in order to return a reference that no longer changes. Certain objects may not be cloneable, in which case the original value is returned. In the following example, `property` is cloned, but `window` is not, because DOM elements are uncloneable:\n\n```js\nconst object = $state({ property: 'this is cloneable', window })\nconst snapshot = $state.snapshot(object);\n```","size_bytes":14155,"metadata":{"title":"Runtime warnings"},"created_at":"2025-07-18T15:47:39.054Z","updated_at":"2025-11-26T14:00:04.230Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/00-legacy-overview.md","title":"Overview","filename":"00-legacy-overview.md","content":"Svelte 5 introduced some significant changes to Svelte's API, including [runes](what-are-runes), [snippets](snippet) and event attributes. As a result, some Svelte 3/4 features are deprecated (though supported for now, unless otherwise specified) and will eventually be removed. We recommend that you incrementally [migrate your existing code](v5-migration-guide).\n\nThe following pages document these features for\n\n- people still using Svelte 3/4\n- people using Svelte 5, but with components that haven't yet been migrated\n\nSince Svelte 3/4 syntax still works in Svelte 5, we will distinguish between _legacy mode_ and _runes mode_. Once a component is in runes mode (which you can opt into by using runes, or by explicitly setting the `runes: true` compiler option), legacy mode features are no longer available.\n\nIf you're exclusively interested in the Svelte 3/4 syntax, you can browse its documentation at [v4.svelte.dev](https://v4.svelte.dev).","size_bytes":975,"metadata":{"title":"Overview"},"created_at":"2025-07-18T15:47:39.058Z","updated_at":"2025-07-18T15:47:40.372Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/01-legacy-let.md","title":"Reactive let/var declarations","filename":"01-legacy-let.md","content":"In runes mode, reactive state is explicitly declared with the [`$state` rune]($state).\n\nIn legacy mode, variables declared at the top level of a component are automatically considered _reactive_. Reassigning or mutating these variables (`count += 1` or `object.x = y`) will cause the UI to update.\n\n```svelte\n<script>\n\tlet count = 0;\n</script>\n\n<button on:click={() => count += 1}>\n\tclicks: {count}\n</button>\n```\n\nBecause Svelte's legacy mode reactivity is based on _assignments_, using array methods like `.push()` and `.splice()` won't automatically trigger updates. A subsequent assignment is required to 'tell' the compiler to update the UI:\n\n```svelte\n<script>\n\tlet numbers = [1, 2, 3, 4];\n\n\tfunction addNumber() {\n\t\t// this method call does not trigger an update\n\t\tnumbers.push(numbers.length + 1);\n\n\t\t// this assignment will update anything\n\t\t// that depends on `numbers`\n\t\tnumbers = numbers;\n\t}\n</script>\n```","size_bytes":963,"metadata":{"title":"Reactive let/var declarations"},"created_at":"2025-07-18T15:47:39.059Z","updated_at":"2025-07-18T15:47:40.374Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/02-legacy-reactive-assignments.md","title":"Reactive $: statements","filename":"02-legacy-reactive-assignments.md","content":"In runes mode, reactions to state updates are handled with the [`$derived`]($derived) and [`$effect`]($effect) runes.\n\nIn legacy mode, any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with a `$:` [label](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). These statements run after other code in the `<script>` and before the component markup is rendered, then whenever the values that they depend on change.\n\n```svelte\n<script>\n\tlet a = 1;\n\tlet b = 2;\n\n\t// this is a 'reactive statement', and it will re-run\n\t// when `a`, `b` or `sum` change\n\t$: console.log(`${a} + ${b} = ${sum}`);\n\n\t// this is a 'reactive assignment' — `sum` will be\n\t// recalculated when `a` or `b` change. It is\n\t// not necessary to declare `sum` separately\n\t$: sum = a + b;\n</script>\n```\n\nStatements are ordered _topologically_ by their dependencies and their assignments: since the `console.log` statement depends on `sum`, `sum` is calculated first even though it appears later in the source.\n\nMultiple statements can be combined by putting them in a block:\n\n```js\n// @noErrors\n$: {\n\t// recalculate `total` when `items` changes\n\ttotal = 0;\n\n\tfor (const item of items) {\n\t\ttotal += item.value;\n\t}\n}\n```\n\nThe left-hand side of a reactive assignments can be an identifier, or it can be a destructuring assignment:\n\n```js\n// @noErrors\n$: ({ larry, moe, curly } = stooges);\n```\n\n## Understanding dependencies\n\nThe dependencies of a `$:` statement are determined at compile time — they are whichever variables are referenced (but not assigned to) inside the statement.\n\nIn other words, a statement like this will _not_ re-run when `count` changes, because the compiler cannot 'see' the dependency:\n\n```js\n// @noErrors\nlet count = 0;\nlet double = () => count * 2;\n\n$: doubled = double();\n```\n\nSimilarly, topological ordering will fail if dependencies are referenced indirectly: `z` will never update, because `y` is not considered 'dirty' when the update occurs. Moving `$: z = y` below `$: setY(x)` will fix it:\n\n```svelte\n<script>\n\tlet x = 0;\n\tlet y = 0;\n\n\t$: z = y;\n\t$: setY(x);\n\n\tfunction setY(value) {\n\t\ty = value;\n\t}\n</script>\n```\n\n## Browser-only code\n\nReactive statements run during server-side rendering as well as in the browser. This means that any code that should only run in the browser must be wrapped in an `if` block:\n\n```js\n// @noErrors\n$: if (browser) {\n\tdocument.title = title;\n}\n```","size_bytes":2501,"metadata":{"title":"Reactive $: statements"},"created_at":"2025-07-18T15:47:39.061Z","updated_at":"2025-07-18T15:47:40.376Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/03-legacy-export-let.md","title":"export let","filename":"03-legacy-export-let.md","content":"In runes mode, [component props](basic-markup#Component-props) are declared with the [`$props`]($props) rune, allowing parent components to pass in data.\n\nIn legacy mode, props are marked with the `export` keyword, and can have a default value:\n\n```svelte\n<script>\n\texport let foo;\n\texport let bar = 'default value';\n\n\t// Values that are passed in as props\n\t// are immediately available\n\tconsole.log({ foo });\n</script>\n```\n\nThe default value is used if it would otherwise be `undefined` when the component is created.\n\n\nProps without default values are considered _required_, and Svelte will print a warning during development if no value is provided, which you can squelch by specifying `undefined` as the default value:\n\n```js\nexport let foo= undefined;\n```\n\n## Component exports\n\nAn exported `const`, `class` or `function` declaration is _not_ considered a prop — instead, it becomes part of the component's API:\n\n```svelte\n<!file: Greeter.svelte>\n<script>\n\texport function greet(name) {\n\t\talert(`hello ${name}!`);\n\t}\n</script>\n```\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Greeter from './Greeter.svelte';\n\n\tlet greeter;\n</script>\n\n<Greeter bind:this={greeter} />\n\n<button on:click={() => greeter.greet('world')}>\n\tgreet\n</button>\n```\n\n## Renaming props\n\nThe `export` keyword can appear separately from the declaration. This is useful for renaming props, for example in the case of a reserved word:\n\n```svelte\n<!file: App.svelte>\n<script>\n\t/** @type {string} */\n\tlet className;\n\n\t// creates a `class` property, even\n\t// though it is a reserved word\n\texport { className as class };\n</script>\n```","size_bytes":1635,"metadata":{"title":"export let"},"created_at":"2025-07-18T15:47:39.062Z","updated_at":"2025-07-18T15:47:40.378Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/04-legacy-$$props-and-$$restProps.md","title":"$$props and $$restProps","filename":"04-legacy-$$props-and-$$restProps.md","content":"In runes mode, getting an object containing all the props that were passed in is easy, using the [`$props`]($props) rune.\n\nIn legacy mode, we use `$$props` and `$$restProps`:\n\n- `$$props` contains all the props that were passed in, including ones that are not individually declared with the `export` keyword\n- `$$restProps` contains all the props that were passed in _except_ the ones that were individually declared\n\nFor example, a `<Button>` component might need to pass along all its props to its own `<button>` element, except the `variant` prop:\n\n```svelte\n<script>\n\texport let variant;\n</script>\n\n<button {...$$restProps} class=\"variant-{variant} {$$props.class ?? ''}\">\n\tclick me\n</button>\n\n<style>\n\t.variant-danger {\n\t\tbackground: red;\n\t}\n</style>\n```\n\nIn Svelte 3/4 using `$$props` and `$$restProps` creates a modest performance penalty, so they should only be used when needed.","size_bytes":928,"metadata":{"title":"$$props and $$restProps"},"created_at":"2025-07-18T15:47:39.063Z","updated_at":"2025-07-18T15:47:40.380Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/10-legacy-on.md","title":"on:","filename":"10-legacy-on.md","content":"In runes mode, event handlers are just like any other attribute or prop.\n\nIn legacy mode, we use the `on:` directive:\n\n```svelte\n<!file: App.svelte>\n<script>\n\tlet count = 0;\n\n\t/** @param {MouseEvent} event */\n\tfunction handleClick(event) {\n\t\tcount += 1;\n\t}\n</script>\n\n<button on:click={handleClick}>\n\tcount: {count}\n</button>\n```\n\nHandlers can be declared inline with no performance penalty:\n\n```svelte\n<button on:click={() => (count += 1)}>\n\tcount: {count}\n</button>\n```\n\nAdd _modifiers_ to element event handlers with the `|` character.\n\n```svelte\n<form on:submit|preventDefault={handleSubmit}>\n\t<!-- the `submit` event's default is prevented,\n\t     so the page won't reload -->\n</form>\n```\n\nThe following modifiers are available:\n\n- `preventDefault` — calls `event.preventDefault()` before running the handler\n- `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element\n- `stopImmediatePropagation` — calls `event.stopImmediatePropagation()`, preventing other listeners of the same event from being fired.\n- `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)\n- `nonpassive` — explicitly set `passive: false`\n- `capture` — fires the handler during the _capture_ phase instead of the _bubbling_ phase\n- `once` — remove the handler after the first time it runs\n- `self` — only trigger handler if `event.target` is the element itself\n- `trusted` — only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action.\n\nModifiers can be chained together, e.g. `on:click|once|capture={...}`.\n\nIf the `on:` directive is used without a value, the component will _forward_ the event, meaning that a consumer of the component can listen for it.\n\n```svelte\n<button on:click>\n\tThe component itself will emit the click event\n</button>\n```\n\nIt's possible to have multiple event listeners for the same event:\n\n```svelte\n<!file: App.svelte>\n<script>\n\tlet count = 0;\n\n\tfunction increment() {\n\t\tcount += 1;\n\t}\n\n\t/** @param {MouseEvent} event */\n\tfunction log(event) {\n\t\tconsole.log(event);\n\t}\n</script>\n\n<button on:click={increment} on:click={log}>\n\tclicks: {count}\n</button>\n```\n\n## Component events\n\nComponents can dispatch events by creating a _dispatcher_ when they are initialised:\n\n```svelte\n<!file: Stepper.svelte -->\n<script>\n\timport { createEventDispatcher } from 'svelte';\n\tconst dispatch = createEventDispatcher();\n</script>\n\n<button on:click={() => dispatch('decrement')}>decrement</button>\n<button on:click={() => dispatch('increment')}>increment</button>\n```\n\n`dispatch` creates a [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). If a second argument is provided, it becomes the `detail` property of the event object.\n\nA consumer of this component can listen for the dispatched events:\n\n```svelte\n<script>\n\timport Stepper from './Stepper.svelte';\n\n\tlet n = 0;\n</script>\n\n<Stepper\n\ton:decrement={() => n -= 1}\n\ton:increment={() => n += 1}\n/>\n\n<p>n: {n}</p>\n```\n\nComponent events do not bubble — a parent component can only listen for events on its immediate children.\n\nOther than `once`, modifiers are not valid on component event handlers.\n\n> If you're planning an eventual migration to Svelte 5, use callback props instead. This will make upgrading easier as `createEventDispatcher` is deprecated:\n>\n> ```svelte\n> <!--- file: Stepper.svelte --->\n> <script>\n> \texport let decrement;\n> \texport let increment;\n> </script>\n>\n> <button on:click={decrement}>decrement</button>\n> <button on:click={increment}>increment</button>\n> ```","size_bytes":3645,"metadata":{"title":"on:"},"created_at":"2025-07-18T15:47:39.065Z","updated_at":"2025-11-26T14:00:04.231Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/20-legacy-slots.md","title":"<slot>","filename":"20-legacy-slots.md","content":"In Svelte 5, content can be passed to components in the form of [snippets](snippet) and rendered using [render tags](@render).\n\nIn legacy mode, content inside component tags is considered _slotted content_, which can be rendered by the component using a `<slot>` element:\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Modal from './Modal.svelte';\n</script>\n\n<Modal>This is some slotted content</Modal>\n```\n\n```svelte\n<!file: Modal.svelte>\n<div class=\"modal\">\n\t<slot></slot>\n</div>\n```\n\n\n## Named slots\n\nA component can have _named_ slots in addition to the default slot. On the parent side, add a `slot=\"...\"` attribute to an element, component or [`<svelte:fragment>`](legacy-svelte-fragment) directly inside the component tags.\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Modal from './Modal.svelte';\n\n\tlet open = true;\n</script>\n\n{#if open}\n\t<Modal>\n\t\tThis is some slotted content\n\n\t\t<div slot=\"buttons\">\n\t\t\t<button on:click={() => open = false}>\n\t\t\t\tclose\n\t\t\t</button>\n\t\t</div>\n\t</Modal>\n{/if}\n```\n\nOn the child side, add a corresponding `<slot name=\"...\">` element:\n\n```svelte\n<!file: Modal.svelte>\n<div class=\"modal\">\n\t<slot></slot>\n\t<hr>\n\t<slot name=\"buttons\"></slot>\n</div>\n```\n\n## Fallback content\n\nIf no slotted content is provided, a component can define fallback content by putting it inside the `<slot>` element:\n\n```svelte\n<slot>\n\tThis will be rendered if no slotted content is provided\n</slot>\n```\n\n## Passing data to slotted content\n\nSlots can be rendered zero or more times and can pass values _back_ to the parent using props. The parent exposes the values to the slot template using the `let:` directive.\n\n```svelte\n<!file: FancyList.svelte>\n<ul>\n\t{#each items as data}\n\t\t<li class=\"fancy\">\n\t\t\t<!-- 'item' here... -->\n\t\t\t<slot item={process(data)} />\n\t\t</li>\n\t{/each}\n</ul>\n```\n\n```svelte\n<!file: App.svelte>\n<!-- ...corresponds to 'item' here: -->\n<FancyList {items} let:item={processed}>\n\t<div>{processed.text}</div>\n</FancyList>\n```\n\nThe usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `<slot {item}>` is equivalent to `<slot item={item}>`.\n\nNamed slots can also expose values. The `let:` directive goes on the element with the `slot` attribute.\n\n```svelte\n<!file: FancyList.svelte>\n<ul>\n\t{#each items as item}\n\t\t<li class=\"fancy\">\n\t\t\t<slot name=\"item\" item={process(data)} />\n\t\t</li>\n\t{/each}\n</ul>\n\n<slot name=\"footer\" />\n```\n\n```svelte\n<!file: App.svelte>\n<FancyList {items}>\n\t<div slot=\"item\" let:item>{item.text}</div>\n\t<p slot=\"footer\">Copyright (c) 2019 Svelte Industries</p>\n</FancyList>\n```","size_bytes":2586,"metadata":{"title":"<slot>"},"created_at":"2025-07-18T15:47:39.067Z","updated_at":"2025-07-18T15:47:40.385Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/21-legacy-$$slots.md","title":"$$slots","filename":"21-legacy-$$slots.md","content":"In runes mode, we know which [snippets](snippet) were provided to a component, as they're just normal props.\n\nIn legacy mode, the way to know if content was provided for a given slot is with the `$$slots` object, whose keys are the names of the slots passed into the component by the parent.\n\n```svelte\n<!file: Card.svelte>\n<div>\n\t<slot name=\"title\" />\n\t{#if $$slots.description}\n\t\t<!-- This <hr> and slot will render only if `slot=\"description\"` is provided. -->\n\t\t<hr />\n\t\t<slot name=\"description\" />\n\t{/if}\n</div>\n```\n\n```svelte\n<!file: App.svelte>\n<Card>\n\t<h1 slot=\"title\">Blog Post Title</h1>\n\t<!-- No slot named \"description\" was provided so the optional slot will not be rendered. -->\n</Card>\n```","size_bytes":728,"metadata":{"title":"$$slots"},"created_at":"2025-07-18T15:47:39.072Z","updated_at":"2025-07-18T15:47:40.388Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/22-legacy-svelte-fragment.md","title":"<svelte:fragment>","filename":"22-legacy-svelte-fragment.md","content":"The `<svelte:fragment>` element allows you to place content in a [named slot](legacy-slots) without wrapping it in a container DOM element. This keeps the flow layout of your document intact.\n\n```svelte\n<!file: Widget.svelte>\n<div>\n\t<slot name=\"header\">No header was provided</slot>\n\t<p>Some content between header and footer</p>\n\t<slot name=\"footer\" />\n</div>\n```\n\n```svelte\n<!file: App.svelte>\n<script>\n\timport Widget from './Widget.svelte';\n</script>\n\n<Widget>\n\t<h1 slot=\"header\">Hello</h1>\n\t<svelte:fragment slot=\"footer\">\n\t\t<p>All rights reserved.</p>\n\t\t<p>Copyright (c) 2019 Svelte Industries</p>\n\t</svelte:fragment>\n</Widget>\n```\n\n> In Svelte 5+, this concept is obsolete, as snippets don't create a wrapping element","size_bytes":758,"metadata":{"title":"<svelte:fragment>"},"created_at":"2025-07-18T15:47:39.074Z","updated_at":"2025-07-18T15:47:40.391Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/30-legacy-svelte-component.md","title":"<svelte:component>","filename":"30-legacy-svelte-component.md","content":"In runes mode, `<MyComponent>` will re-render if the value of `MyComponent` changes. See the [Svelte 5 migration guide](/docs/svelte/v5-migration-guide#svelte:component-is-no-longer-necessary) for an example.\n\nIn legacy mode, it won't — we must use `<svelte:component>`, which destroys and recreates the component instance when the value of its `this` expression changes:\n\n```svelte\n<svelte:component this={MyComponent} />\n```\n\nIf `this` is falsy, no component is rendered.","size_bytes":511,"metadata":{"title":"<svelte:component>"},"created_at":"2025-07-18T15:47:39.075Z","updated_at":"2025-07-18T15:47:40.394Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/31-legacy-svelte-self.md","title":"<svelte:self>","filename":"31-legacy-svelte-self.md","content":"The `<svelte:self>` element allows a component to include itself, recursively.\n\nIt cannot appear at the top level of your markup; it must be inside an if or each block or passed to a component's slot to prevent an infinite loop.\n\n```svelte\n<script>\n\texport let count;\n</script>\n\n{#if count > 0}\n\t<p>counting down... {count}</p>\n\t<svelte:self count={count - 1} />\n{:else}\n\t<p>lift-off!</p>\n{/if}\n```\n\n> This concept is obsolete, as components can import themselves:\n> ```svelte\n> <!--- file: App.svelte --->\n> <script>\n> \timport Self from './App.svelte'\n> \texport let count;\n> </script>\n>\n> {#if count > 0}\n> \t<p>counting down... {count}</p>\n> \t<Self count={count - 1} />\n> {:else}\n> \t<p>lift-off!</p>\n> {/if}\n> ```","size_bytes":745,"metadata":{"title":"<svelte:self>"},"created_at":"2025-07-18T15:47:39.076Z","updated_at":"2025-07-18T15:47:40.396Z"},{"path":"apps/svelte.dev/content/docs/svelte/99-legacy/40-legacy-component-api.md","title":"Imperative component API","filename":"40-legacy-component-api.md","content":"In Svelte 3 and 4, the API for interacting with a component is different than in Svelte 5. Note that this page does _not_ apply to legacy mode components in a Svelte 5 application.\n\n## Creating a component\n\n```ts\n// @noErrors\nconst component = new Component(options);\n```\n\nA client-side component — that is, a component compiled with `generate: 'dom'` (or the `generate` option left unspecified) is a JavaScript class.\n\n```ts\n// @noErrors\nimport App from './App.svelte';\n\nconst app = new App({\n\ttarget: document.body,\n\tprops: {\n\t\t// assuming App.svelte contains something like\n\t\t// `export let answer`:\n\t\tanswer: 42\n\t}\n});\n```\n\nThe following initialisation options can be provided:\n\n| option    | default     | description                                                                                          |\n| --------- | ----------- | ---------------------------------------------------------------------------------------------------- |\n| `target`  | **none**    | An `HTMLElement` or `ShadowRoot` to render to. This option is required                               |\n| `anchor`  | `null`      | A child of `target` to render the component immediately before                                       |\n| `props`   | `{}`        | An object of properties to supply to the component                                                   |\n| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component                             |\n| `hydrate` | `false`     | See below                                                                                            |\n| `intro`   | `false`     | If `true`, will play transitions on initial render, rather than waiting for subsequent state changes |\n\nExisting children of `target` are left where they are.\n\nThe `hydrate` option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [`hydratable: true` option](/docs/svelte-compiler#compile). Hydration of `<head>` elements only works properly if the server-side rendering code was also compiled with `hydratable: true`, which adds a marker to each element in the `<head>` so that the component knows which elements it's responsible for removing during hydration.\n\nWhereas children of `target` are normally left alone, `hydrate: true` will cause any children to be removed. For that reason, the `anchor` option cannot be used alongside `hydrate: true`.\n\nThe existing DOM doesn't need to match the component — Svelte will 'repair' the DOM as it goes.\n\n```ts\n/// file: index.js\n// @noErrors\nimport App from './App.svelte';\n\nconst app = new App({\n\ttarget: document.querySelector('#server-rendered-html'),\n\thydrate: true\n});\n```\n\n> In Svelte 5+, use [`mount`](svelte#mount) instead\n\n## `$set`\n\n```ts\n// @noErrors\ncomponent.$set(props);\n```\n\nProgrammatically sets props on an instance. `component.$set({ x: 1 })` is equivalent to `x = 1` inside the component's `<script>` block.\n\nCalling this method schedules an update for the next microtask — the DOM is _not_ updated synchronously.\n\n```ts\n// @noErrors\ncomponent.$set({ answer: 42 });\n```\n\n> In Svelte 5+, use `$state` instead to create a component props and update that\n>\n> ```js\n> // @noErrors\n> let props = $state({ answer: 42 });\n> const component = mount(Component, { props });\n> // ...\n> props.answer = 24;\n> ```\n\n## `$on`\n\n```ts\n// @noErrors\ncomponent.$on(ev, callback);\n```\n\nCauses the `callback` function to be called whenever the component dispatches an `event`.\n\nA function is returned that will remove the event listener when called.\n\n```ts\n// @noErrors\nconst off = component.$on('selected', (event) => {\n\tconsole.log(event.detail.selection);\n});\n\noff();\n```\n\n> In Svelte 5+, pass callback props instead\n\n## `$destroy`\n\n```js\n// @noErrors\ncomponent.$destroy();\n```\n\nRemoves a component from the DOM and triggers any `onDestroy` handlers.\n\n> In Svelte 5+, use [`unmount`](svelte#unmount) instead\n\n## Component props\n\n```js\n// @noErrors\ncomponent.prop;\n```\n\n```js\n// @noErrors\ncomponent.prop = value;\n```\n\nIf a component is compiled with `accessors: true`, each instance will have getters and setters corresponding to each of the component's props. Setting a value will cause a _synchronous_ update, rather than the default async update caused by `component.$set(...)`.\n\nBy default, `accessors` is `false`, unless you're compiling as a custom element.\n\n```js\n// @noErrors\nconsole.log(component.count);\ncomponent.count += 1;\n```\n\n> In Svelte 5+, this concept is obsolete. If you want to make properties accessible from the outside, `export` them\n\n## Server-side component API\n\n```js\n// @noErrors\nconst result = Component.render(...)\n```\n\nUnlike client-side components, server-side components don't have a lifespan after you render them — their whole job is to create some HTML and CSS. For that reason, the API is somewhat different.\n\nA server-side component exposes a `render` method that can be called with optional props. It returns an object with `head`, `html`, and `css` properties, where `head` contains the contents of any `<svelte:head>` elements encountered.\n\nYou can import a Svelte component directly into Node using `svelte/register`.\n\n```js\n// @noErrors\nrequire('svelte/register');\n\nconst App = require('./App.svelte').default;\n\nconst { head, html, css } = App.render({\n\tanswer: 42\n});\n```\n\nThe `.render()` method accepts the following parameters:\n\n| parameter | default | description                                        |\n| --------- | ------- | -------------------------------------------------- |\n| `props`   | `{}`    | An object of properties to supply to the component |\n| `options` | `{}`    | An object of options                               |\n\nThe `options` object takes in the following options:\n\n| option    | default     | description                                                              |\n| --------- | ----------- | ------------------------------------------------------------------------ |\n| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component |\n\n```js\n// @noErrors\nconst { head, html, css } = App.render(\n\t// props\n\t{ answer: 42 },\n\t// options\n\t{\n\t\tcontext: new Map([['context-key', 'context-value']])\n\t}\n);\n```\n\n> In Svelte 5+, use [`render`](svelte-server#render) instead","size_bytes":6415,"metadata":{"title":"Imperative component API"},"created_at":"2025-07-18T15:47:39.077Z","updated_at":"2025-07-18T15:47:40.398Z"}]}