@qwik.dev/mcp 0.0.0-stage → 2.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/docs.json ADDED
@@ -0,0 +1 @@
1
+ {"version":"2.0.0-rc.0","documents":[{"id":"/","title":"Qwik Home","description":"Project overview with the core value proposition behind resumability and streaming execution.","url":"https://next.qwik.dev/","content":"# Qwik\n\n> Qwik is a resumable web framework built to start fast, stay interactive, and download code only when it is actually needed.\n\nQwik renders HTML on the server, serializes the application state into that HTML, and resumes on the client without replaying the whole component tree.\n\nKey ideas:\n\n- Resumability instead of hydration\n- Lazy-loaded event handlers and component logic via QRLs\n- Fine-grained reactivity with signals and stores\n- File-based routing and server features via Qwik Router\n\nStart with the getting started guide, the core concepts pages, and the router guides to understand how applications are structured in practice.\n"},{"id":"/docs/labs/mcp/","title":"MCP server","description":"Connect an MCP client to a running Qwik app for local read-only inspection.","url":"https://next.qwik.dev/docs/labs/mcp/","content":"# MCP server\n\n`@qwik.dev/mcp` connects an MCP client to a running Qwik development server. It supports browser rendering and Router SSR and works independently of the DevTools panel.\n\n## Setup\n\n```sh\npnpm add -D @qwik.dev/mcp\n```\n\nAdd `qwikMcp()` before `qwikVite()` in `vite.config.ts`:\n\n```ts\nimport { defineConfig } from 'vite';\nimport { qwikVite } from '@qwik.dev/core/optimizer';\nimport { qwikRouter } from '@qwik.dev/router/vite';\nimport { qwikMcp } from '@qwik.dev/mcp';\n\nexport default defineConfig({\n plugins: [qwikMcp(), qwikRouter(), qwikVite()],\n});\n```\n\nFor a browser-only Qwik app, omit `qwikRouter()` and keep your existing `qwikVite({ csr: true })` configuration. Start Vite and open the app in a local browser.\n\nConfigure your MCP client to launch the locally installed binary through stdio:\n\n```json\n{\n \"mcpServers\": {\n \"qwik\": {\n \"command\": \"npx\",\n \"args\": [\"--no-install\", \"qwik-mcp\", \"/absolute/path/to/project\"]\n }\n }\n}\n```\n\nSet the client's working directory to your project so `npx --no-install` resolves its local dependency. The optional positional path selects the Vite project root; it defaults to the process's working directory. No package download occurs when launching this configuration.\n\n## Tools\n\n| Tool | Inputs | Result |\n| --- | --- | --- |\n| `get_project_info` | `{}` | Installed versions, script names, documentation match and optional dev URL |\n| `list_routes` | `{}` | `routerInstalled` and Router's routes, source files, parameters, layouts |\n| `get_dev_errors` | `{ url? }` | Vite errors observed by the selected page, with source locations |\n| `inspect_page` | `{ url?, selector?, includeHtml?, includeSignalValues?, includeSerializedState?, includeSerializedVNodeTree?, offset? }` | Component tree, hooks, optional HTML, signal values, parsed state and VNode tree |\n| `search_docs` | `{ query, limit? }` | Ranked documentation page IDs, titles, snippets and snapshot version |\n| `get_doc` | `{ id }` | Full Markdown page, source URL and snapshot version |\n| `get_best_practices` | `{}` | Short Qwik coding guide and its bundled version |\n\n`includeHtml` and `includeSignalValues` default to `false`. `selector` scopes the HTML fragment; component metadata still describes the page. HTML is current DOM, marked `source: \"live-dom\"`, limited to 64 KiB of UTF-8, with `truncated` indicating an incomplete fragment. It is not the original SSR response.\n\n`includeSerializedState` and `includeSerializedVNodeTree` also default to `false`. They parse the page's Qwik state scripts and reconstruct a VNode tree from a copy of the DOM. Each returns `null` when no Qwik container or relevant state exists, or `{ source: \"serialized-dom\", content, truncated, nextOffset }` with a 64 KiB UTF-8 limit. These snapshots may differ from current signal values after interaction. `selector` does not scope them.\n\nEach text result also includes `nextOffset`. If `truncated` is `true`, call `inspect_page` again with the same include flag and `offset: nextOffset`. Repeat until `nextOffset` is `null`. The offset counts UTF-8 bytes and applies to every selected text field, so request one text field at a time when paging. Page changes can mix snapshots across calls; if an offset becomes invalid, restart at `0`.\n\nHook metadata is collected by the shared DevTools instrumentation as components execute and their document-ready tasks run. Components that have not executed in the browser may appear in the tree without hook metadata. Snapshot entries are grouped by component source, so repeated instances share that metadata.\n\nWith several pages connected, provide the exact page URL. Duplicate tabs with the same URL must be closed until one remains. Missing pages, invalid selectors, missing runtime and disconnected servers return tool errors. Vite errors clear after successful HMR; this is not a project-wide typecheck or build report.\n\n## Offline documentation\n\n`get_best_practices`, `search_docs` and `get_doc` work without Vite, an open browser or network access. The short guide and documentation snapshot are bundled with the MCP package and carry its version. The snapshot is generated from all Qwik documentation and API pages during the MCP build. MCP uses the same complete manifest as `llms.txt`; new documentation pages are discovered automatically during the build. It describes that release, which may differ from the Qwik version installed in your application.\n\nThe MCP server also sends workflow instructions during initialization: read the guide for Qwik code, search for specific topics, then fetch the full page. The instructions describe which live tools require Vite and a connected browser.\n\n`get_project_info` reads installed Qwik packages and project script names even when Vite is stopped. It returns `documentation.version` and `documentation.matchesProject`, which compares the bundled documentation version with the installed Qwik core version exactly. `devServerRunning` is `false` and `devUrl` is absent until Vite starts. `routerVersion` reports the installed Router package; use `list_routes` to see whether the Router plugin is active.\n\nSearch first, then use a returned page ID to read the full document:\n\n```json\n{ \"query\": \"useSignal\", \"limit\": 5 }\n```\n\n```json\n{ \"id\": \"/docs/core/state/\" }\n```\n\nSearch matches words in page titles, descriptions and Markdown content, with title matches ranked first. `limit` defaults to 5 and accepts 1–20. An unknown page ID returns a tool error.\n\n## Local access\n\nThe plugin runs only during development. Its internal endpoint accepts loopback connections with a random session token and rejects browser origins. Discovery files live in `node_modules/.cache/qwik-mcp`, have owner-only permissions on Unix, and are removed when the server closes. Stale files from terminated processes are ignored.\n\nUse a standalone HTTP Vite server with HMR enabled. HTTPS and middleware mode are currently unsupported. The CLI sends only MCP protocol messages to stdout. Tools inspect the running app and do not edit files, install packages or start builds. Returned HTML, hook metadata and signal values are application content and may contain private information.\n"},{"id":"/docs/getting-started/","title":"Getting Started","description":"Hands-on introduction to creating an app, routing, data loading, state, tasks, and styling.","url":"https://next.qwik.dev/docs/getting-started/","content":"# Getting Started Qwikly\n\nQwik is a new kind of framework that is [resumable](/docs/concepts/resumable.md) (no eager JS execution and no hydration), built for the edge and [familiar to React developers](/docs/integrations/react.md).\n\nTo play with it right away, check out Qwik's in-browser playgrounds:\n\n- [StackBlitz Qwik](https://qwik.new) (Full Qwik + Qwik Router integration)\n- [Examples playground](/examples/reactivity/counter/) (Qwik only, no routing)\n\n## Prerequisites\n\nTo get started with Qwik locally, you need the following:\n\n- [Node.js v18.17](https://nodejs.org/en/download/) or higher\n- Your favorite IDE ([vscode](https://code.visualstudio.com/) recommended)\n- Optionally, read [think qwik](/docs/concepts/think-qwik.md)\n\n## Create an app using the CLI\n\nFirst, use the Qwik CLI to generate a blank starter application, to quickly familiarize yourself with it.\n\nRun the Qwik CLI in your shell. Qwik supports pnpm, npm, yarn and bun. Choose the package manager you prefer and run one of the following commands:\n\n```shell\npnpm create qwik@latest\n```\n\nThe CLI guides you through an interactive menu to set the project-name, select one of the starters, and ask if you want to install the dependencies. To find out more about the files generated, refer to the [Project Structure](/docs/project-structure.md) documentation.\n\nStart the development server:\n\n```shell\npnpm run start\n```\n\n## Qwik Joke App\n\nThe Qwik Hello World tutorial guides you through building a joke app with Qwik while covering the most important Qwik concepts. The app displays a random joke from https://icanhazdadjoke.com and features a button to get a new joke on click.\n\n### 1. Create A Route\n\nStart by serving a page at a particular route. This basic app serves a random dad joke application on the `/joke/` route. This tutorial relies on Qwik Router, which uses [directory-based](/docs/routing.md) routing. To get started:\n\n1. In your project, create a new `joke` directory in `routes` containing an `index.tsx` file.\n2. Each route's `index.tsx` file must have an `export default component$(...)` so that Qwik Router knows what content to serve. Paste the following content to `src/routes/joke/index.tsx`:\n\n```tsx {3-5} title=\"src/routes/joke/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return <section class=\"section bright\">A Joke!</section>;\n});\n```\n\n3. Navigate to `localhost:5173/joke/` to see your new page working.\n\n**Route and Component Basics**\n\n- Your `joke` route default component is surrounded by an existing layout. See [Layout](/docs/layout.md) for more details on what layouts are and how to work with them.\n- index.tsx, layout.tsx in routes folder, root.tsx and all entry files need **export default**. For other components you can use export const and export function.\n- For more details about how to author components, see the [Component API](/docs/core/overview.md) section.\n\n### 2. Loading Data\n\nUse the external JSON API at https://icanhazdadjoke.com to load random jokes. You can use [route loaders](/docs/route-loader.md) to load this data into the server and render it in the component.\n\n1. Open `src/routes/joke/index.tsx` and add this code:\n\n```tsx /routeLoader$/ /useDadJoke/#a title=\"src/routes/joke/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useDadJoke = routeLoader$(async () => {\n const response = await fetch('https://icanhazdadjoke.com/', {\n headers: { Accept: 'application/json' },\n });\n return (await response.json()) as {\n id: string;\n status: number;\n joke: string;\n };\n});\n\nexport default component$(() => {\n // Calling our `useDadJoke` hook, will return a reactive signal to the loaded data.\n const dadJokeSignal = useDadJoke();\n return (\n <section class=\"section bright\">\n <p>{dadJokeSignal.value.joke}</p>\n </section>\n );\n});\n```\n\n2. Now on `http://localhost:5173/joke/`, the browser displays a random joke.\n\nCode explanation:\n\n- The function passed to `routeLoader$` is invoked on the server eagerly before any component is rendered and is responsible for loading data.\n- The `routeLoader$` returns a use-hook, `useDadJoke()`, that can be used in the component to retrieve the server data.\n\n**routeLoader$ Behavior**\n\n- The `routeLoader$` is invoked eagerly on the server before any component is rendered, even if its use-hook is not invoked in any component.\n- The `routeLoader$` return type is inferred in the component without the need for any additional type information.\n\n### 3. Posting Data to the Server\n\nPreviously, the component `routeLoader$` was used to send data from the server to the client. To post (send) data from the client back to the server, use [`routeAction$`](/docs/action.md).\n\nNOTE: `routeAction$` is the preferred way to send data to the server because it uses the browser native form API, which works even if JavaScript is disabled.\n\nTo declare an action, add this code:\n\n```tsx /routeAction\\$/ title=\"src/routes/joke/index.tsx\"\nimport { routeLoader$, Form, routeAction$ } from '@qwik.dev/router';\n\nexport const useJokeVoteAction = routeAction$(\n (props) => {\n // Leave it as an exercise for the reader to implement this.\n console.log('VOTE', props);\n },\n { invalidate: [useDadJoke] }\n);\n```\n\n2. Update the `export default` component to use the `useJokeVoteAction` hook with `<Form>`.\n\n```tsx {3,7-11} /favoriteJokeAction/ title=\"src/routes/joke/index.tsx\"\nexport default component$(() => {\n const dadJokeSignal = useDadJoke();\n const favoriteJokeAction = useJokeVoteAction();\n return (\n <section class=\"section bright\">\n <p>{dadJokeSignal.value.joke}</p>\n <Form action={favoriteJokeAction}>\n <input type=\"hidden\" name=\"jokeID\" value={dadJokeSignal.value.id} />\n <button name=\"vote\" value=\"up\"></button>\n <button name=\"vote\" value=\"down\"></button>\n </Form>\n </section>\n );\n});\n```\n\n3. Now the buttons display on `http://localhost:5173/joke/`, and their values will log to the console when they are clicked.\n\nCode explanation:\n\n- `routeAction$` receives the data.\n - The function passed to `routeAction$` is invoked on the server whenever the form is posted.\n - The `invalidate` option tells Qwik to re-run `useDadJoke` after the action completes.\n - The `routeAction$` returns a use-hook, `useJokeVoteAction`, that you can use in the component to post the form data.\n- `Form` is a convenience component that wraps the browser's native `<form>` element.\n\nThings to note:\n\n- For validation, see [zod validation](/docs/action.md#validation-and-type-safety).\n- The `routeAction$` works even if JavaScript is disabled.\n- If JavaScript is enabled, the `Form` component will prevent the browser from posting the form and instead post the data using JavaScript and emulate the browser's native form behavior without a full refresh.\n\nFor reference, the complete code snippet for this section is as follows:\n\n```tsx /favoriteJokeAction/ /invalidate/ title=\"src/routes/joke/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$, Form, routeAction$ } from '@qwik.dev/router';\n\nexport const useDadJoke = routeLoader$(async () => {\n const response = await fetch('https://icanhazdadjoke.com/', {\n headers: { Accept: 'application/json' },\n });\n return (await response.json()) as {\n id: string;\n status: number;\n joke: string;\n };\n});\n\nexport const useJokeVoteAction = routeAction$(\n (props) => {\n console.log('VOTE', props);\n },\n { invalidate: [useDadJoke] }\n);\n\nexport default component$(() => {\n // Calling our `useDadJoke` hook, will return a reactive signal to the loaded data.\n const dadJokeSignal = useDadJoke();\n const favoriteJokeAction = useJokeVoteAction();\n return (\n <section class=\"section bright\">\n <p>{dadJokeSignal.value.joke}</p>\n <Form action={favoriteJokeAction}>\n <input type=\"hidden\" name=\"jokeID\" value={dadJokeSignal.value.id} />\n <button name=\"vote\" value=\"up\">\n </button>\n <button name=\"vote\" value=\"down\">\n </button>\n </Form>\n </section>\n );\n});\n```\n\n### 4. Modifying State\n\nKeeping track of the state and updating the UI is core to what applications do. Qwik provides a `useSignal` hook to keep track of the application's state. To learn more, see [state management](/docs/core/state.md).\n\nTo declare state:\n\n1. Import `useSignal` from `qwik`.\n ```tsx /useSignal/\n import { component$, useSignal } from \"@qwik.dev/core\";\n ```\n2. Declare the component's state using `useSignal()`.\n ```tsx /useSignal/\n const isFavoriteSignal = useSignal(false);\n ```\n3. After the closing `Form` tag, add a button to the component to modify the state.\n ```tsx /isFavoriteSignal/\n <button\n onClick$={() => {\n isFavoriteSignal.value = !isFavoriteSignal.value;\n }}>\n {isFavoriteSignal.value ? '' : ''}\n </button>\n ```\n\nNOTE: Clicking on the button updates the state, which in turn updates the UI.\n\nFor reference, the complete code snippet for this section is as follows:\n\n```tsx /isFavoriteSignal/ title=\"src/routes/joke/index.tsx\"\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { routeLoader$, Form, routeAction$ } from '@qwik.dev/router';\n\nexport const useDadJoke = routeLoader$(async () => {\n const response = await fetch('https://icanhazdadjoke.com/', {\n headers: { Accept: 'application/json' },\n });\n return (await response.json()) as {\n id: string;\n status: number;\n joke: string;\n };\n});\n\nexport const useJokeVoteAction = routeAction$(\n (props) => {\n console.log('VOTE', props);\n },\n { invalidate: [useDadJoke] }\n);\n\nexport default component$(() => {\n const isFavoriteSignal = useSignal(false);\n // Calling our `useDadJoke` hook, will return a reactive signal to the loaded data.\n const dadJokeSignal = useDadJoke();\n const favoriteJokeAction = useJokeVoteAction();\n\n return (\n <section class=\"section bright\">\n <p>{dadJokeSignal.value.joke}</p>\n <Form action={favoriteJokeAction}>\n <input type=\"hidden\" name=\"jokeID\" value={dadJokeSignal.value.id} />\n <button name=\"vote\" value=\"up\">\n </button>\n <button name=\"vote\" value=\"down\">\n </button>\n </Form>\n <button\n onClick$={() => (isFavoriteSignal.value = !isFavoriteSignal.value)}\n >\n {isFavoriteSignal.value ? '' : ''}\n </button>\n </section>\n );\n});\n```\n\n### 5. Tasks and Invoking Server Code\n\nIn Qwik, a [task](/docs/core/tasks.md#usetask) is work that needs to happen when a state changes. (This is similar to an \"effect\" in other frameworks.) In this example, we use the task to invoke code on the server.\n\n1. Import `useTask$` from `qwik` and `server$` from `qwik-router`.\n ```tsx /useTask\\$/ /server\\$/\n import { component$, useSignal, useTask$ } from \"@qwik.dev/core\";\n import {\n routeLoader$,\n Form,\n routeAction$,\n server$,\n } from '@qwik.dev/router';\n ```\n\n2. Create a new task that tracks the `isFavoriteSignal` state:\n ```tsx /useTask\\$/\n useTask$(({ track }) => {});\n ```\n3. Add a `track` call to re-execute the task on `isFavoriteSignal` state change:\n ```tsx /track/\n useTask$(({ track }) => {\n track(() => isFavoriteSignal.value);\n });\n ```\n4. Add the work that you want to execute on state change:\n ```tsx {3}\n useTask$(({ track }) => {\n track(() => isFavoriteSignal.value);\n console.log('FAVORITE (isomorphic)', isFavoriteSignal.value);\n });\n ```\n5. If you want to have work happen on the server only, wrap it in `server$()`\n ```tsx /server\\$/ {4-6}\n useTask$(({ track }) => {\n track(() => isFavoriteSignal.value);\n console.log('FAVORITE (isomorphic)', isFavoriteSignal.value);\n server$(() => {\n console.log('FAVORITE (server)', isFavoriteSignal.value);\n })();\n });\n ```\n\nNOTE:\n\n- The body of `useTask$` is executed on both the server and the client (isomorphic).\n- On SSR, the server prints `FAVORITE (isomorphic) false` and `FAVORITE (server) false`.\n- When the user interacts with favorite, the client prints `FAVORITE (isomorphic) true` and the server prints `FAVORITE (server) true`.\n\nFor reference, the complete code snippet for this section is as follows:\n\n```tsx {32-38} title=\"src/routes/joke/index.tsx\"\nimport { component$, useSignal, useTask$ } from '@qwik.dev/core';\nimport {\n routeLoader$,\n Form,\n routeAction$,\n server$,\n} from '@qwik.dev/router';\n\nexport const useDadJoke = routeLoader$(async () => {\n const response = await fetch('https://icanhazdadjoke.com/', {\n headers: { Accept: 'application/json' },\n });\n return (await response.json()) as {\n id: string;\n status: number;\n joke: string;\n };\n});\n\nexport const useJokeVoteAction = routeAction$(\n (props) => {\n console.log('VOTE', props);\n },\n { invalidate: [useDadJoke] }\n);\n\nexport default component$(() => {\n const isFavoriteSignal = useSignal(false);\n // Calling our `useDadJoke` hook, will return a reactive signal to the loaded data.\n const dadJokeSignal = useDadJoke();\n const favoriteJokeAction = useJokeVoteAction();\n useTask$(({ track }) => {\n track(() => isFavoriteSignal.value);\n console.log('FAVORITE (isomorphic)', isFavoriteSignal.value);\n server$(() => {\n console.log('FAVORITE (server)', isFavoriteSignal.value);\n })();\n });\n return (\n <section class=\"section bright\">\n <p>{dadJokeSignal.value.joke}</p>\n <Form action={favoriteJokeAction}>\n <input type=\"hidden\" name=\"jokeID\" value={dadJokeSignal.value.id} />\n <button name=\"vote\" value=\"up\">\n </button>\n <button name=\"vote\" value=\"down\">\n </button>\n </Form>\n <button\n onClick$={() => (isFavoriteSignal.value = !isFavoriteSignal.value)}\n >\n {isFavoriteSignal.value ? '' : ''}\n </button>\n </section>\n );\n});\n```\n\n### 6. Styling\n\nStyling is an important part of any application. Qwik provides a way to associate and scope styles with your component.\n\nTo add styles:\n\n1. Create a new file `src/routes/joke/index.css`:\n\n ```css\n p {\n font-weight: bold;\n }\n\n form {\n float: right;\n }\n ```\n\n2. import the styles in `src/routes/joke/index.tsx`:\n ```tsx\n import styles from \"./index.css?inline\";\n ```\n3. Import `useStylesScoped$` from `qwik`.\n ```tsx /useStylesScoped$/\n import { component$, useSignal, useStylesScoped$, useTask$ } from \"@qwik.dev/core\";\n4. Tell the component to load the styles:\n ```tsx\n useStylesScoped$(styles);\n ```\n\nCode explanation:\n\n- The `?inline` query parameter tells Vite to inline the styles into the component.\n- The `useStylesScoped$` call tells Qwik to associate the styles with the component only (scoping).\n- Styles are only loaded if they are not already inlined as part of SSR and only for the first component.\n\nFor reference, the complete code snippet for this section is as follows:\n\n<CodeSandbox maxHeight={500} src=\"/src/routes/demo/getting-started/06-styling/index.tsx\" style={{ height: '10em' }}>\n```tsx /useStylesScoped\\$/#a /styles/#b title=\"src/routes/joke/index.tsx\"\n component$,\n useSignal,\n useStylesScoped$,\n useTask$,\n} from '@qwik.dev/core';\n routeLoader$,\n Form,\n routeAction$,\n server$,\n} from '@qwik.dev/router';\n\n const response = await fetch('https://icanhazdadjoke.com/', {\n headers: { Accept: 'application/json' },\n });\n return (await response.json()) as {\n id: string;\n status: number;\n joke: string;\n };\n});\n\n (props) => {\n console.log('VOTE', props);\n },\n { invalidate: [useDadJoke] }\n);\n\nexport default component$(() => {\n useStylesScoped$(styles);\n const isFavoriteSignal = useSignal(false);\n // Calling our `useDadJoke` hook, will return a reactive signal to the loaded data.\n const dadJokeSignal = useDadJoke();\n const favoriteJokeAction = useJokeVoteAction();\n useTask$(({ track }) => {\n track(() => isFavoriteSignal.value);\n console.log('FAVORITE (isomorphic)', isFavoriteSignal.value);\n server$(() => {\n console.log('FAVORITE (server)', isFavoriteSignal.value);\n })();\n });\n return (\n <section class=\"section bright\">\n{dadJokeSignal.value.joke}\n\n <input type=\"hidden\" name=\"jokeID\" value={dadJokeSignal.value.id} />\n <button name=\"vote\" value=\"up\"></button>\n <button name=\"vote\" value=\"down\"></button>\n <button\n onClick$={() => (isFavoriteSignal.value = !isFavoriteSignal.value)}\n >\n {isFavoriteSignal.value ? '' : ''}\n </button>\n </section>\n );\n});\n```\n</CodeSandbox>\n\n### 7. Preview\n\nUp until now, you've been using the dev server to make your application.\n\nThis is great to see your changes in real time, but it doesn't work the same way as in production:\n\n- Each file is loaded individually, which may cause waterfalls in the network tab.\n- There is no speculative loading of bundles, so there may be a delay on the first interaction.\n\nTo make sure everything is ready for production and eliminate these issues, you can run your app in preview:\n\n1. Run `preview` command to create a production build and run it.\n\n<PackageManagerTabs>\n<span q:slot=\"pnpm\">\n```shell\npnpm run preview\n```\n</span>\n<span q:slot=\"npm\">\n```shell\nnpm run preview\n```\n</span>\n<span q:slot=\"yarn\">\n```shell\nyarn run preview\n```\n</span>\n<span q:slot=\"bun\">\n```shell\nbun run preview\n```\n</span>\n</PackageManagerTabs>\n\nNOTE:\n\n- Your application should now have a production build running on localhost:4173.\n- If you interact with the application now, the network tab of the dev tools should show that the bundles have been [preloaded](/docs/advanced/speculative-module-fetching.md).\n\n## Review\n\nCongratulations, you've learned a lot about Qwik!\nFor more on just how much you can achieve with Qwik, check out the dedicated docs on each of the topics touched on in this tutorial:\n\n- [Project structure](/docs/project-structure.md)\n- [Directory-based routing](/docs/routing.md#directory-based-routing)\n- [Component](/docs/core/overview.md)\n- [Route loaders](/docs/route-loader.md)\n- [Form actions](/docs/action.md) && [zod validation](/docs/action.md#validation-and-type-safety)\n- [State management](/docs/core/state.md)\n- [Tasks](/docs/core/tasks.md#use-usetask-when-you-need-to)\n- [Preloading](/docs/advanced/speculative-module-fetching.md)\n"},{"id":"/docs/project-structure/","title":"Project Structure","description":"Explains the default app layout, routing folders, and where framework and router concerns live.","url":"https://next.qwik.dev/docs/project-structure/","content":"# Project Structure\n\nA typical Qwik project looks like this:\n\n```bash\nqwik-app-demo\n|-- README.md\n|-- package.json\n|-- public\n| `-- favicon.svg\n|-- src\n| |-- components\n| | `-- router-head\n| | `-- router-head.tsx\n| |-- entry.ssr.tsx\n| |-- global.css\n| |-- root.tsx\n| `-- routes\n| |-- flower\n| | |-- flower.css\n| | `-- index.tsx\n| |-- index.tsx\n| `-- layout.tsx\n|-- tsconfig.json\n`-- vite.config.ts\n```\n\n## Project files\n\n### `src/routes/`\n\nThe `src/routes/` directory is a special directory where Qwik Router will look for your pages. Folders and files inside this directory have a special meaning and they will be mapped to the URL of your app.\n\n- `src/routes/index.tsx` is the homepage of your app.\n- `src/routes/layout.tsx` is the root layout of your app, all pages will be rendered inside this layout.\n\nRefer to the [Routing](/docs/routing.md) section for more information.\n\n### `src/components/`\n\nThe directory named `src/components/` follows a standard convention. It's present in all Qwik starters and you can rename it if you prefer. The `src/components/` directory is where to put your components (i.e. reusable pieces of code that can be used in multiple places). These components are not routes or layouts, but they can be referenced from within your route or layout code.\n\nFor example, a `Button` component should be inside `src/components/button/button.tsx`.\n\n### `public/`\n\nThe `public/` directory contains static assets such as images, fonts, and icons. When you build your app, these files will be copied to the `dist/` directory and served at the root.\n\nRefer to [Vite configuration for more information](https://vitejs.dev/guide/build.html#public-base-path).\n\n### `src/entry.ssr.tsx`\n\nThe SSR entry point is the common entry point in all cases where the application is rendered outside of the browser.\n\n- Server (express, cloudflare...)\n- `start` command\n- `preview` command\n- `build` command\n\n### `src/root.tsx`\n\nThe `src/root.tsx` file is the root of the application tree. It is the entry point and is the first component that will be rendered.\n\n### `src/global.css`\n\nThe `src/global.css` file is a global CSS file, if you need to define some CSS that is used in multiple places in your app, you can define it here.\n\nThe root component (`src/root.tsx`) imports this file by default.\n\n### `tsconfig.json`\n\nThe `tsconfig.json` file contains the TypeScript compiler configuration. It's standard for any TypeScript project.\n\n### `vite.config.ts`\n\nQwik uses Vite to build the project. The `vite.config.ts` file contains the Vite configuration. It's standard for any Vite project. Please refer to the [Vite documentation](https://vitejs.dev/config/) for more information.\n\n## Utilities\n\nQwik has a utility command called `new` that allows developers to easily create new components and routes.\n\nLet's say you wanted to create a new component called `Button`, you would run the command:\n\n```shell\npnpm run qwik new Button\n```\n\nMaybe you want to create a new route for the /contact page. To do that, you could use the command:\n\n```shell\npnpm run qwik new /contact\n```\n\nThe following commands are consistent with Qwik's directory file structure, allowing you to scaffold components more quickly.\n\nIf we compare our `qwik-app-demo` from the top of the page, the additional changes would look like this:\n\n```bash\nqwik-app-demo\n|-- README.md\n|-- package.json\n|-- public\n| `-- favicon.svg\n|-- src\n| |-- components\n| | `-- router-head\n| | `-- router-head.tsx\n| | Button\n| | `-- button.tsx\n| |-- entry.ssr.tsx\n| |-- global.css\n| |-- root.tsx\n| `-- routes\n| |-- flower\n| | |-- flower.css\n| | `-- index.tsx\n| |-- contact\n| | `-- index.tsx\n| |-- index.tsx\n| |-- layout.tsx\n| `-- service-worker.ts\n|-- tsconfig.json\n`-- vite.config.ts\n```\n\nIf you prefer to generate the `Button` component with the `Button/index.tsx` naming convention, you could use the command:\n\n```shell\npnpm run qwik new --barrel Button\n```\n\nIn that case, the `src/components` folder would look like this:\n```bash\nsrc\n| |-- components\n| | `-- router-head\n| | `-- router-head.tsx\n| | Button\n| | `-- index.tsx\n```\n\nThis feature was added in Qwik v1.2, and those using an older version will not see this functionality.\n"},{"id":"/playground/","title":"Playground","description":"Interactive playground for trying Qwik code, shareable examples, and quick experiments.","url":"https://next.qwik.dev/playground/","content":"# Playground\n\n> The Qwik playground is an in-browser REPL for experimenting with Qwik code and sharing runnable examples.\n\nUse the playground when you want to:\n\n- try component and signal examples quickly\n- reproduce a small issue in isolation\n- share example snippets with a stable URL\n\nThe playground focuses on rapid experimentation rather than long-form documentation, so use the docs mirrors for detailed explanations and the playground for fast iteration.\n"},{"id":"/docs/","title":"Docs Overview","description":"High-level docs entry point for Qwik framework concepts and core learning paths.","url":"https://next.qwik.dev/docs/","content":"# Welcome to Qwik\n\nQwik is a new kind of web framework that can deliver instant loading web applications at any size or complexity thanks to its resumable and javascript streaming architecture.\n\n## Getting Started with Qwik\n\n- [Getting Started](/docs/getting-started.md): Learn the basics and create your first Qwik app in minutes.\n- [Why Qwik?](/docs/concepts/think-qwik.md): Understand resumability, javascript streaming, and what makes Qwik unique.\n- [API Reference](/api.md): Complete reference for all Qwik core APIs, hooks, and utilities.\n- [Courses](/ecosystem/#courses): Step-by-step tutorials and interactive courses for all skill levels.\n- [Community](https://qwik.dev/chat): Join the Discord, contribute to the project, and share what you build.\n- [Qwik Router](/docs/qwikrouter.md): File-based routing, loaders, actions, and middleware for your app.\n\n## Explore More\n\n- [Media & Presentations](/media/): See more presentations, videos, and podcasts\n- [Showcase](/showcase/): Check out websites built with Qwik\n\n## Why Qwik?\n\n- **General-purpose:** Qwik can be used to build any type of website or application.\n- **Instant Interactivity:** Qwik apps work instantly without any delay because they don't need hydration, regardless of their size or complexity.\n- **JS Streaming:** Qwik delivers sub-second full page loads, even on mobile, by serving pure HTML and executing JavaScript when your users opt-in.\n"},{"id":"/docs/core/overview/","title":"Core Overview","description":"Overview of components, JSX rendering, and the framework primitives used throughout Qwik apps.","url":"https://next.qwik.dev/docs/core/overview/","content":"# Components\n\nComponents are the basic building blocks of Qwik Applications. They are reusable pieces of code that can be used to build a UI.\n\nQwik components are unique in that:\n\n- Qwik components automatically get broken down into lazy-loaded chunks by the [Optimizer](/docs/advanced/optimizer.md).\n- They are [resumable](/docs/concepts/resumable.md) (a component can get created on a server and continue its execution on the client).\n- They are [reactive](/docs/concepts/reactivity.md) and render independently of other components on the page. See [rendering](/docs/core/rendering.md).\n\n## `component$()`\n\nA Qwik component is a function that returns JSX wrapped in a `component$` call.\n\n```tsx /component$/\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return <div>Hello World!</div>;\n});\n```\n\nThe `component$` function, marked by the trailing `$`, enables the Optimizer to split components into separate chunks. This allows each chunk to be loaded independently as needed, rather than loading all components whenever the parent component is loaded. index.tsx, layout.tsx in routes folder, root.tsx and all entry files need **export default**. For other components you can use export const and export function.\n\n### Composing Components\n\nComponents can be composed together to create more complex components.\n\n```tsx {7}\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <>\n <p>Parent Text</p>\n <Child />\n </>\n );\n});\n\nconst Child = component$(() => {\n return <p>Child Text</p>;\n});\n```\n\nQwik components are already lazy loaded thanks to the `$` sign. That means that you don't need to dynamically import the child component manually, Qwik will do it for you.\n\n### Dot Notation Components\n\nWhile you cannot directly attach properties to a component created with `component$` (e.g. `Scene.Title = Title`), you can achieve dot-notation by using ES module exports or barrel files.\n\n#### Using Barrel Files\n\nCreate an `index.ts` file in your component directory to group related components:\n\n```tsx\n// components/scene/index.ts\nexport { SceneComponent as Root } from './scene-root';\nexport { SceneTitle as Title } from './scene-title';\n```\n\nThen, you can import and use them with dot notation:\n\n```tsx\nimport * as Scene from './components/scene';\n\nexport default component$(() => {\n return (\n <Scene.Root>\n <Scene.Title>ACT III Scene II</Scene.Title>\n </Scene.Root>\n );\n});\n```\n\n#### Exporting as Namespace\n\nYou can also export all sub-components from a directory as a single namespace:\n\n```tsx\n// components/ui/index.ts\nexport * as Select from './select';\nexport * as Accordion from './accordion';\n```\n\nAnd use it like so:\n\n```tsx\nimport { Select } from './components/ui';\n\nexport default component$(() => {\n return (\n <Select.Root>\n <Select.Item>Option 1</Select.Item>\n </Select.Root>\n );\n});\n```\n\n### Counter Example\n\nA slightly more complex example of a counter.\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const count = useSignal(0);\n\n return (\n <>\n <p>Count: {count.value}</p>\n <button onClick$={() => count.value++}>Increment</button>\n </>\n );\n});\n```\n\n## Props\n\nProps are used to pass data from the parent into the component. Data passed via props is accessible via the `props` argument to the `component$` function.\n\nProps are shallowly immutable, meaning primitive data types (strings, numbers, booleans) cannot be changed once passed. However, internal elements of reference types (objects, arrays, functions) can be changed despite the reference itself being immutable.\n\nTo change primitive props data in the parent component from the child component, use signals. When updating data locally within the child component a signal is not necessary, destructure the props and use the values to define new local variables.\n\nThe two examples below show a component `Item` that declares optional `name`, `quantity`, `description`, and `price` props.\n\nIn the first example, primitive data types are passed via props. The `price` prop is passed as a signal and can be changed from the parent component. `quantity` is passed as a number value that is used to define a new signal in `Item` that can be reactively updated locally. Alternatively, if quantity did not need to be reactive it could be defined as a normal variable instead of a signal.\n\n```tsx {3-8, 27} /ItemProps/\nimport { component$, useSignal } from \"@qwik.dev/core\";\nimport type { Signal } from \"@qwik.dev/core\";\n\ninterface ItemProps {\n name?: string;\n quantity?: number;\n description?: string;\n price?: Signal<number>;\n}\n\nexport const Item = component$<ItemProps>((props) => {\n const localQuantity = useSignal(props.quantity);\n\n return (\n <ul>\n <li>name: {props.name}</li>\n <li>quantity: {localQuantity}</li>\n <li>description: {props.description}</li>\n <li>price: {props.price}</li>\n </ul>\n );\n});\n\nexport default component$(() => {\n const price = useSignal(9.99);\n\n return (\n <>\n <h1>Props</h1>\n <Item name=\"hammer\" price={price} quantity={5} />\n </>\n );\n});\n\n```\n\nIn this second example, the props are passed as a single details object containing the data, instead of individual primitive values. This allows the data inside to be mutated without the use of signals. However, the details object storing the data is still immutable and cannot be changed once passed.\n\n```tsx {3-8, 27} /ItemProps/\nimport { component$ } from \"@qwik.dev/core\";\n\ninterface ItemProps {\n details: {\n name?: string;\n quantity?: number;\n description?: string;\n price?: number;\n };\n}\n\nexport const Item = component$((props: ItemProps) => {\n props.details.price = 4.99;\n\n return (\n <ul>\n <li>name: {props.details.name}</li>\n <li>quantity: {props.details.quantity}</li>\n <li>description: {props.details.description}</li>\n <li>price: {props.details.price}</li>\n </ul>\n );\n});\n\nexport default component$(() => {\n return (\n <Item\n details={{ name: \"hammer\", quantity: 5, description: \"\", price: 9.99 }}\n />\n );\n});\n\n```\n\nIn the examples above, we are using `component$` to provide an explicit type for the props. This is optional, but it allows the TypeScript compiler to check that the props are used correctly.\n\n### Default props\n\nYou can use the destructuring pattern with props to provide default values.\n\n```tsx\ninterface Props {\n enabled?: boolean;\n placeholder?: string;\n}\n\n// We can use JS's destructuring of props to provide a default value.\nexport default component$<Props>(({enabled = true, placeholder = ''}) => {\n return (\n <input disabled={!enabled} placeholder={placeholder} />\n );\n});\n```\n\n## Rendering on Reactivity\n\nQwik components are reactive. This means that they automatically update on a state change. There are two kinds of updates:\n\n1. A state is bound to a DOM text or attribute. Such changes usually directly update the DOM and do not require component function re-execute.\n2. A state causes a structural change to the DOM (elements are created and or removed). Such changes require component function to re-execute.\n\nThe thing to keep in mind is that when state changes, your component function may execute zero or more times depending on what the state is bound to. For this reason, the function should be idempotent and you should not rely on the number of times it executes.\n\nA state change causes the component to get invalidated. When components get invalidated, they are added to the invalidation queue, which is flushed (rendered) on the next `requestAnimationFrame`. This acts as a form of coalescing for component rendering.\n\n## Getting hold of DOM element\n\nUse `ref` to get hold of a DOM element. Create a signal to store DOM element. Then pass the signal to the JSX `ref` property.\n\nGetting a reference to DOM elements can be useful to calculate the element size (`getBoundingClientRect`), computed styles, initializing a WebGL canvas, or even wire-up some third-party library that interacts with DOM elements directly.\n\n```tsx /const outputRef = useSignal<Element>();/ /ref={outputRef}/\nimport { component$, useVisibleTask$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const width = useSignal(0);\n const height = useSignal(0);\n const outputRef = useSignal<Element>();\n\n useVisibleTask$(() => {\n if (outputRef.value) {\n const rect = outputRef.value.getBoundingClientRect();\n width.value = Math.round(rect.width);\n height.value = Math.round(rect.height);\n }\n });\n\n return (\n <section>\n <article\n ref={outputRef}\n style={{ border: '1px solid red', width: '100px' }}\n >\n Change text value here to stretch the box.\n </article>\n <p>\n The above red box is {height.value} pixels high and {width.value}{' '}\n pixels wide.\n </p>\n </section>\n );\n});\n```\n\n## Accessing Elements by `id` Across Server and Client Environments\n\nIn server and client environments, elements must sometimes be accessed by their `id`. Use the `useId()` function to get a unique identifier for the current component that remains consistent across server-side rendering (SSR) and client-side operations. This is pivotal when server-rendered components need client-side scripting, such as:\n\n1. **Animation Engines**\n2. **Accessibility Enhancement**\n3. **Other Client-Side Libraries**\n\nIn a microfrontends setup, where multiple fragments run concurrently, `useId()` ensures unique and consistent IDs across execution environments, eliminating conflicts.\n\n```tsx /const outputRef = useSignal<Element>();/ /ref={outputRef}/\nimport {\n component$,\n useId,\n useSignal,\n useVisibleTask$,\n} from '@qwik.dev/core';\n\nexport default component$(() => {\n const elemIdSignal = useSignal<string | null>(null);\n const id = useId();\n const elemId = `${id}-example`;\n console.log('server-side id:', elemId);\n\n useVisibleTask$(() => {\n const elem = document.getElementById(elemId);\n elemIdSignal.value = elem?.getAttribute('id') || null;\n console.log('client-side id:', elemIdSignal.value);\n });\n\n return (\n <section>\n <div id={elemId}>\n Both server-side and client-side console should match this id:\n <br />\n <b>{elemIdSignal.value || null}</b>\n </div>\n </section>\n );\n});\n```\n\n## Lazy Loading\n\nThe component also serves an important role when breaking parent-child relationships for bundling purposes.\n\n```tsx\nexport const Child = () => <span>child</span>;\n\nconst Parent = () => (\n <section>\n <Child />\n </section>\n);\n```\n\nIn the above example, referring to the `Parent` component implies a transitive reference to the `Child` component. When the bundler is creating a chunk, a reference to `Parent` necessitates bundling `Child` as well. (`Parent` internally refers to `Child`.) These transitive dependencies are a problem because it means that having a reference to the root component will transitively refer to the remainder of the application—something which Qwik tries to avoid explicitly.\n\nTo avoid the above problem we don't refer to components directly, instead, we refer to the lazy wrapper. This is created automatically by the `component$()` function.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\n\nexport const Child = component$(() => {\n return <p>child</p>;\n});\n\nexport const Parent = component$(() => {\n return (\n <section>\n <Child />\n </section>\n );\n});\n\nexport default Parent;\n```\n\nIn the above example the Optimizer transforms the above to:\n\n```tsx\nconst Child = componentQrl(qrl('./chunk-a', 'Child_onMount'));\nconst Parent = componentQrl(qrl('./chunk-b', 'Parent_onMount'));\nconst Parent_onMount = () => qrl('./chunk-c', 'Parent_onRender');\nconst Parent_onRender = () => (\n <section>\n <Child />\n </section>\n);\n```\n\nFor simplicity, not all of the transformations are shown; all resulting symbols are kept in the same file for succinctness.\n\nNotice that after the Optimizer transforms the code, the `Parent` no longer directly references `Child`. This is important because it allows the bundler (and tree shakers) to freely move the symbols into different chunks without pulling the rest of the application with it.\n\nSo what happens when the `Parent` component needs to render a `Child` component, but the `Child` component has not yet been downloaded? First, the `Parent` component renders its DOM like so.\n\n```html\n<main>\n <section>\n <!--qv--><!--/qv-->\n </section>\n</main>\n```\n\nAs you can see in the above example, the `<!--qv-->` acts as a marker where the `Child` component will be inserted once it is lazy-loaded.\n\n## Inline Components\n\nIn addition to the standard `component$()` with all of it's lazy-loaded\nproperties, Qwik also supports lightweight (inline) components that act more\nlike components in traditional frameworks.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\n\n// Inline component: declared using a standard function.\nexport const MyButton = (props: { text: string }) => {\n return <button>{props.text}</button>;\n};\n\n// Component: declared using `component$()`.\nexport default component$(() => {\n return (\n <p>\n Some text:\n <MyButton text=\"Click me\" />\n </p>\n );\n});\n```\n\nIn the above example, `MyButton` is an inline component.\nUnlike the standard `component$()`, inline components cannot be individually\nlazy-loaded; instead, they are bundled with their parent component. In this case:\n\n- `MyButton` will get bundled with the `default` component.\n- Whenever `default` is rendered, it will also guarantee that `MyButton` is\nrendered.\n\nYou can think of inline components as being inlined into the component where they are instantiated.\n\n### Limitations\nInline components come with some limitations that the standard `component$()`\ndoes not have. Inline components:\n- Cannot use `use*` methods such as `useSignal` or `useStore`.\n- Cannot project content with a `<Slot>`.\n\nAs the name implies, inline components are best used sparingly for\nlightweight pieces of markup since they offer the convenience of being\nbundled with the parent component.\n\n## Polymorphic components\n\nWhen you want to output a different type of element depending on props but default to a `<div>`, you can do it using something like this:\n\n```tsx\nconst Poly = component$(\n <C extends string | FunctionComponent = 'div'>({\n as,\n ...props\n }: { as?: C } & PropsOf<string extends C ? 'div' : C>) => {\n const Cmp = as || 'div';\n return (\n <Cmp {...props}>\n <Slot />\n </Cmp>\n );\n }\n);\n\nexport const TestComponent = component$(() => {\n // These all work with correct types\n return (\n <>\n <Poly>Hello from a div</Poly>\n <Poly as=\"a\" href=\"/blog\">\n Blog\n </Poly>\n <Poly as=\"input\" onInput$={(ev, el) => console.log(el.value)} />\n <Poly as={OtherComponent} someProp />\n </>\n );\n});\n```\n\nNote the `string extends C`, this is only true when TypeScript cannot infer the type from the `as` prop allowing you to specify the default type.\n\n## API Overview\n\n### State\n\n- [`useSignal(initialState)`](/docs/core/state.md#usesignal) - creates a signal with a value you can set\n- [`useStore(initialStateObject)`](/docs/core/state.md#usestore) - creates an object for grouped state; Qwik tracks its property reads and writes\n- [`useComputed$()`](/docs/core/state.md#usecomputed) - creates a signal with a value calculated (synchronously or asynchronously) from other values\n- [`createContextId(contextName)`](/docs/core/context.md#createcontext) - creates a context reference\n- [`useContextProvider()`](/docs/core/context.md#usecontextprovider) - provides a value to a given context\n- [`useContext()`](/docs/core/context.md#usecontext) - reads the value of the current context\n\n### Styles\n\n- [`useStylesScoped$()`](/docs/core/styles.md#usestylesscoped) - appends scoped styles to the component\n- [`useStyles$()`](/docs/core/styles.md#usestyles) - appends unscoped styles to the component\n\n### Events\n\n- [`useOn()`](/docs/core/events.md#useonwindowdocument-hook) - appends a listener to the current component programmatically\n- [`useOnWindow()`](/docs/core/events.md#useonwindowdocument-hook) - appends a listener to the window object programmatically\n- [`useOnDocument()`](/docs/core/events.md#useonwindowdocument-hook) - appends a listener to the document object programmatically\n\n### Tasks/Lifecycle\n\n- [`useTask$()`](/docs/core/tasks.md#usetask) - defines a callback that will be called before render and/or when a watched store changes\n- [`useVisibleTask$()`](/docs/core/tasks.md#usevisibletask) - defines a callback that will be called after rendering in the client only (browser)\n\n### Other\n\n- [`$()`](/docs/advanced/qrl.md) - creates a QRL\n- [`noSerialize()`](/docs/core/state.md#noserialize)\n- [`qwikVite()`](/docs/advanced/vite.md#qwikvite) - entry point for qwik with vite\n\n### Components\n\n- [`<Slot>`](/docs/core/slots.md) - declares a content projection slot\n- [`<Pending>`](/docs/labs/pending.md) - shows fallback UI while part of the page waits\n- [`<Catch>`](/api/qwik.md#catch) - renders a fallback when a descendant throws\n- `<SSRStreamBlock>` - declares a stream block\n- `<SSRStream>` - declares a stream\n- `<Fragment>` - declares a JSX fragment\n## See Also\n\n- [Inline components](/docs/core/overview.md#inline-components)\n"},{"id":"/docs/concepts/think-qwik/","title":"Think Qwik","description":"Mental model for resumability, lazy execution, and how Qwik differs from hydration-based frameworks.","url":"https://next.qwik.dev/docs/concepts/think-qwik/","content":"# Think Qwik\nIf you're coming from another reactive web framework such as Angular, React, Vue, Svelte or Solid, you are already familiar with the core Qwik concepts such as components and reactivity. You can learn more about the Qwik flavor [here](link).\n\nWhat makes Qwik different is a mechanism we call **javascript streaming**. Compared to the other reactive web frameworks which must execute all and thefore download all of the javascript code present or visible on a page in order to become interactive, Qwik has this unique ability to buffer javascript code bit by bit, prioritize the preloading of user events code and execution, and continuing to preload the rest of the code when idle.\n\nYou can think of it like how video streaming compares to downloading. Instead of having to wait for the download to complete before being able press play, users can start running the video most often right away, and they can jump to other parts of the video, which will resume instantly if the packets have already been buffered or only after a short delay if not. Except the difference with javascript streaming is that it's about avoiding executing code, and therefore the associated downloads.\n\n**The result:** TTI (Time To Interactive) is sped up significantly, now a constant O(1) in time instead of growing proportionally to the amount of code present on a page.\n\nThis means:\n - <u>More scalability</u>: there is theoretically no ceiling where you need to stop building features and start focusing on performance because your app is getting too big and too slow.\n - <u>Happier developers</u>: no need to learn how to optimize application performance, the framework handles it for you.\n - <u>Happier users</u>: The vast majority of users will never experience unresponsiveness, regardless of the network or device they're on, and will instead enjoy more features or better interfaces.\n\n## Concretely speaking\nModern websites require vast amounts of javascript to become interactive.\n\nIn a typical Qwik application, TTI normally takes only 3s on 4G and 6s on 3G. It is physically hard to get any faster in such network conditions, accounting for network roundtrip latencies and the time it takes to stream the fully server-side rendered html. Once all of the code has been preloaded, all user interactions are basically instant and you can use Cache Control strategies to speed up future user sessions as well as for offline usage.\n\nOn the other hand, TTI in the other reactive web frameworks will most often reach **at least** 6s or more on 4G, and 20s or more on 3G networks. It is not uncommon for bigger apps to reach even 60s or more on 3G. Such delays can easily be noticed by end users. They not only increase bounce rates and reduce conversion rates, but also degrade your brand image.\n\n> In the wild, TTI numbers for the other reactive web frameworks are hard to compare apples to apples as those depend on application size, code splitting, render and other optimization strategies.\n\n## How does it work?\n\nHistorically, reactive web frameworks were designed for CSR (Client Side Rendering). It is only later that they introduced SSR (Server Side Rendering) to show content to the user sooner.\n\nThe way they've achieved this is through a process called hydration, where the server generates and sends the html to the client, and then the client uses javascript to regenerate the tree and attach event listeners for a given page/section to be interactive.\n\nThe problem of this approach is that now the framework still has to execute all of the code for that page/section and therefore must also download all of it.\n\n> There are many strategies to optimize hydration, such as reducing what needs to be hydrated (avoiding the non-interactive parts) and/or hydrating only on a page by page or visible intersection by visible intersection basis. While these strategies can help, they introduce added complexity without fully solving the problem.\n>\n> When partially hydrating only the above the fold components for example, hydration will have to continue on user scroll or route change, introducing continued perceivable delays during the session lifetime. Another limitation of this approach is that it still needs to hydrate all the interactive components above the fold, which can still take a lot of time if there are many.\n\nInstead, Qwik has been designed with SSR as a first class citizen, supporting [out of order html streaming](link) and relying on the following 5 mechanisms to enable javascript streaming and constant O(1) TTI:\n - Fine grained Reactivity (a.k.a. signals)\n - Automatic code splitting (a.k.a. the optimizer)\n - State serialization (a.k.a. resumability)\n - Immediate user events registration (a.k.a. the qwikloader)\n - Buffered and on-demand module preloads (a.k.a. the preloader)\n\n> While Qwik applications do work with pure CSR, SSR is usually the preferred approach. With CSR, any web app (and even Qwik apps) must download the render functions in order to be able to generate the tree, slowing down TTI as the application grows.\n\n### Fine grained Reactivity (a.k.a. signals)\n\nReactive web frameworks are called reactive because they react on state changes. There are many ways to detect state changes, such as component re-renders, dirty-checking, proxies, observables, and signals.\n\nExcept for React, the industry (Angular, Vue, Svelte and Solid) has converged towards signals as the preferred way to handle reactivity.\n\nSignals are a push/pull mechanism that only update DOM nodes directly affected by a state change, without the need to re-render an entire sub-tree of components. It is more fine grained, does less work and is therefore faster than the other approaches.\n\nThis ability to propagate state changes outside of the component tree structure is key to javascript streaming as it allows preloading and executing only the code necessary for a given user interaction without pulling in parent or child code altogether.\n\nWithout fine-grained reactivity, a user interaction triggering a state change would require re-rendering entire sub-trees of components, which would force downloading and executing a lot of code all at once, introducing delays that would essentially reproduce a form of hydration.\n\n### Automatic code splitting and closure extraction (a.k.a. the optimizer)\n\nIn order to be able to stream anything, the code must first be split into small packets that can be sent independently. This is one of the core features of the Qwik optimizer. At build time through the `qwikVite` plugin, it analyzes the code and splits it into small chunks, keeping it reactive and attaching metadata to know which bundles are most likely to be requested first. Developers write code as they normally would and the optimizer takes care of the rest.\n\nUnder the hood, the optimizer relies on QRLs (Qwik Resource Locators), identified through the `$` signs present in the code to split it into separate segment chunks.\n\nFor example, when you write:\n\n```tsx title=\"counter.tsx\"\nexport default component$(() => {\n const count = useSignal(0);\n\n useTask$(({ track }) => {\n track(count);\n console.log('Count is now', count.value);\n });\n\n return <button onClick$={() => count.value++}>{count.value}</button>;\n});\n```\n\nin a .jsx or .tsx file, the optimizer will split the code into 3 separate chunks: one for the component render function itself, one for the click event listener and one for the visible task.\n\nThe outputs would look like this:\n\n```tsx title=\"./app.tsx_app_component_useTask_41mb3rLO0N0.js\"\nexport const s_41mb3rLO0N0 = ({ track }) => {\n const count = _capturesObj._[0];\n track(count);\n console.log('Count is now', count.value);\n};\n```\n\n```tsx title=\"./app.tsx_app_component_button_on_click_LToOrb0bX0M.js\"\nexport const s_LToOrb0bX0M = () => {\n const count = _capturesObj._[0];\n count.value++;\n};\n```\n\n```tsx title=\"component_qrl.tsx\"\nconst q_s_41mb3rLO0N0 = /*#__PURE__*/ qrl(()=>import(\"./app.tsx_app_component_useTask_41mb3rLO0N0.js\"), \"s_41mb3rLO0N0\");\nconst q_s_LToOrb0bX0M = /*#__PURE__*/ qrl(()=>import(\"./app.tsx_app_component_button_on_click_LToOrb0bX0M.js\"), \"s_LToOrb0bX0M\");\n//\nexport const s_QbmWc3TlyqA = () => {\n const count = useSignal(0);\n useTaskQrl(q_s_41mb3rLO0N0.w([\n count\n ]));\n return /*#__PURE__*/ _jsxSorted(\"button\", {\n \"q:p\": count\n }, {\n \"q-e:click\": q_s_LToOrb0bX0M\n }, _wrapProp(count), 7, \"ga_0\");\n};\n```\n\nAnd now thanks to fine-grained reactivity, all three QRLs can be preloaded and executed independently of one another.\n\nBy default, Qwik tries to avoid having too many bundles. After the `qwikVite` plugin transformations, it then leverages the bundler (Rollup/Rolldown) output options to group back segment chunks that belong together.\n\nFor example here, the `useTask$` will always run when `count.value` changes, so it makes sense to group the `onClick$` and the `useTask$` together in the same output chunk, while the render function can run entirely on its own thanks to fine grained reactivity (and won't even get shipped to the client when it runs during SSR).\n\n> For the most optimal bundling, the `qwikInsights` plugin can be used to analyze which bundles are used together at runtime.\n\n### State Serialization (a.k.a. resumability)\n\nState serialization allows Qwik applications to continue execution where the server left off.\n\nAll reactive frameworks need to keep track of application state. The current generation of frameworks does not preserve this information when transitioning from the server to the browser. As a result, the application state must be rebuilt in the browser, duplicating the work that was done on the server.\n\nOn the other hand, Qwik serializes listeners, internal data structures, and application state into the HTML during the server-browser handoff. Because all of the information is serialized in the html, the client can just resume execution where the server left off.\n\nUsing our counter.tsx example above, Qwik would serialize the click handler, reactive DOM nodes and state as follows:\n\n```html title=\"counter.html\"\n<body>\n <button q:p=\"0\" :=\"ga_0\" on:click=\"../handlers-DnDcryhk.js#_run#1\">\n 0\n </button>\n <!-- ... -->\n <script type=\"qwik/state\" :>\n \"[30,[0,0,40,[28,[9,\"2#3#0\",0,10,0,1,10,\"5A\"],0,\":\",3,1],40, ...]\"\n </script>\n <script type=\"qwik/vnode\" :>\n \"#!~{1<5@wQ_0`6^7[8=4}2!~{B`10=9}\"\n </script>\n</body>\n```\n\nWhen a user clicks on the button, the `on:click` handler would then reach out for the internal `handlers-DnDcryhk.js`'s `_run` function with the given argument (e.g. `1`), wich would in turn parse the `qwik/state` and `qwik/vnode` scripts to know which code to preload and execute. If the code has been preloaded already it will execute right away, otherwise it will be prioritized over other preloads and executed as soon as it is available.\n\n### Immediate User Events Registration (a.k.a. the qwikloader)\n\nThe qwikloader is a small script that is responsible for registering user events as soon as possible, even before any other code has been preloaded. This allows keeping track of user interactions until the code gets preloaded, for example incrementing a cart button by 3 if a user clicked on it 3 times.\n\n### Buffered and on-demand modulepreloads (a.k.a. the preloader)\n\nTo not compete with visual content loading (FCP & LCP), Qwik waits for the browser `load` event before initiating the streaming of javascript bundles. Once the `load` event fires, Qwik starts to buffer `<link rel=\"modulepreload\" href=\"...\" as=\"script\">` tags to speculatively preload the most likely code executed by the user.\n\nBy default a queue of idle preloads is set to a maximum of 25 simultaneous preloads through the [`maxIdlePreloads`](link). Preloads are therefore buffered in a queue of 25 until all bundles have been preloaded. If a user interaction happens during buffering, the preloader will append the corresponding bundles modulepreload link tags, bypassing the idle queue and starting to preload them right away.\n"},{"id":"/docs/concepts/resumable/","title":"Resumable","description":"Explains resumability and how Qwik serializes state and resumes without replaying components.","url":"https://next.qwik.dev/docs/concepts/resumable/","content":"# Resumable vs. Hydration\n\nA key concept of Qwik applications is that they are resumable from a server-side-rendered state. The best way to explain resumability is to understand how the current generation of frameworks are replayable (hydration).\n\nWhen an SSR/SSG application boots up on a client, it requires that the framework on the client restores three pieces of information:\n\n1. Listeners - locate event listeners and install them on the DOM nodes to make the application interactive.\n2. Component tree - build up an internal data structure representing the application component tree.\n3. Application state - restore any data that was fetched or saved in a `store` on the server.\n\nCollectively, this is known as hydration. All current generations of frameworks require this step to make the application interactive.\n\n[Hydration is expensive](https://www.builder.io/blog/hydration-is-pure-overhead) for two reasons:\n\n1. The frameworks have to download all of the component code associated with the current page.\n2. The frameworks have to execute the templates associated with the components on the page to rebuild the listener location and the internal component tree.\n\n![Resumable vs Hydration](https://cdn.builder.io/api/v1/image/assets%2FYJIGb4i01jvw0SRdL5Bt%2F04681212764f4025b2b5f5c6a258ad6e?format=webp&width=945)\n\nQwik is different because it does not require hydration to resume an application on the client. Not requiring hydration is what makes the Qwik application startup instantaneous.\n\nAll other frameworks' hydration **replays** all the application logic on the client. Qwik instead pauses execution on the server, and resumes execution on the client.\n\n## Introducing Resumability\n\nResumability is about pausing execution on the server and resuming execution on the client without having to replay and download all of the application logic.\n\nA good mental model is that Qwik applications at any point of their lifecycle can be serialized and moved to a different VM instance (server to browser). There, the application simply resumes where the serialization stopped. No hydration is required. Hence, Qwik applications don't hydrate; they resume.\n\nIn order to achieve this, Qwik needs to solve the 3 problems (listeners, component tree, application state) in a way that is compatible with a no-code startup.\n\n### Listeners\n\nDOM without event listeners is just a static page; it is not an application. Today's standard for all sites is quite a high level of interactivity, so even the most static-looking sites are full of event listeners. These include menus, hovers, expanding details, or even full-on interactive apps.\n\nExisting frameworks solve the event listener by downloading the components and executing their templates to collect event listeners that are then attached to the DOM. The current approach has these issues:\n\n1. Requires the template code to be eagerly downloaded.\n2. Requires template code to be eagerly executed.\n3. Requires the event handler code to be downloaded eagerly (to be attached).\n\nThe above approach does not scale. As the application becomes more complicated, the amount of code needed to download eagerly and execute grows proportionally with the size of the application. This negatively impacts the application startup performance and hence the user experience.\nIn other frameworks, lazy-loading chunks of the application becomes a development task in itself that consumes time and effort. In Qwik, lazy-loading is a natural consequence of the resumable architecture.\n\nQwik solves the above issue by serializing the event listeners into DOM like so:\n\n```html\n<button q-e:click=\"./chunk.js#handler_symbol\">click me</button>\n```\n\nQwik still needs to collect the listener information, but this step is done as part of the SSR/SSG. The results of SSR/SSG are then serialized into HTML so that the browser does not need to do anything to resume the execution. Notice that the `q-e:click` attribute contains all of the information to resume the application without doing anything eagerly.\n\n1. [Qwikloader](https://qwik.dev/docs/advanced/qwikloader/) sets up a single global listener instead of many individual listeners per DOM element. This step can be done with no application code present.\n2. The HTML contains a URL to the chunk and symbol name. The attribute tells Qwikloader which code chunk to download and which symbol to retrieve from the chunk and then to be executed.\n3. Finally, to make all of the above possible, Qwik's event processing implementation understands asynchronicity which allows it to lazy load closures automatically.\n\n### Component Trees\n\nFrameworks work with component trees. To that end, frameworks need a complete understanding of the component trees to know which components need to be rerendered and when. If you look into the existing framework SSR/SSG output, the component boundary information has been destroyed. There is no way of knowing where component boundaries are by looking at the resulting HTML. To recreate this information, frameworks re-execute the component templates and memoize the component boundary location. Re-execution is what hydration is. Hydration is expensive as it requires both the download of component templates and their execution.\n\nQwik collects [component boundary information](https://qwik.dev/docs/cheat/serialization/) as part of the SSR/SSG and then serializes that information into HTML. The result is that Qwik can:\n\n1. Rebuild the component hierarchy information without the component code actually being present. The component code can remain lazy.\n2. Qwik can do this lazily only for the components which need to be re-rendered rather than all upfront.\n3. Qwik collects relationship information between stores and components. This creates a subscription model that informs Qwik which components need to be re-rendered as a result of state change. The subscription information also gets serialized into HTML.\n\n### Application State\n\nExisting frameworks usually have a way of serializing the application state into HTML so that the state can be restored as part of hydration. In this way, they are very similar to Qwik. However, Qwik has state management more tightly integrated into the lifecycle of the components. In practice, this means that component can be delay-loaded independently from the state of the component. This is not easily achievable in existing frameworks because component props are usually created by the parent component. This creates a chain reaction. In order to restore component X, its parents need to be restored as well. Qwik allows any component to be resumed without the parent component code being present.\n\n#### Serialization\n\nThe simplest way to think about serialization is through `JSON.stringify`. However, JSON has several limitations. Qwik can overcome some limitations, but some can't be overcome, and they place limitations on what the developer can do. Understanding these limitations is important when building Qwik applications.\n\nLimitations of JSON which Qwik solves:\n\n- JSON produces a DAG. DAG stands for Directed Acyclic Graph, which means that the object which is being serialized can't have circular references. This is a big limitation because the application state is often circular. Qwik ensures that when the graph of objects gets serialized, the circular references get properly saved and then restored.\n- JSON can't serialize some object types. For example, DOM references, or Dates. Qwik's serialization format ensures that such objects can correctly be serialized and restored. Here is a list of types that can be serialized with Qwik:\n - DOM references\n - Promises (See [resources](../../core/resource/))\n - Function closures (if wrapped in QRL)\n - Dates\n - `URL` objects\n - `Map` and `Set` instances.\n\nLimitations of JSON that Qwik does not solve:\n\n- Serialization of classes (`instanceof` and prototype)\n - Although some built-in classes, such as [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL), [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) are supported.\n- Serialization of Streams.\n\nFor cases where serialization is not possible, code should run [on client only](https://qwik.dev/docs/core/lifecycle/#serverbrowser-only-task).\n\n### Writing applications with serializability in mind\n\nThe resumability capability of the framework must extend to resumability of the application as well. This means that the framework must provide mechanisms for the developer to express *components* and *entities* of the application in a way which can be serialized and then resumed (without re-bootstrapping). This necessitates that the application is written with resumability constraints in mind. It is simply not possible for developers to continue to write applications in a heap-centric way and expect that a better framework can somehow make up for this sub-optimal approach.\n\nDevelopers must write their applications in a DOM-centric way. This will require a change of behavior and retooling of web developers' skills. Frameworks need to provide guidance and APIs to make it easy for developers to write the applications in this way.\n\n### Other benefits of resumability\n\nThe most obvious benefit of using resumability is for server-side-rendering. However, there are secondary benefits:\n\n- Serializing existing PWA apps so that users don't lose context when they return to the application\n- Improved rendering performance because only changed components need to be re-rendered\n- Fine-grained lazy-loading\n- Decreased memory pressure, especially on mobile devices\n- Progressive interactivity of existing static websites\n"},{"id":"/docs/concepts/reactivity/","title":"Reactivity","description":"Covers signals, stores, and the fine-grained update model used by Qwik.","url":"https://next.qwik.dev/docs/concepts/reactivity/","content":"# Reactivity\n\nReactivity allows Qwik to track which components are subscribed to which state. This information enables Qwik to invalidate only the relevant component on state change, which minimizes the number of components that need to be re-rendered.\n\nWithout fine-grained reactivity, a state change would require re-rendering from the root component, which would force the whole component tree to be eagerly downloaded.\n\nIt's important to notice that Qwik does not do change detection like Angular. Instead, Qwik relies on signals to surgically update the component templates when the relevant state changes, without having to dirty-check the whole state.\n\n## Proxy\n\nReactivity requires that the framework keeps track of the relationship between the state of the application and the components. The framework must render the whole application at least once to build the reactivity graph. The build of this reactivity graph initially happens on the server and is serialized to HTML so that the browser can use the information without being forced to do a single pass through all components to rebuild the graph. (Qwik does not need to do hydration to register events or build up the reactivity graph).\n\nReactivity can be done in a few ways:\n\n1. Using explicit registration of listeners using `.subscribe()` (for example, RxJS)\n2. Using implicit registration using a compiler (for example, Svelte)\n3. Using implicit registration using proxies.\n\nQwik uses proxies for a few reasons:\n\n1. Using explicit registration such as `.subscribe()` would require the system to serialize all of the subscribed listeners to avoid hydration. Serializing subscribed closures would not be possible, as all the subscribe functions would have to be lazy-loaded and asynchronous (too expensive).\n2. Using the compiler to create graphs implicitly would work, but only for components. Intra component communications would still require `.subscribe()` methods and hence suffer the issues described above.\n\nBecause of the above constraints, Qwik uses proxies to keep track of the reactivity graph.\n\n- Use [`useStore()`](/docs/core/state.md#usestore) to create a store proxy.\n- The proxy notices the reads and creates subscriptions that are serializable.\n- The proxy notices the writes and uses the subscription information to invalidate the relevant components.\n\n## Counter Example\n\n```tsx\nexport const Counter = component$(() => {\n const store = useStore({ count: 0 });\n\n return <button onClick$={() => store.count++}>{store.count}</button>;\n});\n```\n\n1. The server performs an initial render of the component. The server rendering includes creating the proxy represented by `store`.\n2. The initial render invokes the OnRender method, which has a reference to the `store` proxy. The rendering puts the proxy in \"learn\" mode. During the build-up of JSX, the proxy observes a read of the `count` property. Because the proxy is in \"learn\" mode, it records that the text node inside `Counter` has a subscription on the `store.count`.\n3. The server serializes the state of the application into HTML. This includes the `store` as well as subscription information which says that the text node inside `Counter` is subscribed to `store.count`.\n4. In the browser, the user clicks the button. Because the click event handler closed over `store`, Qwik restores the store proxy. The proxy contains the application state (the count) and the subscription, which associates the text node inside `Counter` with `state.count`.\n5. The event handler increments the `store.count`. Because the `store` is a proxy, it notices the write and uses the subscription information to create a signal operation to update the text node inside `Counter`.\n6. After `requestAnimationFrame`, the signal value is reflected in the DOM by updating the text node's value to that of the signal.\n\n## Unsubscribe example\n\n```tsx\nexport const ComplexCounter = component$(() => {\n const store = useStore({ count: 0, visible: true });\n\n return (\n <>\n <button onClick$={() => (store.visible = !store.visible)}>\n {store.visible ? 'hide' : 'show'}\n </button>\n <button onClick$={() => store.count++}>increment</button>\n {store.visible ? <p>{store.count}</p> : null}\n </>\n );\n});\n```\n\nThis example is a more complicated counter.\n\n- It contains the `increment` button, which always increments `store.count`.\n- It contains a `show`/`hide` button which determines if the count is shown.\n\n1. On the initial render, the count is visible. Therefore the server creates a subscription that records that `ComplexCounter` needs to get re-rendered if either `store.count` or `store.visible` changes.\n2. If the user clicks on `hide`, the `ComplexCounter` rerenders. The re-rendering clears all of the subscriptions and records new ones. This time the JSX does not read `store.count`. Therefore, only `store.visible` gets added to the list of subscriptions.\n3. User clicking on `increment` will update `store.count`, but doing so will not cause the component to re-render. This is correct because the counter is not visible, so re-rendering would be a no-op.\n4. If the user clicks `show`, the component will re-render and this time the JSX will read both `store.visible` as well as `store.count`. The subscription list is once again updated.\n5. Now, clicking on `increment` updates the `store.count`. Because the count is visible, the `ComplexCounter` is subscribed to `store.count`.\n\nNotice how the set of subscriptions automatically updates as the component renders different branches of its JSX. The advantage of the proxy is that the subscriptions update automatically as the applications execute, and the system can always compute the smallest set of invalidated components.\n\n## Deep objects\n\nSo far, the examples show the store (`useStore()`) was a simple object with primitive values.\n\n```tsx\nexport const MyComp = component$(() => {\n const store = useStore({\n person: { first: null, last: null },\n location: null\n });\n\n store.location = {street: 'main st'};\n\n return (\n <section>\n <p>{store.person.last}, {store.person.first}</p>\n <p>{store.location.street}</p>\n </section>\n );\n})\n```\n\nIn the above examples, Qwik will automatically wrap child objects `person` and `location` into a proxy and correctly create subscriptions on all deep properties.\n\nThe wrapping behavior described above has one surprising side-effect. Writing and reading from a proxy auto wraps the object, which means that the identity of the object changes. This should normally not be an issue, but it is something that the developer should keep in mind.\n\n```tsx\nexport const MyComp = component$(() => {\n const store = useStore({ person: null });\n const person = { first: 'John', last: 'Smith' };\n store.person = person; // store.person auto wraps object into proxy\n\n if (store.person !== person) {\n // The consequence of auto wrapping is that the object identity changes.\n console.log('store auto-wrapped person into a proxy');\n }\n});\n```\n\n## Out-of-order rendering\n\nQwik components are rendered out of order. A component can be rendered without forcing a parent component to be rendered first or a child components to be rendered as a consequence of the component render. This is an important property of Qwik because it allows Qwik applications to only re-render components which have been invalidated due to a state change rather than re-rendering the whole component tree on a state change.\n\nWhen components are rendered, they need to have access to their props. Parent components create props. The props must be [serializable](/docs/concepts/resumable.md#serialization) for the component to render independently from the parent.\n\n## Invalidating child components\n\nWhen re-rendering a component, the child component's props either stay the same or are updated. A child component only invalidates if its props change.\n\n```tsx\nexport const Child = component$((props: { count: number }) => {\n return <span>{props.count}</span>;\n});\n\nexport const MyApp = component$(() => {\n const store = useStore({ a: 0, b: 0, c: 0 });\n\n return (\n <>\n <button onClick$={() => store.a++}>a++</button>\n <button onClick$={() => store.b++}>b++</button>\n <button onClick$={() => store.c++}>c++</button>\n {JSON.stringify(store)}\n\n <Child count={store.a} />\n <Child count={store.b} />\n </>\n );\n});\n```\n\nIn the above example, there are two `<Child/>` components.\n\n- Every time a button is clicked, one of the three counters is incremented. A change of counter state will cause the `MyApp` component to re-render on each click.\n- If `store.c` has been incremented, none of the child components get re-rendered. (And therefore, their code does not get lazy-loaded)\n- If `store.a` has been incremented, then only `<Child count={store.a}/>` will re-render.\n- If `store.b` has been incremented, then only `<Child count={store.b}/>` will re-render.\n\nNotice that the child components only re-render when their props change. This is an important property of Qwik applications as it significantly limits the amount of re-rendering the application must do on some state change. While less re-rendering has performance benefits, the real benefit is that large portions of the applications do not get downloaded if they don't need to be re-rendered.\n"},{"id":"/docs/advanced/dollar/","title":"The $ Dollar Sign","description":"Explains the `$` suffix transform, lazy boundaries, and serializable closures.","url":"https://next.qwik.dev/docs/advanced/dollar/","content":"# The dollar `$` sign\n\nQwik splits up your application into many small pieces we call symbols. A component can be broken up into many symbols, so a symbol is smaller than a component. The splitting up is performed by the [Qwik Optimizer](/docs/advanced/optimizer.md).\n\nThe `$` suffix is used to signal both the optimizer and the developer when this transformation occurs. As a developer, you need to understand that special rules apply whenever you see `$` (not all valid JavaScript is a valid Qwik Optimizer transform.)\n\n## Compiler-time implications\n\nThe [optimizer](/docs/advanced/optimizer.md) runs as a Vite plugin during bundling. The purpose of the Optimizer is to break up the application into many small lazy-loadable chunks. The Optimizer moves expressions (usually functions) into new files and leaves behind a reference pointing to where the expression was moved from.\n\nThe `$` tells the optimizer which functions to extract into a separate file and which ones to leave untouched. The optimizer does not keep an internal list of magic functions, instead, it solely relies on the `$` suffix to know which functions to transform. The system is extendable and developers can create their own `$` functions, such as `myCustomFunction$()`.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n console.log('render');\n return <button onClick$={() => console.log('hello')}>Hello Qwik</button>;\n});\n```\n\nThe component above is split into multiple chunks thanks to the `$` syntax:\n\n```js title=\"app.js\"\nimport { componentQrl, qrl } from '@qwik.dev/core';\n\nconst App = /*#__PURE__*/ componentQrl(\n qrl(() => import('./app_component_akbu84a8zes.js'), 'App_component_AkbU84a8zes')\n);\n\nexport { App };\n```\n\n```js title=\"app_component_akbu84a8zes.js\"\nimport { jsx as _jsx } from '@qwik.dev/core/jsx-runtime';\nimport { qrl } from '@qwik.dev/core';\nexport const App_component_AkbU84a8zes = () => {\n console.log('render');\n return /*#__PURE__*/ _jsx('button', {\n onClick$: qrl(\n () => import('./app_component_button_onclick_01pegc10cpw'),\n 'App_component_button_onClick_01pEgC10cpw'\n ),\n children: 'Hello Qwik',\n });\n};\n```\n\n```js title=\"app_component_button_onclick_01pegc10cpw.js\"\nexport const App_component_button_onClick_01pEgC10cpw = () => console.log('hello');\n```\n\n## Rules\n\nThe Optimizer uses `$` as a signal to extract the code. The developer needs to understand that the extraction comes with constraints and therefore special rules apply whenever the `$` is present. (Not all valid JavaScript code is valid code for the Optimizer.)\n\nThe worst kind of code magic is the kind that's invisible to the developer.\n\n### Allowed expressions\n\nThe first argument of any function that ends with `$` has certain restrictions:\n\n#### Literals without local identifiers\n\n```tsx\nconst bar = 'bar';\nconst foo = 'foo';\n\n// Invalid expressions\nfoo$({ value: bar }); // it contains a local identifier \"bar\"\nfoo$(`Hello, ${bar}`); // it contains a local identifier \"bar\"\nfoo$(count + 1); // it contains a local identifier \"count\"\nfoo$(foo); // foo is not exported, so it's not importable\n\n// Valid expressions\nfoo$(`Hello, bar`); // string literal without local identifiers\nfoo$({ value: 'stuff' }); // object literal without local identifiers\nfoo$(1 + 3); // expression without local identifiers\n```\n\n#### Importable identifiers\n\n```tsx\n// Invalid\nconst foo = 'foo';\nfoo$(foo); // foo is not exported, so it's not importable\n\n// Valid\nexport const bar = 'bar';\nfoo$(bar);\n\n// Valid\nimport { bar } from './bar';\nfoo$(bar);\n```\n\n#### Closures\n\nFor closures, the rules are a bit relaxed, and local identifiers can be referenced and captured.\n\n**Closure Capture Rule**\n\nIf a function lexically captures a variable (or parameter), that variable must be:\n\n1. a `const` and\n2. the value must be serializable.\n\n##### Captured variables must be declared as a `const`.\n\n**Invalid**\n\n```tsx\ncomponent$(() => {\n let foo = 'value'; // variable is not a const\n return <div onClick$={() => console.log(foo)}/>\n});\n```\n\n**Valid**\n\n```tsx\ncomponent$(() => {\n const foo = 'value';\n return <div onClick$={() => console.log(foo)}/>\n});\n```\n\n##### Local captured variables must be serializable\n\n```tsx\n// Invalid\ncomponent$(() => {\n const foo = new MyCustomClass(12); // MyCustomClass is not serializable\n return <div onClick$={() => console.log(foo)}/>\n});\n\n// Valid\ncomponent$(() => {\n const foo = { data: 12 };\n return <div onClick$={() => console.log(foo)}/>\n});\n```\n\n##### Module-declared variables can be importable\n\nIf a function that is being extracted by the Optimizer refers to a top-level symbol, that symbol must either be imported or exported.\n\n```tsx\n// Invalid\nconst foo = new MyCustomClass(12);\ncomponent$(() => {\n // Foo is declared at the module level, but it's not exported\n console.log(foo);\n});\n\n// Valid\nexport const foo = new MyCustomClass(12);\ncomponent$(() => {\n console.log(foo);\n});\n\n// Valid\nimport { foo } from './foo';\ncomponent$(() => {\n console.log(foo);\n});\n```\n\n##### Module-level variables cannot be mutated after extraction\n\nReading an exported module-level variable from an extracted closure works, since the Optimizer turns the reference into an `import`. Assigning to it does not: `import` bindings are read-only, so mutating one from inside the extracted closure fails at build time.\n\n```tsx\n// Invalid\nexport let count = 0;\ncomponent$(() => {\n return <button onClick$={() => count++}>{count}</button>; // count becomes an import; count++ fails\n});\n```\n\nA non-exported module-level `let` doesn't hit this error, but it's not safe either: the Optimizer duplicates the declaration into each chunk that references it, so every chunk mutates its own independent copy instead of shared state.\n\nWrap the read and the write in their own exported functions in a separate module instead of mutating the binding directly:\n\n```tsx title=\"counter.ts\"\nlet count = 0;\nexport const getCount = () => count;\nexport const incrementCount = () => count++;\n```\n\n```tsx\n// Valid\nimport { getCount, incrementCount } from './counter';\n\ncomponent$(() => {\n return <button onClick$={() => incrementCount()}>{getCount()}</button>;\n});\n```\n\nIf the state needs to be reactive or scoped per component instance, use a [signal](/docs/core/state.md) instead of a module-level variable.\n\n## Deep dive\n\nLet's look at the hypothetical problem of acting on a scroll event. You may be tempted to write the code like so:\n\n```tsx\nfunction onScroll(fn: () => void) {\n document.addEventListener('scroll', fn);\n}\nonScroll(() => alert('scroll'));\n```\n\nThe problem with this approach is that the event handler is eagerly loaded, even if the scroll event never triggers. What is needed is a way to refer to code in a lazy loadable way.\n\nThe developer could write:\n\n```tsx\nexport scrollHandler = () => alert('scroll');\n\nonScroll(() => (await import('./some-chunk')).scrollHandler());\n```\n\nThis works but is a lot of work. The developer is responsible for putting the code in a different file and hard coding the chunk name. Instead, we use the Optimizer to perform the work for us automatically. But we need a way to tell the Optimizer that we want to perform such a refactoring. We use `$()` as a marker function for this purpose.\n\n```tsx\nfunction onScroll(fnQrl: QRL<() => void>) {\n document.addEventListener('scroll', async () => {\n const fn = await fnQrl.resolve();\n fn();\n });\n}\n\nonScroll($(() => alert('scroll')));\n```\n\nThe Optimizer will generate:\n\n```tsx\nonScroll(qrl('./chunk-a.js', 'onScroll_1'));\n```\n\n```tsx title=\"chunk-a.js\"\nexport const onScroll_1 = () => alert('scroll');\n```\n\n1. All that the developer had to do was to wrap the function in the `$()` to signal to the Optimizer that the function should be moved to a new file and therefore be lazy-loaded.\n2. The `onScroll` function had to be implemented slightly differently as it needs to take into account the fact that the `QRL` of the function needs to be loaded before it can be used. In practice using `QRL.resolve()` is rare in Qwik applications as the Qwik framework provides higher-level APIs that rarely expect the developer to work with `QRL.resolve()` directly.\n\nHowever, wrapping code in `$()` is a bit inconvenient. For this reason, one can use `implicit$FirstArg()` to automatically perform the wrapping and type matching of the function taking the `QRL`. The function passed into `implicit$FirstArg()` should have a suffix of `Qrl`, and the result of that function should be set to a value with a suffix of `$`;\n\n```tsx\nconst onScroll$ = implicit$FirstArg(onScrollQrl);\n\nonScroll$(() => alert('scroll'));\n```\n\nNow the developer has an easy syntax for expressing that a particular function should be lazy-loaded.\n\n## Symbol extraction\n\nAssume that you have this code:\n\n```tsx\nexport const MyComp = component$(() => {\n /* my component definition */\n});\n```\n\nThe Optimizer breaks the code up into two files:\n\nThe original file:\n\n```tsx\nconst MyComp = component(qrl('./chunk-a.js', 'MyComp_onMount'));\n```\n\nand a chunk\n\n```tsx title=\"chunk-a.js\"\nexport const MyComp_onMount = () => {\n /* my component definition */\n};\n```\n\nThe result of Optimizer is that the `MyComp`'s `onMount` method was extracted into a new file. There are a few benefits to doing this:\n\n- A Parent component can refer to `MyComp` without pulling in `MyComp` implementation details.\n- The application now has more entry points, giving the bundler more ways to chunk up the codebase.\n\n## Capturing the lexical scope\n\nThe Optimizer extracts expressions (usually functions) into new files and leaves behind a `QRL` pointing to the lazy-loaded location.\n\nLet's look at a simple case:\n\n```tsx\nexport const Greeter = component$(() => {\n return <div>Hello World!</div>;\n});\n```\n\nthis will result in:\n\n```tsx\nconst Greeter = component(qrl('./chunk-a.js', 'Greeter_onMount'));\n```\n\n```tsx title=\"chunk-a.js\"\nconst Greeter_onMount = () => {\n return qrl('./chunk-b.js', 'Greeter_onRender');\n};\n```\n\n```tsx title=\"chunk-b.js\"\nconst Greeter_onRender = () => <span>Hello World!</span>;\n```\n\nThe above is for simple cases where the extracted function closure does not capture any variables. Let's look at a more complicated case where the extracted function closure lexically captures variables.\n\n```tsx\nexport const Greeter = component$((props: { name: string }) => {\n const salutation = 'Hello';\n\n return (\n <div>\n {salutation} {props.name}!\n </div>\n );\n});\n```\n\nThe naive way to extract functions will not work.\n\n```tsx\nconst Greeter = component(qrl('./chunk-a.js', 'Greeter_onMount'));\n```\n\n```tsx title=\"chunk-a.js\"\nconst Greeter_onMount = (props) => {\n const salutation = 'Hello';\n return qrl('./chunk-b.js', 'Greeter_onRender');\n};\n```\n\n```tsx title=\"chunk-b.js\"\nconst Greeter_onRender = () => (\n <div>\n {salutation} {props.name}!\n </div>\n);\n```\n\nThe issue can be seen in `chunk-b.js`. The extracted function refers to `salutation` and `props`, which are no longer in the lexical scope of the function. For this reason, the generated code must be slightly different.\n\n```tsx title=\"chunk-a.js\"\nconst Greeter_onMount = (props) => {\n const salutation = 'Hello';\n return qrl('./chunk-b.js', 'Greeter_onRender', [salutation, props]);\n};\n```\n\n```tsx title=\"chunk-b.js\"\nconst Greeter_onRender = () => {\n const [salutation, props] = useLexicalScope();\n\n return (\n <div>\n {salutation} {props.name}!\n </div>\n );\n};\n```\n\nNotice two changes:\n\n1. The `QRL` in `Greeter_onMount` now stores the `salutation` and `props`. This performs the role of capturing the constants inside closures.\n2. The generated closure `Greeter_onRender` now has a preamble which restores the `salutation` and `props` (`const [salutation, props] = useLexicalScope()`.)\n\nThe ability for the Optimizer (and Qwik runtime) to capture lexically scoped constants significantly improves which functions can be extracted into lazy-loaded resources. It is a powerful tool for breaking up complex applications into smaller lazy-loadable chunks.\n"},{"id":"/docs/advanced/qrl/","title":"QRL","description":"Deep dive into QRLs, how lazy references are encoded, and how symbols are resumed on demand.","url":"https://next.qwik.dev/docs/advanced/qrl/","content":"# QRL\n\nQRL (Qwik URL) is a particular form of URL that Qwik uses to lazy load content.\n\nQRLs:\n\n- are specially formatted URLs that are left as attributes in the HTML to tell Qwik where the handlers for the code should be loaded from.\n- point to a JavaScript chunk to be lazy-loaded.\n- Contain a symbol name which needs to be retrieved from the chunk.\n- May contain lexically scoped object references. (Captured variables from closures.)\n- If relative, use `q:base` for resolution.\n\n## QRL Encoding\n\n```\n./path/to/chunk.js#SymbolName\n```\n\nIn its simplest form, the QRL contains a URL (such as `./path/to/chunk.js`) that the browser can use to lazy-load a resource, and a `SymbolName` to retrieve from the lazy-loaded chunk.\n\nQwik uses `q:base` to resolve a QRL into an absolute URL if the URL is relative. (If no `q:base` attribute is present, then `document.baseURI` is used as a base.)\n\n## Encoding lexically scoped captured variables\n\nQRLs can also restore lexically scoped variables. In that case, the variables are encoded in the QRL at the end in the form of an array of indexes into the `q:obj` attribute.\n\n```\n./path/to/chunk.js#SymbolName[0,1]\n```\n\nThe array is used by `useLexicalScope()` to restore the variables.\n\n### Example\n\nLet's look at an example of how all of the pieces of the QRL tie together.\n\nThe developer writes code for a simple component.\n\n```tsx\nexport const Counter = component$((props: { step: number }) => {\n const count = useSignal(0);\n\n return <button onClick$={() => (count.value += props.step || 1)}>{count.value}</button>;\n});\n```\n\nThe optimizer breaks above code into pieces like so:\n\n```tsx\nconst Counter = component(qrl('./chunk-a.js', 'Counter_onMount'));\n```\n\n```tsx title=\"chunk-a.js\"\nexport const Counter_onMount = (props) => {\n const count = useSignal(0);\n return qrl('./chunk-b.js', 'Counter_onRender', [count, props]);\n};\n```\n\n```tsx title=\"chunk-b.js\"\nconst Counter_onRender = () => {\n const [count, props] = useLexicalScope();\n return (\n <button onClick$={qrl('./chunk-c.js', 'Counter_onClick', [count, props])}>{count.value}</button>\n );\n};\n```\n\n```tsx title=\"chunk-c.js\"\nconst Counter_onClick = () => {\n const [count, props] = useLexicalScope();\n return (count.value += props.step || 1);\n};\n```\n\n### Rendered HTML\n\nAfter the above code gets executed, it produces this HTML.\n\nAssume: `http://localhost/index.html`\n\n```html\n<html>\n <body q:base=\"/build/\">\n <button q:obj=\"456, 123\" q-e:click=\"./chunk-c.js#Counter_onClick[0,1]\">0</button>\n <script>\n /*Qwikloader script*/\n </script>\n <script type=\"qwik/json\">\n {...json...}\n </script>\n </body>\n</html>\n```\n\nThe main thing to note is the `q-e:click` attribute. This attribute gets read by the Qwikloader when the user clicks on the button.\n\n1. HTML is loaded in the browser, and Qwikloader registers a global `click` listener. No other JavaScript is loaded/executed at this point.\n2. User clicks on the `<button>`. This fires a `click` event which bubbles up and is handled by the Qwikloader.\n3. Qwikloader retraces the event bubble path and looks for `q-e:click` attribute, which it finds on `<button>`.\n4. Qwikloader now tries to load the corresponding chunk. To do that, the Qwikloader needs to resolve the relative path of `./chunk-c.js`. It uses these values to build an absolute path starting at `<button>` and walking towards the document.\n - `q-e:click=\"./chunk-c.js#Counter_onClick[0,1]\"`\n - `<body q:base=\"/build/\">`\n - `document.baseURI = \"http://localhost/index.html\"`\n - The resulting absolute URL is `http://localhost/build/chunk-c.js` which Qwikloader fetches.\n5. Qwikloader now retrieves the `Counter_onClick` reference from `http://localhost/build/chunk-c.js` and invokes it.\n ```tsx\n const Counter_onClick = () => {\n const [count, props] = useLexicalScope();\n return (count.value += props.step || 1);\n };\n ```\n6. At this point, the execution is handed off from Qwikloader to the lazy-loaded chunk. This is done so that the Qwikloader can be as small as possible as it is inlined into the HTML.\n7. `useLexicalScope` is imported from `@qwik.dev/core` and is responsible for retrieving the `count` and `props`.\n `const [count, props] = useLexicalScope();`\n8. Parse the `<script type=\"qwik/json\">{...json...}</script>` JSON and distribute the deserialized objects per `q:obj` attribute. In our case\n - `<div q:id=\"123\" q:obj=\"456\" q:host>` gets object with id `123`. This will be the `count` created in the `Counter_onMount` function.\n - `<button q:obj=\"456, 123\"` gets `count` as well as a reference to the `<div q:id=\"457\">`\n9. Once the `qwik/json` is deserialized, `useLexicalScope` can use the QRL's `[0,1]` array to look into `q:obj=\"456, 123\"` to retrieve object with id `456` and `123`, which are props of `<div q:id=\"123\" q:obj=\"456\" q:host>` as well as `store` from `Counter_onMount` function.\n\nFor performance reasons the `q:obj` and `` are only updated when the application is deserialized into HTML. When the application is running, these attributes may have stale values.\n\n## Why not just dynamic `import()`?\n\nBrowsers already have dynamic import mechanisms available from `import()`. Why not use that instead of inventing a new QRL format?\n\nThere are several reasons:\n\n1. For Qwik to work, the QRLs need to be serialized into HTML. This is problematic for dynamic `import()` because there is no easy way to retrieve the relative URL from the `import('./some-path.js')` so that it can be placed in the HTML.\n2. Dynamic imports deal with chunks, but they have no mechanism to refer to a specific symbol in the chunk.\n3. Dynamic imports have relative paths to the file which imported it. This is a problem because when the relative path is placed in HTML, it loses the context which defines relative to what. When the framework reads the path from HTML and tries to import it as `import(element.getAttribute('q-e:click'))`, the framework will become the context for relative path resolution. This is wrong as the original context before serialization to the HTML was different.\n4. QRLs encode information about the lexically scoped variables that were captured in the closure and need to be restored.\n5. Dynamic import requires that the developer writes `import('./file-a.js')`, which means the developer is in charge of deciding where the lazy-loaded boundaries are. This limits the ability of the tooling to move code around in an automated way.\n\nBecause of the above differences, Qwik introduces QRLs as a mechanism for lazy loading closures into a Qwik application.\n\n## See Also\n\n- [`qrl`: API used to create QRLs.](https://qwik.dev/api/qwik/#qrl)\n"},{"id":"/docs/advanced/optimizer-hints/","title":"Optimizer Hints","description":"Documents optimizer suppression hints like `@qwik-disable-next-line` and when to use named diagnostics sparingly.","url":"https://next.qwik.dev/docs/advanced/optimizer-hints/","content":"# Optimizer Hints\n\nQwik supports an inline optimizer directive named `@qwik-disable-next-line`.\n\nUse it to suppress a specific optimizer diagnostic for the next line of code, similar to how `eslint-disable-next-line` works.\n\n## Syntax\n\nAdd the directive in a comment immediately before the line you want to suppress:\n\n```tsx\n{/* @qwik-disable-next-line rule-name */}\n```\n\nYou can also disable more than one rule by separating them with commas:\n\n```tsx\n{/* @qwik-disable-next-line rule-one, rule-two */}\n```\n\nThe directive only applies to the next physical line.\n\n## Example\n\nThe optimizer warns when `preventdefault:*` is combined with `passive:*` for the same event, because passive listeners cannot call `preventDefault()`.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\n\nexport const App = component$(() => {\n return (\n <div>\n {/* @qwik-disable-next-line preventdefault-passive-check */}\n <button passive:click preventdefault:click onClick$={() => {}}>\n click\n </button>\n </div>\n );\n});\n```\n\nIn this example, the optimizer suppresses the `preventdefault-passive-check` diagnostic for that button.\n\n## When to use it\n\nUse `@qwik-disable-next-line` sparingly.\n\nIt is most useful when:\n\n- you understand why the optimizer is warning\n- the warning is intentional in your codebase\n- you want to suppress a single known case without affecting nearby code\n\nThe directive is consumed by the optimizer and removed from the generated output.\n\n## Choosing a rule name\n\nUse the rule name documented for the optimizer diagnostic you want to suppress.\n\nFor example:\n\n- `preventdefault-passive-check`\n\nIf a diagnostic does not document a named optimizer rule, it should not be treated as something to routinely suppress.\n"},{"id":"/docs/advanced/worker/","title":"Web Workers","description":"Explains `worker$()`, when to use browser Web Workers, and what data can be passed to worker functions.","url":"https://next.qwik.dev/docs/advanced/worker/","content":"# `worker$()`\n\nA Web Worker lets the browser run JavaScript away from the main UI thread. This is useful when a\ncalculation is large enough that it could make clicks, typing, scrolling, or animations feel stuck.\n\n`worker$()` is Qwik's way to run one of your functions in a worker. You write a normal function and\nwrap it with `worker$()`.\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { worker$ } from '@qwik.dev/core/worker';\n\nconst incrementInWorker = worker$((count: number) => count + 1);\n\nexport default component$(() => {\n const count = useSignal(0);\n\n return (\n <button\n onClick$={async () => {\n count.value = await incrementInWorker(count.value);\n }}\n >\n Count: {count.value}\n </button>\n );\n});\n```\n\n`worker$()` returns a QRL function. Calling it always returns a promise, so you can use `await`,\n`.then()`, or any other promise flow that fits your code.\n\n## What to Put in a Worker\n\nUse `worker$()` for work that is expensive enough to move out of the UI path:\n\n- parsing or formatting large data\n- compression, hashing, or encoding\n- image, text, or number processing\n- calculations that would otherwise make the page feel unresponsive\n\nSmall operations are usually better left inline. Sending data to a worker and getting a response back\nhas a cost, so `worker$()` is most useful when the work itself is meaningfully heavier than that cost.\n\n## Passing Data\n\nPass data that Qwik can serialize to worker functions. This follows the same\n[serialization boundary rules](/docs/guides/serialization.md) as other Qwik\nQRLs.\n\n```tsx\nimport { worker$ } from '@qwik.dev/core/worker';\n\nconst formatMessage = worker$((name: string, count: number) => {\n return `${name}:${count}`;\n});\n\nformatMessage('qwik', 2).then((result) => {\n console.log(result);\n});\n```\n\nReturn values should also be serializable by Qwik.\n\n## Events and Forms\n\nBrowser event objects and DOM nodes should not be sent to a worker. Read the data you need from the\nevent first, then pass that data to the worker.\n\nFor form submissions, Qwik helps by converting a form `SubmitEvent` into `FormData` before it reaches\nthe worker.\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { worker$ } from '@qwik.dev/core/worker';\n\nconst parseValue = worker$((value: string) => Number(value));\n\nexport default component$(() => {\n const count = useSignal(0);\n\n return (\n <input\n onInput$={async (_, target) => {\n count.value = await parseValue(target.value);\n }}\n />\n );\n});\n```\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { worker$ } from '@qwik.dev/core/worker';\n\nconst submitInWorker = worker$((data: FormData) => {\n return `${data.get('name')}:${data.get('count')}`;\n});\n\nexport default component$(() => {\n const result = useSignal('pending');\n\n return (\n <form\n preventdefault:submit\n onSubmit$={async (event) => {\n result.value = await submitInWorker(event);\n }}\n >\n <input name=\"name\" value=\"qwik\" />\n <input name=\"count\" value=\"2\" />\n <button type=\"submit\">Submit to worker</button>\n <p>{result.value}</p>\n </form>\n );\n});\n```\n\n## Setup\n\nNo manual `new Worker()` setup is needed when using the Qwik Vite plugin. Import `worker$()` from\n`@qwik.dev/core/worker`, define the worker function, and call it from your component, event handler,\ntask, or other Qwik code.\n\n## Server-side Rendering\n\n`worker$()` is mainly useful to think about as a browser Web Worker API. During SSR, Qwik can also\noffload worker functions when worker support is available. If workers are not available in the\ncurrent runtime, Qwik invokes the QRL directly instead.\n\n## Things to Remember\n\n- Worker functions return promises.\n- Pass data, not DOM nodes.\n- Keep arguments and return values serializable.\n- Prefer `worker$()` for expensive work, not tiny calculations.\n- Avoid browser-only globals inside the worker function.\n\n## API Reference\n\n- [`worker$()` API](/api/qwik-worker.md#worker_)\n- [`workerQrl()` API](/api/qwik-worker.md#workerqrl)\n"},{"id":"/docs/core/state/","title":"State","description":"Reference for signals, stores, computed values, async state, and related reactive primitives.","url":"https://next.qwik.dev/docs/core/state/","content":"# State\n\nApplications need to keep track of values that change over time. In Qwik, those values usually fall into two groups:\n\n1. Plain data: serializable values like strings, numbers, objects, and arrays.\n2. Reactive state: values that trigger UI updates where they are used. Create it with `useSignal()` or `useStore()`.\n\nState in Qwik does not have to live inside one component. Any component can create state, and that state can be shared with other parts of the app.\n\n## `useSignal()`\n\nA <a href=\"https://www.builder.io/blog/usesignal-is-the-future-of-web-frameworks\" target=\"_blank\" rel=\"noopener noreferrer\">reactive signal</a> is an object with a single `.value` property.\n\nWhen `.value` changes, Qwik updates the components that use it.\n\n```tsx {4} /count/\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const count = useSignal(0);\n\n return (\n <button onClick$={() => count.value++}>\n Increment {count.value}\n </button>\n );\n});\n```\n\nIn this example, `count` is a signal. Clicking the button updates `count.value`, and Qwik updates the button text automatically.\n\n**Passing signals to child components**\n\nBoth `.value` and the signal object can be passed as props.\n\nPass `.value` when the child only needs the current value. Pass the signal object when the child should be able to read and update the value, or when the prop is typed as `Signal<T>`.\n\n**Current value only:**\n\n```tsx\nconst isClosed = useSignal(false);\n\nreturn <Child isClosed={isClosed.value} />;\n```\n\nThis passes the current boolean value.\n\n**Pass the signal object:**\n\n```tsx\nconst isClosed = useSignal(false);\n\nreturn <Child isClosed={isClosed} />;\n```\n\nThis passes the signal object, so the child can read and update `isClosed.value`.\n\n## `useConstant()`\n\n`useConstant()` stores a value for the lifetime of the component. Subsequent calls always return the first value.\n\nIf you pass a function, Qwik invokes it **once** to compute the value (you can also pass extra arguments to that function). The result is not reactive — use `useSignal()` or `useStore()` when the UI should update.\n\n```tsx\nimport { component$, useConstant } from '@qwik.dev/core';\n\nexport default component$(() => {\n // function form: invoked once\n const id = useConstant(() => Math.random());\n // value form: retained as-is\n const config = useConstant({ theme: 'dark' });\n\n return (\n <p>\n id={id}, theme={config.theme}\n </p>\n );\n});\n```\n\n## `useStore()`\n\nA store is similar to a signal, but for an entire object instead of a single `.value` property.\n\nPass an initial object, or a function that returns one. Qwik tracks reads and writes to the object's properties. By default, nested objects and arrays are also tracked.\n\n```tsx {4} /count/#a /name/\nimport { component$, useStore } from '@qwik.dev/core';\n\nexport default component$(() => {\n const state = useStore({ count: 0, name: 'Qwik' });\n\n return (\n <>\n <button onClick$={() => state.count++}>Increment</button>\n <p>Count: {state.count}</p>\n <input\n value={state.name}\n onInput$={(_, el) => (state.name = el.value)}\n />\n <p>Name: {state.name}</p>\n </>\n );\n});\n```\n\n**Avoid destructuring store properties**\n\nKeep the store object, not destructured values.\n\n```tsx\nconst state = useStore({ count: 0 });\n\n// Good: Qwik can track this property.\nstate.count++;\n\n// Avoid: `count` is just a local variable now.\nconst { count } = state;\n```\n\nIf you destructure a store property, Qwik cannot track writes to that local variable.\n\n### Nested objects and arrays\n\nBy default, a store also tracks objects and arrays inside it:\n\n```tsx\nimport { component$, useStore } from '@qwik.dev/core';\n\nexport default component$(() => {\n const store = useStore({\n nested: {\n fields: { are: 'also tracked' },\n },\n list: ['Item 1'],\n });\n\n return (\n <>\n <p>{store.nested.fields.are}</p>\n <button\n onClick$={() => {\n // Updating a nested property updates the UI.\n store.nested.fields.are = 'tracked';\n }}\n >\n Update nested field\n </button>\n <br />\n <button\n onClick$={() => {\n // Updating an array also updates the UI.\n store.list.push(`Item ${store.list.length + 1}`);\n }}\n >\n Add to list\n </button>\n <ul>\n {store.list.map((item, key) => (\n <li key={key}>{item}</li>\n ))}\n </ul>\n </>\n );\n});\n```\n\nNested tracking is convenient, but it can add overhead for large objects. If you only need to track top-level properties, pass `{ deep: false }`:\n\n```tsx\nconst shallowStore = useStore(\n {\n nested: {\n fields: { are: 'not tracked deeply' }\n },\n count: 0,\n },\n { deep: false }\n);\n```\n### Store methods\n\nStores can include methods. Use `$()` so the method can be serialized, and use the `function` keyword when the method needs JavaScript's `this` keyword.\n\n```tsx\nimport { $, component$, useStore, type QRL } from '@qwik.dev/core';\n\ntype CountStore = {\n count: number;\n increment: QRL<(this: CountStore) => void>;\n};\n\nexport default component$(() => {\n const state = useStore<CountStore>({\n count: 0,\n increment: $(function (this: CountStore) {\n this.count++;\n }),\n });\n\n return (\n <>\n <button onClick$={() => state.increment()}>Increment</button>\n <p>Count: {state.count}</p>\n </>\n );\n});\n```\n\n**Why use the function keyword?**\n\nThis example uses `this.count` to update the store. Use the `function` keyword here so <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this\" target=\"_blank\" rel=\"noopener noreferrer\">`this`</a> points to the store.\n\n## Computed values\n\nSometimes you do not need to store state directly. You can calculate it from existing state, or resolve it from async work.\n\n`useComputed$()` creates a signal for those values. The calculation can be synchronous, such as formatting a name, or asynchronous, such as fetched data or Web Worker output. Qwik automatically tracks every signal and store the function reads and re-runs it when they change (in async functions, reads after the first `await` need [`track()`](#async-computed-values)).\n\nIf you do not need a new signal, try [`useTask$()`](/docs/core/tasks.md#usetask) instead. A task runs code during component setup or when tracked state changes, and you write any result to existing state yourself.\n\n### `useComputed$()`\n\nCreate a signal for a value that is calculated from other state.\n\nQwik keeps the result and runs the function again only when one of the signals it reads changes. The function can be synchronous (shown here) or asynchronous (see [Async computed values](#async-computed-values) below).\n\n```tsx {5} /useComputed$/\nimport { component$, useComputed$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const name = useSignal('Qwik');\n const upperName = useComputed$(() => {\n // Runs again when name.value changes.\n return name.value.toUpperCase();\n });\n\n return (\n <>\n <input type=\"text\" bind:value={name} />\n <p>Name: {name.value}</p>\n <p>Uppercase name: {upperName.value}</p>\n </>\n );\n});\n```\n\nYou do not need to list dependencies for `useComputed$()`. Qwik automatically tracks the signals read inside the function.\n\n#### Async computed values\n\nThe function passed to `useComputed$()` can be `async` (or return a Promise), for values that come from fetching data, calling `server$()`, reading from a Web Worker, or running a long calculation.\n\nAuto-tracking only covers reads before the first `await`: read `signal.value` or `store.prop` at the top of the function and Qwik re-runs it when they change. After the first `await` the tracking context is gone, so reads there are not tracked. To track those, use the `track()` function provided on the context argument:\n\n```tsx\nconst user = useComputed$(async ({ track }) => {\n // Tracked automatically: read before the first await.\n const id = userId.value;\n const res = await fetch(`/api/users/${id}`);\n // Tracked explicitly: after an await, use track().\n const locale = track(localeSignal);\n return formatUser(await res.json(), locale);\n});\n```\n\nWhile the async work is running, reading `.value` makes that part of the UI wait, and a [`<Pending>`](/docs/labs/pending.md) boundary can show fallback UI. If the work fails, reading `.value` re-throws the error, and a [`<Catch>`](/docs/labs/catch.md) can render a fallback for it.\n\nThe async work can run during SSR and in the browser. For values that need to stay up to date, poll the signal with `usePoll` from `@qwik.dev/utils`.\n\n#### Example\n\nBelow, `useComputed$()` fetches programming jokes for the current query. Reading `query.value` reruns the function when the query changes, and `abortSignal` cancels any previous request. `JokeList` reads `jokes.value` inside `<Pending>` and `<Catch>`.\n\n```tsx /useComputed$/ /query.value/ /abortSignal/ /Pending/ /Catch/\nimport {\n $,\n component$,\n Catch,\n Pending,\n useComputed$,\n useSignal,\n type Signal,\n} from '@qwik.dev/core';\n\ntype Joke = {\n joke?: string;\n setup?: string;\n delivery?: string;\n};\n\nconst JokeList = component$((props: { jokes: Signal<Joke[]> }) => {\n return props.jokes.value.length === 0 ? (\n <p>No jokes found</p>\n ) : (\n <ul>\n {props.jokes.value.map((joke, i) => (\n <li key={i}>\n <div style={{ whiteSpace: 'pre-wrap' }}>\n {joke.joke ?? `${joke.setup}\\n${joke.delivery}`}\n </div>\n </li>\n ))}\n </ul>\n );\n});\n\nexport default component$(() => {\n const query = useSignal('');\n\n const jokes = useComputed$(async ({ abortSignal }) => {\n // Re-run when query.value changes.\n const search = query.value.trim();\n const url = new URL(\n 'https://v2.jokeapi.dev/joke/Programming?safe-mode&amount=2'\n );\n\n if (search) {\n url.searchParams.set('contains', search);\n }\n\n const response = await fetch(url, { signal: abortSignal });\n const data = (await response.json()) as {\n jokes?: Joke[];\n };\n\n return data.jokes ?? [];\n });\n\n return (\n <>\n <label>\n Query: <input bind:value={query} />\n </label>\n <Catch\n fallback$={$((error, reset) => (\n <div>\n Error: {error.message} <button onClick$={() => reset()}>Retry</button>\n </div>\n ))}\n >\n <Pending fallback$={() => <p>Loading...</p>}>\n <JokeList jokes={jokes} />\n </Pending>\n </Catch>\n </>\n );\n});\n```\n\n`<Pending>` shows the loading fallback until the first result arrives, and `<Catch>` renders the error if the request fails. During SSR, Qwik waits for the async work before rendering the result.\n\n**Async computed values and Pending**\n\nWhen the query changes, `jokes.value` keeps returning the previous jokes until the new ones arrive, so the fallback only shows on the first load. Call `jokes.clear()` when readers should see the fallback again while the new value computes.\n\n**Advanced: channel example**\n\n`useComputed$()` can also keep its own value updated after the first result. For example, a Server-Sent Events connection can write new messages into the signal.\n\n```tsx\nimport { component$, useComputed$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const state = useComputed$<string>(\n ({ abortSignal }) => {\n const eventSource = new EventSource('/api/state-channel');\n\n eventSource.onmessage = (event) => {\n state.value = event.data;\n };\n\n abortSignal.addEventListener('abort', () => {\n eventSource.close();\n });\n\n return 'init';\n },\n { eagerCleanup: true }\n );\n\n return <div>Current state is: {state.value}</div>;\n});\n```\n\n`eagerCleanup` closes the connection as soon as nothing is reading the signal.\n\n**API reference**\n\nMost apps only need `.value`. The full API also includes options for cleanup, cancellation, timeouts, and manual invalidation.\n\n```tsx\nfunction useComputed$<T>(\n computeFn: (ctx: {\n readonly track: Tracker;\n cleanup: (fn: () => void | Promise<void>) => void;\n readonly abortSignal: AbortSignal;\n readonly previous: T | undefined;\n readonly info: unknown;\n }) => T | Promise<T>,\n options?: {\n initial?: T | (() => T);\n concurrency?: number;\n eagerCleanup?: boolean;\n clientOnly?: boolean;\n timeout?: number;\n }\n): ComputedSignal<T>;\n```\n\nThe function reads reactive state directly (`signal.value`, `store.prop`); Qwik tracks those reads automatically until the first `await`. Context:\n\n- `track`: tracks reads explicitly. Required for reads after the first `await`, where automatic tracking stops.\n- `cleanup`: runs cleanup when the function re-runs or the component is destroyed.\n- `abortSignal`: aborts when the function re-runs or is destroyed. Pass it to APIs like `fetch()`.\n- `previous`: the previous resolved value, if one exists.\n- `info`: the value passed to `signal.invalidate(info)`.\n\nOptions:\n\n- `initial`: value to use before the async function resolves.\n- `concurrency`: number of computations that can run at the same time. Defaults to `1`; `0` means no limit.\n- `eagerCleanup`: cleanup as soon as nothing is reading the signal.\n- `clientOnly`: skip SSR and only run in the browser.\n- `timeout`: abort if the function takes longer than this many milliseconds.\n\nReturned signal:\n\n```ts\ninterface ComputedSignal<T> {\n value: T;\n pending: boolean;\n error: Error | undefined;\n promise(): Promise<void>;\n abort(reason?: any): void;\n invalidate(info?: unknown): void;\n clear(): void;\n}\n```\n\n- `value`: the resolved value, or `initial` if provided.\n- `pending`: whether the async function is running.\n- `error`: the error if the async function failed.\n- `promise()`: starts the async function if needed and waits for it to finish.\n- `abort()`: aborts the current async function.\n- `invalidate()`: marks the signal to run again; readers keep seeing the previous value while it recomputes.\n- `clear()`: like `invalidate()`, but drops the value so readers suspend until the new value is ready.\n\nTo re-run the signal on an interval, use `usePoll(signal, ms)` from `@qwik.dev/utils`: it starts polling once the document is idle and resets the timer whenever a new result lands.\n\n## Sharing state\n\nOne of the nice features of Qwik is that the state can be passed to other components. Writing to the store will then only re-render the components which read from the store only.\n\nThere are two ways to pass state to other components:\n\n1. pass state to child component explicitly using props,\n2. or pass state implicitly through context.\n\n### Using props\n\nThe simplest way to pass the state to other components is to pass it through props.\n\n```tsx {9} /userData=/\nimport { component$, useStore } from '@qwik.dev/core';\n\nexport default component$(() => {\n const userData = useStore({ count: 0 });\n return <Child userData={userData} />;\n});\n\ninterface ChildProps {\n userData: { count: number };\n}\nexport const Child = component$<ChildProps>(({ userData }) => {\n return (\n <>\n <button onClick$={() => userData.count++}>Increment</button>\n <p>Count: {userData.count}</p>\n </>\n );\n});\n```\n\n### Using context\n\nThe context API is a way to pass state to components without having to pass it through props (i.e.: avoids prop drilling issues). Automatically, all the descendant components in the tree can access a reference to the state with read/write access to it.\n\nCheck the [context API](/docs/core/context.md) for more information.\n\n```tsx /userData/ /export const CTX = createContextId<{ count: number }>('stuff');/ /useContextProvider(CTX, userData);/ /const userData = useContext(CTX);/\nimport {\n component$,\n createContextId,\n useContext,\n useContextProvider,\n useStore,\n} from '@qwik.dev/core';\n\n// Declare a context ID\nexport const CTX = createContextId<{ count: number }>('stuff');\n\nexport default component$(() => {\n const userData = useStore({ count: 0 });\n\n // Provide the store to the context under the context ID\n useContextProvider(CTX, userData);\n\n return <Child />;\n});\n\nexport const Child = component$(() => {\n const userData = useContext(CTX);\n return (\n <>\n <button onClick$={() => userData.count++}>Increment</button>\n <p>Count: {userData.count}</p>\n </>\n );\n});\n```\n\n## Serialization\n\n### `useSerializer$()` / `createSerializer$()`\n\nSometimes you need to serialize data that Qwik doesn't know how to serialize. For this, you can use the `useSerializer$(cfg)` hook to create a serializer for the data. `createSerializer$(cfg)` does the same thing but is not bound to a specific component and can be called anywhere.\n\nThe `cfg` argument is an object with generic type `S` (serialized data) and `T` (the object type) with the following properties:\n\n- `deserialize: (data: S) => T`: Creates the object using the initial value or the deserialized value.\n- `serialize?: (value: T) => S | Promise<S>`: Optional, serializes the object. If not provided, the object will be serialized as `undefined`.\n- `initial?: S`: Optional, the initial value of the serializer.\n- `update?: (value: T) => T | void`: Optional, updates the object when the reactive state changes. This can only be passed when `cfg` is a function, see below.\n\nThe result is a `SerializerSignal<T>` object. This is a lazy reactive signal that contains the serialized value of the object. It must be passed around as the signal, otherwise serialization will not work.\n\n```tsx /useSerializer$/\nimport { component$, useSerializer$ } from '@qwik.dev/core';\nimport { MyClass } from './my-class';\n\nexport default component$(() => {\n const serializer = useSerializer$({\n deserialize: (data) => new MyClass(data),\n serialize: (value) => value.serialize(),\n initial: {x: 3, y: 4},\n });\n\n return <div>{JSON.stringify(serializer.value)}</div>;\n});\n```\n\nDuring SSR, `deserialize` will be called with the initial value. You can then use `signal.value` to access the custom object. On the client, the `deserialize` function will be called with the serialized value, but only when the signal is first read. So if you don't need to read the signal, no code will run.\n\nYou can also use reactive state to create a serializer. For this, you need to pass the config as a function that captures the reactive state. Then you can use the `update` function to update the object when the reactive state changes. If the `update` function returns an object, it will be used as the new value for the serializer, and it will trigger all listeners. The trigger happens even when returning the same object.\n\n```tsx /useSerializer$/\nimport { component$, useSerializer$ } from '@qwik.dev/core';\nimport { ComplexObject } from './complex-object';\n\nexport default component$(() => {\n const sig = useSignal(123);\n const serializer = useSerializer$((cfg) => ({\n deserialize: () => new ComplexObject(sig.value),\n update: (obj) => {\n if (sig.value < 7) {\n // ignore changes below 7\n return;\n }\n // Tell the object about the change\n obj.update(sig.value);\n // Return the updated object so the listeners are notified\n return obj;\n }\n }));\n\n // ...\n});\n```\n\nThis primitive is very powerful, and can be used to create all sorts of custom serializers. Note that the `serialize` function is allowed to return a Promise, so you could for example write the data to a database and return the id. Note that you will need to use `if (isServer)` to guard this operation, so vite won't bundle database code in the client bundle.\n\nAlso note that serialization can also happen on the client, when calling `server$` functions.\n\n### `noSerialize()` / `NoSerializeSymbol`\n\nQwik ensures that all application state is always serializable. This is important to ensure that Qwik applications have a [resumability](/docs/concepts/resumable.md) property.\n\nSometimes, it's necessary to store data that can't be serialized; `noSerialize()` instructs Qwik not to attempt serializing the marked value.\nFor example, a reference to a third-party library such as [Monaco editor](https://microsoft.github.io/monaco-editor/) will always need `noSerialize()`, as it is not serializable.\n\n`NoSerializeSymbol` is an alternative to `noSerialize()`: You can add this symbol to an object (preferably on the prototype) and it will mark the object as non-serializable.\n\nIf a value is marked as non-serializable, then that value will not survive serialization events, such as resuming the application on the client from SSR. In this situation, the value will be set to `undefined` and it is up to the developer to re-initialize the value on the client.\n\n#### `useComputed$()` and `noSerialize()`\n\nIf a computed value is wrapped with `noSerialize()`, Qwik will not send that value to the client. It will be created again on the client when the computed signal is read.\n\nThis is useful for values that cannot be serialized, such as custom class instances.\n\n```tsx /noSerialize/\nimport {\n component$,\n useStore,\n useSignal,\n noSerialize,\n useVisibleTask$,\n type NoSerialize,\n} from '@qwik.dev/core';\nimport type Monaco from './monaco';\nimport { monacoEditor } from './monaco';\n\nclass MyClass {\n [NoSerializeSymbol] = true;\n}\n\nexport default component$(() => {\n const editorRef = useSignal<HTMLElement>();\n const store = useStore<{ monacoInstance: NoSerialize<Monaco>, myClass: MyClass }>({\n monacoInstance: undefined,\n myClass: undefined,\n });\n\n useVisibleTask$(() => {\n const editor = monacoEditor.create(editorRef.value!, {\n value: 'Hello, world!',\n });\n // Monaco is not serializable, so we can't serialize it as part of SSR\n // We can however instantiate it on the client after the component is visible\n store.monacoInstance = noSerialize(editor);\n // Here we demonstrate `NoSerializeSymbol` for the same purpose\n store.myClass = new MyClass();\n });\n return <div ref={editorRef}>loading...</div>;\n});\n```\n\n### `SerializerSymbol`\n\nThe `SerializerSymbol` is a symbol that can be added to an object to achieve custom serialization. There is no corresponding `DeserializerSymbol` however, for that you should use the `useSerializer$()` hook.\n\nThis can be used to skip serializing part of an object, or to work with third-party objects that are not serializable by default.\n\n```tsx /SerializerSymbol/\nimport { component$, SerializerSymbol } from '@qwik.dev/core';\nimport { getItem, type Item } from './my-db-layer';\n\nconst serializer = (o: Item) => o.toJSON();\ntype MyItem = Item & { [SerializerSymbol]: typeof serializer };\n\nexport default component$((props: {id: string}) => {\n const obj = useSignal<MyItem | null>(null);\n useTask$(async () => {\n const item = await getItem(props.id);\n if (item) {\n item[SerializerSymbol] = serializer;\n obj.value = item;\n }\n });\n return <div>{JSON.stringify(obj.value)}</div>;\n});\n```\n\nYou could even monkey-patch the third-party library to add the `SerializerSymbol` to their objects. Note that this can result in problems when the third-party library is updated, so use this method with caution. You will also need to update the types so that our linting plugin doesn't complain about serialization of unknown types.\n"},{"id":"/docs/core/events/","title":"Events","description":"Event handling model, lazy event listeners, and DOM interaction in Qwik.","url":"https://next.qwik.dev/docs/core/events/","content":"# Events\n\nFor a web application to be interactive, there needs to be a way to respond to user events. This is done by registering callback functions in the JSX template. Event handlers are registered using the `on{EventName}$` attribute. For example, the `onClick$` attribute is used to listen for `click` events.\n\n```tsx /onClick$/\n<button onClick$={() => alert('CLICKED!')}>click me!</button>\n```\n\n## Inline Handler\n\nIn the following example, the `onClick$` attribute of the `<button>` element is used to let Qwik know that a callback `() => store.count++` should be executed whenever the `click` event is fired by the `<button>`.\n\n```tsx {7} /onClick$/\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const count = useSignal(0);\n\n return (\n <button onClick$={() => count.value++}>\n Increment {count.value}\n </button>\n );\n});\n```\n\nYou can also use `bind:propertyName` to conveniently have a [two-way binding](/docs/core/rendering.md#bind-attribute) between a signal and an input element.\n\nNotice that `onClick$` ends with [`$`](/docs/advanced/dollar.md). This is a hint to both the [Optimizer](/docs/advanced/optimizer.md) and the developer that a special transformation occurs at this location. The presence of the `$` suffix implies a lazy-loaded boundary here. The code associated with the `click` handler is not loaded into the JavaScript Virtual Machine (VM) until the user activates the click event. However, to avoid delays during the first interaction, it is eagerly loaded into the browser cache.\n\nIn real-world applications, the listener may refer to complex code. By creating a lazy-loaded boundary (with the `$`), Qwik can tree-shake all of the code behind the click listener and delay its loading until the user clicks the button.\n\n## Reusing Event Handlers\n\nTo reuse the same event handler for multiple elements or events, you have to wrap the event handler into the `$()` function exported by `@qwik.dev/core`. This transforms it into a [`QRL`](/docs/advanced/qrl.md).\n\n```tsx {5} /increment/#a\nimport { component$, useSignal, $ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const count = useSignal(0);\n const increment = $(() => count.value++);\n return (\n <>\n <button onClick$={increment}>Increment</button>\n <p>Count: {count.value}</p>\n </>\n );\n});\n```\n\nIf you extract the event handler, you must manually wrap it in the `$(...handler...)`. This ensures that it is lazily attached.\n\n## Multiple Event Handlers\n\nTo register multiple event handlers for the same event, you can pass an array of event handlers to the `on{EventName}$` attribute.\n\n```tsx /onClick$/\nimport { component$, useSignal, $ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const count = useSignal(0);\n const print = $((ev) => console.log('CLICKED!', ev));\n const increment = $(() => count.value++);\n\n // The button when clicked will print \"CLICKED!\" to the console, increment the count and send an event to Google Analytics.\n return (\n <button\n onClick$={[print, increment, $(() => {\n ga.send('click', { label: 'increment' });\n })]}\n >\n Count: {count.value}\n </button>\n );\n});\n```\n\n## Event Object\n\nThe first argument of the event handler is the `Event` object. This object contains information about the event that triggered the handler. For example, the `Event` object for a `click` event contains information about the mouse position and the element that was clicked. You can check out the [MDN docs to know more details about each DOM event](https://developer.mozilla.org/en-US/docs/Web/API/Event).\n\n```tsx /event/\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const position = useSignal<{ x: number; y: number }>();\n return (\n <div\n onClick$={(event) => (position.value = { x: event.x, y: event.y })}\n style=\"height: 100vh\"\n >\n <p>\n Clicked at: ({position.value?.x}, {position.value?.y})\n </p>\n </div>\n );\n});\n```\n\n## Asynchronous Events\n\nDue to Qwik's asynchronous nature, the execution of an event handler might be delayed if the implementation has not yet been loaded into the JavaScript VM. Consequently, the following APIs on an Event object will not work:\n\n- `event.preventDefault()`\n- `event.stopPropagation()`\n- `event.currentTarget`\n\n### preventDefault & stopPropagation\n\nBecause event handling is asynchronous, you can't use `event.preventDefault()` or `event.stopPropagation()`. To solve this, Qwik introduces a declarative way to prevent default through `preventdefault:{eventName}` and `stoppropagation:{eventName}` attributes.\n\n```tsx {7}\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <a\n href=\"/docs\"\n preventdefault:click // This will prevent the default behavior of the \"click\" event.\n stoppropagation:click // This will stop the propagation of the \"click\" event.\n onClick$={() => {\n // event.PreventDefault() will not work here, because handler is dispatched asynchronously.\n alert('Do something else to simulate navigation...');\n }}\n >\n Go to docs page\n </a>\n );\n});\n```\n\n### Passive events\n\nUse `passive:eventname` to mark a Qwik event listener as passive when the handler does not need\n`preventDefault()`.\n\nThis is especially useful for events such as `touchstart`, `touchmove`, and `scroll`, where the\nbrowser can optimize scrolling when it knows the listener is passive.\n\n```tsx /passive:touchmove/ /passive:touchstart/ /passive:scroll/\n<div passive:touchmove onTouchMove$={() => console.log('move')} />\n\n<button\n passive:touchstart\n document:onTouchStart$={() => console.log('document touchstart')}\n/>\n\n<button passive:scroll window:onScroll$={() => console.log('window scroll')} />\n```\n\n`passive:eventname` is only a marker. It must match a Qwik handler for the same event, and Qwik\nconsumes it during JSX processing.\n\nPassive listeners do not combine with `preventdefault:eventname` for the same event. Qwik warns\nabout that combination with the `preventdefault-passive-check` optimizer diagnostic and drops the\n`preventdefault:*` marker for that event.\n\n If you need to prevent the browser default, do not use `passive:eventname` for that event. If\n you intentionally want to suppress the optimizer warning for one line, use\n [`@qwik-disable-next-line`](/docs/advanced/optimizer-hints.md).\n\n### Capture events\n\nUse `capture:eventname` to run an element event handler during the capture phase instead of the\ndefault bubbling phase.\n\nThis is useful when a parent element needs to observe or intercept an event before it reaches a\nchild's bubbling handler.\n\n```tsx /capture:click/\n<div\n capture:click\n onClick$={() => console.log('parent capture')}\n>\n <button onClick$={() => console.log('button bubble')} />\n</div>\n```\n\nWhen the button is clicked, Qwik runs:\n\n1. the parent's `click` handler during capture\n2. the button's `click` handler during bubbling\n\n`capture:eventname` is scoped to a single event. For example, this makes `click` capture-phase\nwhile leaving `scroll` in its normal mode:\n\n```tsx /capture:click/\n<div\n capture:click\n onClick$={() => console.log('capture click')}\n onScroll$={() => console.log('bubble scroll')}\n/>\n```\n\n`capture:eventname` only applies to element-scoped handlers such as `onClick$`. It does not change\n`window:on*` or `document:on*` listeners.\n\n `capture:eventname` is a marker for the existing handler bucket for that event. A single element\n event cannot be both capture and bubble at the same time. For example, you can mark `click` as\n capture and leave `scroll` as bubble on the same element, but you cannot register both capture\n and bubble handlers for `click` on the same element.\n\n### Event Target\n\nBecause event handling is asynchronous, you can't use `event.currentTarget`. To solve this, Qwik handlers provide a `currentTarget` as a second argument.\n\n```tsx /currentTarget/\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const currentElm = useSignal<HTMLElement|null>(null);\n const targetElm = useSignal<HTMLElement|null>(null);\n\n return (\n <section onClick$={(event, currentTarget) => {\n currentElm.value = currentTarget;\n targetElm.value = event.target as HTMLElement;\n }}>\n Click on any text <code>target</code> and <code>currentElm</code> of the event.\n <hr/>\n <p>Hello <b>World</b>!</p>\n <hr/>\n <ul>\n <li>currentElm: {currentElm.value?.tagName}</li>\n <li>target: {targetElm.value?.tagName}</li>\n </ul>\n </section>\n );\n});\n```\n\n`currentTarget` in the DOM points to the element that the event listener was attached to. In the example above it will always be the `` element.\n\n### Synchronous Event Handling\n\nIn some cases, it is necessary to handle an event traditionally, because some APIs need to be used synchronously. For example, `dragstart` event must be processed synchronously and therefore it can't be combined with Qwik's lazy code execution.\n\nTo do this, you can leverage a `useVisibleTask` to programmatically add an event listener using the DOM API directly.\n\n```tsx {7-20}\nimport { component$, useSignal, useVisibleTask$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const draggableRef = useSignal<HTMLElement>();\n const dragStatus = useSignal('');\n\n useVisibleTask$(({ cleanup }) => {\n if (draggableRef.value) {\n // Use the DOM API to add an event listener.\n const dragstart = () => (dragStatus.value = 'dragstart');\n const dragend = () => (dragStatus.value = 'dragend');\n\n draggableRef.value!.addEventListener('dragstart', dragstart);\n draggableRef.value!.addEventListener('dragend', dragend);\n cleanup(() => {\n draggableRef.value!.removeEventListener('dragstart', dragstart);\n draggableRef.value!.removeEventListener('dragend', dragend);\n });\n }\n });\n\n return (\n <div>\n <div draggable ref={draggableRef}>\n Drag me!\n </div>\n <p>{dragStatus.value}</p>\n </div>\n );\n});\n```\n\nUsing `VisibleTask` to listen for events is an anti-pattern in Qwik because it causes eager execution of code in the browser defeating [resumability](/docs/concepts/resumable.md). Only use it when you have no other choice. You should use JSX to listen for events, for example: ``. Alternatively, if you need to listen to events programmatically, consider using the `useOn(...)` event methods.\n\n## Custom Event Props\n\nWhen creating your components, it is often useful to pass custom event props that resemble event handlers, even though they are just callbacks and not actual DOM events. Component boundaries in Qwik must be serializable for the optimizer to split them up into separate chunks. Functions are not serializable unless they are converted to a QRL.\n\nFor example, listening for triple click events, which html cannot do by default, would require creating an `onTripleClick$` custom event prop.\n```tsx\nimport { component$, Slot, useStore } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <Button onTripleClick$={() => alert('TRIPLE CLICKED!')}>\n Triple Click me!\n </Button>\n );\n});\n\ntype ButtonProps = {\n onTripleClick$: QRL<() => void>;\n};\n\nexport const Button = component$<ButtonProps>(({ onTripleClick$ }) => {\n const state = useStore({\n clicks: 0,\n lastClickTime: 0,\n });\n return (\n <button\n onClick$={() => {\n // triple click logic\n const now = Date.now();\n const timeBetweenClicks = now - state.lastClickTime;\n state.lastClickTime = now;\n if (timeBetweenClicks > 500) {\n state.clicks = 0;\n }\n state.clicks++;\n if (state.clicks === 3) {\n // handle custom event\n onTripleClick$();\n state.clicks = 0;\n }\n }}\n >\n <Slot />\n </button>\n );\n});\n```\n\nNotice the use of the `QRL` type in `onTripleClick$: QRL void>;`. It is like wrapping a function in `$()` but at the type level. If you had `const greet = $(() => \"hi\");` and hovered over 'greet', you would see that 'greet' is of type `QRL \"hi\">`\n\nEvent names are case sensitive, but all DOM events except for `DOMContentLoaded` are lowercase. For a better DX, event names are always lowercased, so `onTripleClick$` becomes `tripleclick` under the hood.\n\nTo listen for a custom event with uppercase letters, you add a `-` after `on`. For example, to listen for a custom event named `CustomEvent`, you would use `on-CustomEvent$`. For a window event named `Hi-There`, you would use `window:on-Hi-There$`.\n\n## Window and Document Events\n\nSo far, the discussion has focused on listening to events originating from elements. There are events such as `scroll` and `mousemove` that need to be listened to on the `window` or `document`. Qwik allows this by providing the `document:on` and `window:on` prefixes when listening for events.\n\nThe `window:on`/`document:` prefixes are used to register an event at the current DOM location of the component while allowing it to receive events from the `window`/`document`. There are two advantages to this:\n\n1. The events can be registered declaratively in your JSX.\n2. The events get automatically cleaned up when the component is destroyed (No explicit bookkeeping and cleanup is needed).\n\n## `useOn[window|document]` Hook\n\n- `useOn()`: listen to events on the current component's root element.\n- `useOnWindow()`: listen to events on the `window` object.\n- `useOnDocument()`: listen to events on the `document` object.\n\n`useOn[window|document]()` hook will add a DOM-based event listener at the component level programmatically. This is often useful when you want to create your own use hooks or if you don't know the event name at the time of compilation.\n\nUse `useOn()` when you need the ergonomics of JSX event handlers, but the listener must be registered from a reusable hook or helper instead of directly in markup. The event still stays lazy-loadable because the callback is wrapped in `$()`.\n\nAs a rule of thumb:\n\n- Prefer JSX such as `<button onClick$={...}>` when the listener belongs directly to that element in the component's template.\n- Use `useOn()` when you are building a custom `use*()` hook and the hook should attach to the current component's host element.\n- Use `useOnDocument()` or `useOnWindow()` when the event source is global rather than the component's own host element.\n\nThe \"host element\" for `useOn()` is the top-level DOM element rendered by the current component. That means `useOn('click', ...)` behaves like attaching a listener to that root node, not to every child in the component.\n\nAll three hooks also accept an optional third argument for event modifiers:\n\n- `{ passive: true }` registers a passive listener for events such as `touchmove`, `wheel`, or `scroll` when the handler does not need to call `preventDefault()`.\n- `{ capture: true }` runs the listener during the capture phase instead of the bubbling phase.\n- `{ preventdefault: true }` applies the same behavior as JSX `preventdefault:event`, so Qwik calls `event.preventDefault()` before the handler runs.\n- `{ stoppropagation: true }` applies the same behavior as JSX `stoppropagation:event`, so Qwik stops propagation before the handler runs.\n\nAvoid combining `passive: true` with `preventdefault: true`, because passive listeners cannot cancel the browser's default behavior.\n\n```tsx\nimport { $, component$, useOnDocument, useStore } from '@qwik.dev/core';\n\n// Assume reusable use method that does not have access to JSX\n// but needs to register event handlers.\nfunction useMousePosition() {\n const position = useStore({ x: 0, y: 0 });\n useOnDocument(\n 'mousemove',\n $((event) => {\n const { x, y } = event as MouseEvent;\n position.x = x;\n position.y = y;\n })\n );\n return position;\n}\n\nexport default component$(() => {\n const pos = useMousePosition();\n return (\n <div>\n MousePosition: ({pos.x}, {pos.y})\n </div>\n );\n});\n```\n\nIn the example above, `useMousePosition()` is a reusable hook. It cannot write `onMouseMove$` into JSX because it does not render any DOM itself, so it registers the listener programmatically with `useOnDocument()`. This is the main use case for the `useOn*()` family.\n\n```tsx\nimport { $, component$, useOnWindow, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const scrollCount = useSignal(0);\n\n useOnWindow(\n 'scroll',\n $(() => {\n scrollCount.value++;\n }),\n { passive: true }\n );\n\n return <p>Scroll events: {scrollCount.value}</p>;\n});\n```\n\n```tsx\nimport { $, component$, useOn, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const logs = useSignal<string[]>([]);\n\n useOn(\n 'click',\n $(() => {\n logs.value = [...logs.value, 'captured on host'];\n }),\n { capture: true, stoppropagation: true }\n );\n\n return (\n <div>\n <button>Click me</button>\n <pre>{logs.value.join('\\n')}</pre>\n </div>\n );\n});\n```\n"},{"id":"/docs/advanced/sync-events/","title":"Synchronous Events with State","description":"Advanced `sync$()` patterns for synchronous DOM event work that still coordinates with reactive state.","url":"https://next.qwik.dev/docs/advanced/sync-events/","content":"# `sync$()` Synchronous Events\n\nQwik processes events asynchronously. This means that some APIs such as `event.preventDefault()` and `event.stopPropagation()` do not work as expected. To work around this limitation, Qwik provides a `sync$()` API which allows you to process events synchronously. But `sync$()` comes with a few caveats:\n1. `sync$()` can't close over any state.\n2. `sync$()` can't call other functions which are declared in scope or imported.\n3. `sync$()` is serialized into HTML and therefore we should be conscious of the size of the function.\n\nA typical way to deal with these limitations is to split the event handling into two parts:\n1. `sync$()` which is called synchronously and can call methods such as `event.preventDefault()` and `event.stopPropagation()`.\n2. `$()` which is called asynchronously and can close over the state and call other functions, and has no restriction on the size.\n\nBecause `sync$()` can't access the state, what is the best strategy to deal with it? The answer is to use element attributes to pass state into the `sync$()` function.\nIf you only need to prevent the default behavior, you can simply use the standard [`preventDefault:{eventName}`](/docs/core/events.md#prevent-default) syntax. This is strictly for when you need to chain events together synchronously.\n\n## Example: `sync$()` with state\n\nIn this example, we have a behavior where we want to prevent the default behavior of the link based on some state. We do this by breaking the code into three parts:\n1. `sync$()`: a synchronous portion that is kept to the minimum,\n2. `$()`: an asynchronous portion that can be arbitrarily large, and can close over state,\n3. `data-should-prevent-default`: an attribute on the element that is used to pass state into the `sync$()` function.\n\n```tsx\nimport { component$, useSignal, sync$, $ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const shouldPreventDefault = useSignal(true);\n return (\n <div>\n <div>Sync Event:</div>\n <input\n type=\"checkbox\"\n checked={shouldPreventDefault.value}\n onChange$={(e, target) =>\n (shouldPreventDefault.value = target.checked)\n }\n />{' '}\n Should Prevent Default\n <hr />\n <a\n href=\"https://google.com\"\n target=\"_blank\"\n data-should-prevent-default={shouldPreventDefault.value}\n onClick$={[\n sync$((e, target) => {\n if (target.hasAttribute('data-should-prevent-default')) {\n e.preventDefault();\n }\n }),\n $(() => {\n console.log(\n shouldPreventDefault.value ? 'Prevented' : 'Not Prevented'\n );\n }),\n ]}\n >\n open Google\n </a>\n </div>\n );\n});\n```\n"},{"id":"/docs/core/tasks/","title":"Tasks and Lifecycle","description":"Lifecycle and task model including `useTask$`, `useVisibleTask$`, and tracked reactive work.","url":"https://next.qwik.dev/docs/core/tasks/","content":"# Tasks\n\nTasks are meant for running asynchronous operations as part of component initialization or change of component state.\n\n**Tasks vs useEffect()**\n\nTasks are similar to `useEffect()` in React, but there are enough differences that we did not want to call them the same so as not to bring preexisting expectations about how they work. The main differences are:\n\n- Tasks are asynchronous.\n- Tasks run on server and browser.\n- Tasks run before rendering and can block rendering.\n- Subsequent task re-executions (when tracked state changes) block rendering by default, but can be configured to not block DOM updates with `deferUpdates: false`.\n\n`useTask$()` should be your default go-to API for running either synchronous or asynchronous work as part of component initialization or state change. It is only when you can't achieve what you need with `useTask$()` that you should consider using `useVisibleTask$()`.\n\nThe basic use case for `useTask$()` is to perform work on component initialization. `useTask$()` has these properties:\n- It can run on either the server or in the browser.\n- It runs before the initial rendering and blocks the initial render.\n- If multiple tasks are running then they are run sequentially in the order they were registered. An asynchronous task will block the next task from running until it completes.\n- By default, subsequent re-executions (when tracked state changes) do block DOM updates unless `deferUpdates: false` is specified.\n\nTasks can also be used to perform work when a component state changes. In this case, the task will rerun every time the tracked state changes. See: [`track()`](#track).\n\nSometimes a task needs to run only on the browser and after rendering, in that case, you should use [`useVisibleTask$()`](#usevisibletask).\n\nIf you need to fetch data asynchronously and not block rendering, you should use [`useComputed$()`](/docs/core/state.md#usecomputed) with an async function. It does not block rendering while the async value is being resolved.\n\n## Lifecycle\nResumability is \"Lazy execution\", it's the ability to build the \"framework state\" (component boundaries, etc) on the server, and have it exist on the client without re-executing the framework again.\n\nThe application environment—whether client-side or server-side—is determined by user interactions. In server-side rendering, the application initially renders on the server.\nWhen the user interacts with the application, it resumes on the client-side, continuing from the state left by the server. This approach ensures efficient and responsive user experiences by leveraging both environments based on interaction.\n\nFor systems that use hydration, the execution of the application happens twice. Once on a server (SSR/SSG) and once on the browser (hydration). This is why many frameworks have \"effects\" which only execute on the browser. That means that the code that runs on the server is different than the code that runs on the browser. Qwik execution is unified, meaning if the code has already been executed on the server, it does not re-execute it on the browser.\n\n**In Qwik, there are only 3 lifecycle stages:**\n\n- `Task` - run before rendering and when tracked state changes. `Tasks` run sequentially, and block each other. They also can block rendering.\n- `Render` - runs after `TASK` and before `VisibleTask`\n- `VisibleTask` - runs after `Render` and when the component becomes visible\n\n**Diagram:** Task lifecycle diagram: useTask$ runs on server or browser, then renders, then useVisibleTask$ runs on browser\n\n**SERVER**: Usually **the life of a component starts on the server** (during SSR or SSG), in that case, the `useTask$` and `RENDER` will run in the server, and then the `VisibleTask` will run in the browser, after the component is visible.\n\nBecause the component was mounted in the server, **only useVisibleTask$() runs in the browser**. This is because the browser continues the same lifecycle, that was paused in the server right after the render and resumed in the browser.\n\n**BROWSER**: When a component is first mounted or rendered in the browser, for example when a user navigates to a new page in a Single Page Application (SPA) or when a \"modal\" component initially appears on the page, the lifecycle will proceed as follows:\n\n**Diagram:** Browser-only lifecycle: useTask$, then render, then useVisibleTask$ all run in browser\n\nThe lifecycle is exactly the same, but this time all the hooks run in the browser, and not in the server.\n\n## `useTask$()`\n\n- **When:** BEFORE component's first render, and when tracked state changes\n- **Times:** at least once\n- **Platform:** server and browser\n\n`useTask$()` registers a hook to be executed upon component creation, it will run at least once either in the server or in the browser, depending on where the component is initially rendered.\n\n### Task options\n\n`useTask$()` accepts an optional second parameter of type `TaskOptions` to configure the task behavior.\n\n```typescript\ninterface TaskOptions {\n deferUpdates?: boolean;\n}\n```\n\n#### `deferUpdates`\n\nThe `deferUpdates` option controls whether subsequent task re-executions (when tracked state changes) should block DOM updates.\n\n**Default behavior (`deferUpdates: false` or not specified):**\n- **Initial render**: The task blocks rendering (same as default)\n- **Subsequent runs**: The task blocks DOM updates until it completes - the journal flush is deferred until the task finishes\n\n**With `deferUpdates: true`:**\n- **Initial render**: The task blocks rendering (runs before the component renders for the first time)\n- **Subsequent runs**: The task runs asynchronously without blocking DOM updates\n\nAdditionally, this task can be reactive and will re-execute when **tracked** [state](/docs/core/state.md) changes.\n\n**Notice that any subsequent re-execution of the task will always happen in the browser**, because reactivity is a browser-only thing.\n\n**Diagram:** Task re-execution lifecycle: useTask$ with track runs on server, renders, then on browser click triggers re-execution\n\nIf `useTask$()` does not track any state, it will run **exactly once**, either in the server **or** in the browser (**not both**), depending where the component is initially rendered. Effectively behaving like an \"on-mount\" hook.\n\n`useTask$()` will block the rendering of the component until after its async callback resolves. Tasks execute sequentially even if they are asynchronous (only one task executes at a time within a component). Subsequent re-executions (when tracking state changes) run asynchronously by default and block rendering unless `deferUpdates: false` is set.\n\nTake a look at the simplest use case of the task to run some asynchronous work on component initialization:\n\n```tsx\nimport { component$, useSignal, useTask$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const fibonacci = useSignal<number[]>();\n\n useTask$(async () => {\n const size = 40;\n const array = [];\n array.push(0, 1);\n for (let i = array.length; i < size; i++) {\n array.push(array[i - 1] + array[i - 2]);\n await delay(100);\n }\n fibonacci.value = array;\n });\n\n return <p>{fibonacci.value?.join(', ')}</p>;\n});\n\nconst delay = (time: number) => new Promise((res) => setTimeout(res, time));\n```\n\n**Fibonacci Example Explained**\n\n- The `useTask$()` computes the fibonacci number one entry per 100 ms. So 40 entries take 4 seconds to render.\n - The `useTask$()` executes on the server as part of the SSR (the result may be cached in CDN.)\n - Because the `useTask$()` blocks rendering, the rendered HTML page takes 4 seconds to render.\n- Because this task has no `track()` it will never rerun, making it effectively an initialization code.\n - Because this component only renders on the server, the `useTask$()` will never be downloaded or run on the browser.\n\n`useTask$()` runs on the server **BEFORE** the actual rendering. Therefore if you need to do DOM manipulation, use [`useVisibleTask$()`](#usevisibletask) instead, which runs on the browser after rendering.\n\nUse `useTask$()` when you need to:\n- Run async tasks before rendering\n- Run code only once before the component is first rendered\n- Programmatically run side-effect code when state changes\n\nIf you're thinking about loading data using `fetch()` inside of `useTask$`, consider using [`useComputed$()`](/docs/core/state.md#usecomputed) with an async function instead. This API is more convenient.\n\n### On mount\n\nIn Qwik, there isn't a specific \"mount\" step like in some other frameworks. Instead, components just start up directly where they're needed, either on a web server or in your browser.\nThis is without the inner track function, which is used to monitor specific pieces of data.\n\n`useTask$` runs always at least once when the component is first mounted.\n\n```tsx {5-8}\nimport { component$, useTask$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n\n useTask$(async () => {\n // A task without `track` any state effectively behaves like a `on mount` hook.\n console.log('Runs once when the component mounts in the server OR client.');\n });\n\n return <div>Hello</div>;\n});\n```\n\nOne unique aspect of Qwik, is that components are mounted only **once** across the server and client. This is a property of resumability. What this means is that if `useTask$` is executed during Server-Side Rendering (SSR), it will not run again in the browser because Qwik does not perform hydration.\n\n### `track()`\n\nThere are times when it is desirable to re-run a task when a component state changes. This is done by using the `track()` function. The `track()` function allows you to set up a dependency on a component's state when initially rendered on the server, and then re-execute the task when the state changes in the browser.\n\nTrack accepts signals, stores and functions. It returns the value of the signal, the store itself, or the function call result.\n\nWhen you pass a store, the track will be called when the store gets or removes properties as well as mutations of properties.\nNote that deep store updates don't mutate the store itself, so `store[item].count++` will not trigger an update. Instead, you should individually track each `store[item]` (which are also automatically created stores).\n\nDuring SSR, each component will wait until all tasks are completed before outputting the HTML for that component. So a task can be called multiple times during SSR if the tracked state changes due to other tasks.\n\nUse [`useComputed$()`](/docs/core/state.md#usecomputed) to compute a new state from existing state. For async derivations (like search-as-you-type), pass it an async function and cancel in-flight work with `cleanup()` or the provided `abortSignal`.\n\n```tsx\nimport { component$, isServer, useSignal, useTask$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const text = useSignal('Initial text');\n const delayText = useSignal('');\n\n useTask$(({ track }) => {\n // Passing a signal directly is more efficient than using a function.\n const newText = track(text);\n const update = () => (delayText.value = newText);\n isServer\n ? update() // don't delay on server render value as part of SSR\n : delay(500).then(update); // Delay in browser\n });\n\n return (\n <section>\n <label>\n Enter text: <input bind:value={text} />\n </label>\n <p>Delayed text: {delayText}</p>\n </section>\n );\n});\n\nconst delay = (time: number) => new Promise((res) => setTimeout(res, time));\n```\n\n**How track() Works Across Server and Browser**\n\nOn the server:\n\n- The `useTask$()` runs on the server and the `track()` function sets up a subscription on the `text` signal.\n- The page is rendered.\n\nOn the browser:\n- The `useTask$()` does not have to run or be downloaded eagerly because Qwik knows that the task is subscribed to the `text` signal from the server execution.\n- When the user types in the input box, the `text` signal changes. Qwik knows that the `useTask$()` is subscribed to the `text` signal and it is at this time that the `useTask$()` closure is brought into the JavaScript VM to be executed.\n\nThe `useTask$()` blocks rendering until it completes. If you don't want to block rendering, make sure that the task is resolved, and run the delay work on a separate unconnected promise. In this example, we don't await `delay()` because it would block rendering.\n\nSometimes it is required to only run code either in the server or in the client. This can be achieved by using the `isServer` and `isBrowser` booleans exported from `@qwik.dev/core` as shown above.\n\n### `track()` as a function\n\nIn the above example, `track()` was used to track a specific signal. However, `track()` can also be used as a function to track multiple signals at once.\n\n```tsx\nimport { component$, isServer, useSignal, useTask$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const isUppercase = useSignal(false);\n const text = useSignal('');\n const delayText = useSignal('');\n\n useTask$(({ track }) => {\n const value = track(() =>\n isUppercase.value ? text.value.toUpperCase() : text.value.toLowerCase()\n );\n const update = () => (delayText.value = value);\n isServer\n ? update() // don't delay on server render value as part of SSR\n : delay(500).then(update); // Delay in browser\n });\n\n return (\n <section>\n <label>\n Enter text: <input bind:value={text} />\n </label>\n <label>\n Is uppercase? <input type=\"checkbox\" bind:checked={isUppercase} />\n </label>\n <p>Delay text: {delayText}</p>\n </section>\n );\n});\n\nfunction delay(time: number) {\n return new Promise((resolve) => setTimeout(resolve, time));\n}\n```\n\nIn this example, the `track()` takes a function that not only reads the signal but also transforms its value to uppercase/lowercase. The `track()` subscribes to multiple signals and computes their value.\n\n### `cleanup()`\n\nSometimes when running a task, cleanup work needs to be performed. When a new task is triggered, the previous task's `cleanup()` callback is invoked. This callback is also invoked when the component is removed from the DOM.\n\n**cleanup() Behavior**\n\n- The `cleanup()` function is not invoked when the task is completed. It is only invoked when a new task is triggered or when the component is removed.\n- The `cleanup()` function is invoked on the server after the applications are serialized into HTML.\n- The `cleanup()` function is not transferable from server to browser. Cleanup is meant to release resources on the VM where it is running. It is not meant to be transferred to the browser.\n\nThis example shows how to implement a debounce feature using the `cleanup()` function.\n\n```tsx\nimport { component$, useSignal, useTask$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const text = useSignal('');\n const debounceText = useSignal('');\n\n useTask$(({ track, cleanup }) => {\n const value = track(() => text.value);\n const id = setTimeout(() => (debounceText.value = value), 500);\n cleanup(() => clearTimeout(id));\n });\n\n return (\n <section>\n <label>\n Enter text: <input bind:value={text} />\n </label>\n <p>Debounced text: {debounceText}</p>\n </section>\n );\n});\n```\n\n## `useVisibleTask$()`\n\nSometimes a task needs to run only on the browser and after rendering, in that case, you should use `useVisibleTask$()`. The `useVisibleTask$()` is similar to `useTask$()` but it only runs on the browser and after initial rendering. `useVisibleTask$()` registers a hook to be executed when the component becomes visible in the viewport, it will run at least once in the browser, and it can be reactive and re-execute when some **tracked** [state](/docs/core/state.md) changes.\n\n`useVisibleTask$()` has these properties:\n\n- runs on the client only.\n- eagerly executes code on the client when the component becomes visible.\n- runs after initial rendering.\n- does not block rendering.\n\n**Caution: useVisibleTask$() as a Last Resort**\n\nThe `useVisibleTask$()` should be used as a last resort, because it eagerly executes code on the client. Qwik, through [resumability](), goes out of its way to delay the execution of code on the client, and `useVisibleTask$()` is an escape hatch that should be used with caution. See [Best Practices](/docs/guides/best-practices.md#dont-register-events-eagerly-with-usevisibletask) for more details.\nIf you need to run a task on a client consider `useTask$()` with a server guard.\n\n```tsx\nimport { component$, isServer, useSignal, useTask$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const text = useSignal('Initial text');\n const isBold = useSignal(false);\n\n useTask$(({ track }) => {\n track(() => text.value);\n if (isServer) {\n return; // Server guard\n }\n isBold.value = true;\n delay(1000).then(() => (isBold.value = false));\n });\n\n return (\n <section>\n <label>\n Enter text: <input bind:value={text} />\n </label>\n <p style={{ fontWeight: isBold.value ? 'bold' : 'normal' }}>\n Text: {text}\n </p>\n </section>\n );\n});\n\nconst delay = (time: number) => new Promise((res) => setTimeout(res, time));\n```\n\nIn the above example, the `useTask$()` is guarded by `isServer`. The `track()` function is placed before the guard, which\nallows the server to set up the subscription without executing any code on the server. The client\nthen executes the `useTask$()` once the `text` signal changes.\n\nThis example shows how to use `useVisibleTask$()` to initialize a clock on the browser only when the clock component becomes visible.\n\n```tsx\nimport {\n component$,\n useSignal,\n useVisibleTask$,\n type Signal,\n} from '@qwik.dev/core';\n\nexport default component$(() => {\n const isClockRunning = useSignal(false);\n\n return (\n <>\n <div style=\"position: sticky; top:0\">\n Scroll to see clock. (Currently clock is\n {isClockRunning.value ? ' running' : ' not running'}.)\n </div>\n <div style=\"height: 200vh\" />\n <Clock isRunning={isClockRunning} />\n </>\n );\n});\n\nconst Clock = component$<{ isRunning: Signal<boolean> }>(({ isRunning }) => {\n const time = useSignal('paused');\n useVisibleTask$(({ cleanup }) => {\n isRunning.value = true;\n const update = () => (time.value = new Date().toLocaleTimeString());\n const id = setInterval(update, 1000);\n cleanup(() => clearInterval(id));\n });\n return <div>{time}</div>;\n});\n```\n\nThe clock's `useVisibleTask$()` does not run until the `` component becomes visible. The default behavior of `useVisibleTask$()` is to run the task when the component becomes visible. This behavior is implemented through [intersection observers](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).\n\nThe [intersection observers](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) will not run on components that are not considered visible such as ``.\n\n### Option `eagerness`\n\nAt times it is desirable to run `useVisibleTask$()` eagerly as soon as the application is loaded in the browser. In that case, the `useVisibleTask$()` needs to run in eager mode. This is done by using the `{ strategy: 'document-ready' }`.\n\n```tsx\nimport {\n component$,\n useSignal,\n useVisibleTask$,\n type Signal,\n} from '@qwik.dev/core';\n\nexport default component$(() => {\n const isClockRunning = useSignal(false);\n\n return (\n <>\n <div style=\"position: sticky; top:0\">\n Scroll to see clock. (Currently clock is\n {isClockRunning.value ? ' running' : ' not running'}.)\n </div>\n <div style=\"height: 200vh\" />\n <Clock isRunning={isClockRunning} />\n </>\n );\n});\n\nconst Clock = component$<{ isRunning: Signal<boolean> }>(({ isRunning }) => {\n const time = useSignal('paused');\n useVisibleTask$(\n ({ cleanup }) => {\n isRunning.value = true;\n const update = () => (time.value = new Date().toLocaleTimeString());\n const id = setInterval(update, 1000);\n cleanup(() => clearInterval(id));\n },\n { strategy: 'document-ready' }\n );\n return <div>{time}</div>;\n});\n```\n\nIn this example, the clock starts running immediately on the browser regardless of whether it is visible or not.\n\n### Advanced: Time of running, and managing visibility with CSS\n\nInternally, `useVisibleTask$` is implemented by adding an attribute to the first rendered component (either the returned component or in the case of a Fragment, its first child). With the standard `eagerness`, this means that if the first rendered component is hidden, the task will not run.\n\nThis means that you can use CSS to influence when the task runs. For example, if the task should only run on a mobile device, you can return a `<div class=\"md:invisible\" />` (in the case of Tailwind CSS).\n\nThis also means you cannot unhide a component using a visible task; for that you can return a Fragment:\n\n```tsx\nreturn (<>\n <div />\n <MyHiddenComponent hidden={!showSignal.value} />\n</>)\n```\n\n## Use Hook Rules\n\nWhen using lifecycle hooks, you must adhere to the following rules:\n\n- They can only be called at the root level of `component$` (not inside conditional blocks)\n- They can only be called at the root of another `use*` method, allowing for composition.\n\n```tsx\nuseHook(); // <-- does not work\n\nexport default component$(() => {\n useCustomHook(); // <-- does work\n if (condition) {\n useHook(); // <-- does not work\n }\n useTask$(() => {\n useNavigate(); // <-- does not work\n });\n const myQrl = $(() => useHook()); // <-- does not work\n return <button onClick$={() => useHook()}></button>; // <-- does not work\n});\n\nfunction useCustomHook() {\n useHook(); // <-- does work\n if (condition) {\n useHook(); // <-- does not work\n }\n}\n```\n"},{"id":"/docs/core/context/","title":"Context","description":"Dependency-style state sharing with `useContext` and `useContextProvider`.","url":"https://next.qwik.dev/docs/core/context/","content":"# Context\n\nQwik provides a context API, which solves the problem of props drilling and it is very similar to React's functional `useContext()`. In fact, Qwik's context API is the most efficient way to pass down data to different components, reducing overhead, generating less code, and allowing Qwik to more effectively [treeshake](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking) unused data.\n\nQwik's context API is made of 3 methods, importable from `@qwik.dev/core`:\n\n- [`createContextId(contextName: string): ContextId`](#createcontextid)\n- [`useContextProvider(ctx: ContextId, value: VALUE): void`](#usecontextprovider)\n- [`useContext(ctx: ContextId): VALUE`](#usecontext)\n\n```tsx /createContextId/#a /useContext/#b /useContextProvider/#c\nimport { type Signal, component$, useSignal } from '@qwik.dev/core';\nimport {\n useContext,\n useContextProvider,\n createContextId,\n} from '@qwik.dev/core';\n\nexport const ThemeContext = createContextId<Signal<string>>(\n 'docs.theme-context'\n);\n\nexport default component$(() => {\n const theme = useSignal('dark');\n useContextProvider(ThemeContext, theme);\n return (\n <>\n <button\n onClick$={() =>\n (theme.value = theme.value == 'dark' ? 'light' : 'dark')\n }\n >\n Flip\n </button>\n <Child />\n </>\n );\n});\n\nconst Child = component$(() => {\n const theme = useContext(ThemeContext);\n return <div>Theme is {theme.value}</div>;\n});\n```\n\nIn the above example, a `ContextId` named `docs.theme-context` is created and used to provide a `useSignal` to the `default` component. The `Child` component uses the `useContext` method to get the `useSignal` and render its value.\n\n## `createContextId()`\n\nThis method is used to create a new `ContextId`.\n\n```tsx\nexport interface GenericType {\n ...\n}\n\nexport const QwikRouterContext = createContextId<GenericType>(name: string): ContextId<GenericType>;\n```\n\n### Parameters\n\n- `name`: is a unique string given to `createContextId` as an identifier of the context. This will avoid conflicts when there are multiple contexts. It is advised to use a naming convention like `dev.qwik.router`.\n\n### Returns\n\nNotice that the value returned by `createContextId()` does not hold any state, it is an immutable ID object i.e. `{ id: 'dev.qwik.router' }`. It's only used to describe the name and type of the context, like an address or an identifier. Since it doesn't hold any state, it can be initialized as a singleton and exported from a shared module.\n\n## `useContextProvider()`\n\nThis method is used to create a Context for a specific component and its descendants, using the `ContextId` as the key identifier of the context.\n\n```tsx {9, 10, 11} /QwikRouterContext/#a /PlainArrayContext/#b /AppNameContext/#c title=\"src/components/Parent.tsx\"\nimport { component$, useStore, useContextProvider } from '@qwik.dev/core';\n\nexport const Parent = component$(() => {\n\n const qwikRouterObject = useStore<GenericType>({\n ...\n });\n\n useContextProvider(QwikRouterContext, qwikRouterObject);\n useContextProvider(PlainArrayContext, [1, 2, 3])\n useContextProvider(AppNameContext, \"My Qwik App\")\n\n return (\n <Children />\n );\n});\n```\n\n### Parameters\n\n- `ContextId`: A previously created Context must be supplied, serving as an identifier for the data being provided as the second parameter.\n\n- `data`: You can provide any data type, such as Qwik's useSignal, useStore, arrays, or objects.\n\n### Caveats\n\n- The provided value will not be globally available across the whole render tree, but only to descendant components in the tree.\n- If the context isn't used during Server-Side Rendering (SSR), it will not be serialized. If you need the context available on the client, even though it's not used during SSR, you should call `useContext()` in the parent component. This will force it to be serialized.\n\n## `useContext()`\n\nThis method is used to get the value of `Context` which is **provided** by Parent Component.\n\n```tsx {4,5,6} /useContext/ /QwikRouterContext/#a /PlainArrayContext/#b /AppNameContext/#c title=\"src/components/Children.tsx\"\nimport { component$, useContext } from '@qwik.dev/core';\n\nexport const Children = component$(() => {\n const qwikRouterObject = useContext(QwikRouterContext);\n const plainArray = useContext(PlainArrayContext);\n const appName = useContext(AppNameContext);\n\n return (\n <div>Child components can use any of the provided values, such as {appName}</div>\n );\n});\n```\n"},{"id":"/docs/core/slots/","title":"Slots","description":"Projected content and component composition patterns in Qwik.","url":"https://next.qwik.dev/docs/core/slots/","content":"# Slots\n\nSlots allow a component to treat the JSX children of the component as a form of input and project these children into the component's DOM tree.\n\nThis concept has different names in different frameworks:\n\n- In Angular is called Content Projection\n- In React, it's the `children` of the props\n- In Web components it's [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) as well\n\nThe main API to achieve this is the `<Slot>` component, exported in `@qwik.dev/core`:\n```tsx {6} /Slot/\nimport { Slot, component$ } from '@qwik.dev/core';\n\nconst Button = component$(() => {\n return (\n <button>\n Content: <Slot />\n </button>\n );\n});\n\nexport default component$(() => {\n return (\n <Button>\n This goes inside {'<Button>'} component marked by{`<Slot>`}\n </Button>\n );\n});\n```\n\nThe `<Slot>` component is a placeholder for the children of the component. The `<Slot>` component will be replaced by the children of the component during rendering.\n\n**Declarative Slots**\n\nSlots in Qwik are declarative, allowing Qwik to render parents and children in isolation. Because slots are declarative, the children can NOT be read, or transformed by the components.\n\nSlots in Qwik act like designated placeholders for content, allowing components to stay independent and avoid unnecessary re-renders. This setup keeps things flexible and easy to manage, unlike the direct children approach where parent changes can lead to frequent and complex child updates. Slots help maintain a smooth and efficient component structure.\n\nIn unique situations where some work needs to be done based on children, and the drawbacks of parents and children being lazy loaded together are understood, then an inline component is another choice.\n\n### Named Slots\n\nThe `Slot` component can be used multiple times in the same component, as long as it has a different `name` property:\n\n```tsx {9} /start/#a /title/#c /footer/#a /end/#c /q:slot/ /Slot/\nimport { Slot, component$, useStylesScoped$ } from '@qwik.dev/core';\nimport CSS from './index.css?inline';\n\nconst Tab = component$(() => {\n useStylesScoped$(CSS);\n return (\n <section>\n <h2>\n <Slot name=\"title\" />\n </h2>\n <div>\n <Slot /> {/* default slot */}\n <div>\n <Slot name=\"footer\" />\n </div>\n </div>\n </section>\n );\n});\n\nexport default component$(() => {\n return (\n <Tab>\n <div q:slot=\"title\">Qwik</div>\n <div>A resumable framework for building instant web applications</div>\n <span q:slot=\"footer\">made with by </span>\n <a q:slot=\"footer\" href=\"https://builder.io\">\n builder.io\n </a>\n </Tab>\n );\n});\n```\n\nNow, when consuming the `<Tab>` component, we can pass children and specify in which slot they should be placed, using the `q:slot` attribute:\n\nNotice that:\n\n- If `q:slot` is not specified or it's an empty string, the content will be projected into the default `<Slot>`, i.e. the `<Slot>` without a `name` property.\n- Multiple `q:slot=\"footer\"` attributes coalesce items together in the content projection.\n\n### Unprojected Content\n\nQwik keeps all content around, even if not projected. This is because the content could be projected in the future. When projected content does not match any `<Slot>` component, the content is moved into an inert `<q:template>` element.\n\n```tsx\nimport { Slot, component$, useSignal } from '@qwik.dev/core';\n\nconst Accordion = component$(() => {\n const isOpen = useSignal(false);\n return (\n <div>\n <h1 onClick$={() => (isOpen.value = !isOpen.value)}>\n {isOpen.value ? '▼' : '︎'}\n </h1>\n {isOpen.value && <Slot />}\n </div>\n );\n});\n\nexport default component$(() => {\n return (\n <Accordion>\n I am pre-rendered on the Server and hidden until needed.\n </Accordion>\n );\n});\n```\n\nResults in:\n\n```html\n<div>\n <h1>︎</h1>\n</div>\n<q:template hidden aria-hidden=\"true\">\n I am pre-rendered on the Server and hidden until needed.\n</q:template>\n```\n\nNotice that the un-projected content is moved into an inert `<q:template>`. This is done in case the `Accordion` component re-renders in the `<Slot>`. In this case, we avoid having to re-render the parent component just to generate the projected content. By persisting the un-projected content when the parent is initially rendered, the rendering of the two components can stay independent.\n\n### Invalid Projection\n\nThe `q:slot` attribute must be a direct child of a component.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\n\nexport const Project = component$(() => { ... })\n\nexport const MyApp = component$(() => {\n return (\n <Project>\n <span q:slot=\"title\">ok, direct child of Project</span>\n <div>\n <span q:slot=\"title\">Error, not a direct child of Project</span>\n </div>\n </Project>\n );\n});\n```\n\n## Advanced Example\n\nAn example of a collapsible component that conditionally projects editable content.\n\n```tsx\nimport { Slot, component$, useSignal } from '@qwik.dev/core';\n\nexport const Collapsible = component$(() => {\n const isOpen = useSignal(true);\n\n return (\n <div>\n <h1 onClick$={() => (isOpen.value = !isOpen.value)}>\n {isOpen.value ? '▼' : '︎'}\n <Slot name=\"title\" />\n </h1>\n {isOpen.value && <Slot />}\n </div>\n );\n});\n\nexport default component$(() => {\n const title = useSignal('Qwik');\n const description = useSignal(\n 'A resumable framework for building instant web applications'\n );\n return (\n <>\n <label>Title</label>\n <input bind:value={title} type=\"text\" />\n <label>Description</label>\n <textarea bind:value={description} cols={50} />\n <hr />\n <Collapsible>\n <span q:slot=\"title\">{title}</span>\n {description}\n </Collapsible>\n </>\n );\n});\n```\n\nThe `Collapsible` component will always display the title, but the body of the text will only display if `store.isOpen` is `true`.\n\nAdditionally, the `title` and `description` of the projected content are editable.\n\n- The parent component needs to be able to change content without forcing the `Collapsible` component to re-render.\n- The child component needs to change what is projected without having the parent component re-render. In our case, `Collapsible` should be able to show/hide the default `q:slot` without downloading and re-rendering the parent component.\n\nIn order for the two components to have an independent lifecycle, the projection needs to be declarative. In this way, either the parent or child can change what is projected or how it is projected without forcing the re-rendering of the other.\n\n### Projection vs `children`\n\nAll frameworks need a way for a component to wrap its complex content conditionally. This problem is solved in many different ways, but there are two predominant approaches:\n\n- **projection**: Projection is a declarative way of describing how the content gets from the parent template to where it needs to be projected.\n- **`children`**: `children` refers to vDOM approaches that treat content just like another input.\n\nThe two approaches can best be described as declarative vs imperative. They both come with their set of advantages and disadvantages.\n\nQwik uses the declarative projection approach because it needs to be able to render parent and child components independently from each other. In an imperative approach, there are countless ways a child component can modify the `children`. If a child component relied on its `children`, it would be forced to re-render every time the parent component re-rendered to reapply the changes. This additional rendering contradicts Qwik's goal of having components render in isolation.\n\nMake sure to use `` within a `component$()` function to ensure it works correctly. `` cannot operate in [inline components](/docs/core/overview.md#inline-components) which are similar to normal functions `export const MyInlineComp = () => `.\n\n### Advanced: Slots and Context\n\nSlotted components have access to the [Context](../context/) of their parent component, even while they aren't being projected. Furthermore, if the parent is projecting the `<Slot />` inside another component, the slotted components will also have access to the Contexts of that deeper component.\n\nHowever, if a component hasn't been projected yet because the `<Slot />` are rendered conditionally, it's impossible to know about the deeper Context, and then the slotted component will only see the Context of the immediate parent.\n\nAs such, it's safest to avoid these situations; if you are providing Contexts, don't conditionally render your `<Slot />`.\n"},{"id":"/docs/core/rendering/","title":"Rendering","description":"Rendering behavior, JSX output, and how Qwik updates and resumes DOM.","url":"https://next.qwik.dev/docs/core/rendering/","content":"# Rendering\n\nRendering is the process of updating the DOM based on changes in the state of the application and the component templates.\n\nQwik is unique because it knows how to render templates out-of-order asynchronously and in a fine-grained manner.\n\n## JSX\n\nJust like React, Qwik uses [JSX](https://facebook.github.io/jsx/) to express the component's template. Notice that JSX is only syntax, under the hood, React and Qwik are completely different. **JSX != VDOM**.\n\nQwik presents a few differences from other JSX frameworks:\n\n- Components are always declared with the `component$` function.\n- Components can use the `useSignal` hook to create reactive state.\n- Event handlers are declared with the `$` suffix.\n- For `<input>`, the `onChange` event is called `onInput$` in Qwik.\n- HTML attributes are preferred. `class` instead of `className`. `for` instead of `htmlFor`.\n\n```tsx /component$/#a /onClick$/#b /class/#c\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport const MyComponent = component$((props) => {\n const count = useSignal(0);\n return (\n <>\n <button\n onClick$={() => {\n count.value = count.value + props.step;\n }}\n >\n Increment by {props.step}\n </button>\n <main\n class={{\n even: count.value % 2 === 0, // conditional class\n odd: count.value % 2 === 1,\n }}\n >\n <h1>Count: {count.value}</h1>\n </main>\n </>\n );\n});\n```\n\n## Rendering Child Components\n\nQwik lazy loads components on an as-needed basis. To minimize the number of components to download, Qwik only descends into child components if the component's props have changed.\n\n```tsx {9} /Child/#a\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport const Parent = component$(() => {\n const count = useSignal(0);\n\n return (\n <>\n <button onClick$={() => (count.value += 1)}>Increment</button>\n <Child name={'World_' + count.value} />\n </>\n );\n});\n\nexport const Child = component$((props: { name: string }) => {\n return <p>Hello {props.name}</p>;\n});\n```\n\nIn the above example, the Parent component passes a changing `name` property to the Child component. The Child component will only re-render when the count signal changes.\n\n### Rendering a list of items\n\nQwik supports rendering lists with either `items.map()` or the experimental [`Each`](/docs/labs/each.md) component.\n\nFor keyed collections, prefer [`Each`](/docs/labs/each.md) once you have enabled it with `experimental: ['each']`. If you render with `items.map()`, every item in the list must have a unique `key` property on the first child returned by the mapping function. The `key` must be a string or number and must be unique within the list.\n\n```tsx {6} /data.map/ /key/#a\nimport { component$ } from '@qwik.dev/core';\n\nexport const Parent = component$(() => {\n return (\n <>\n {data.map(({ message, uniqueKey }) => (\n <div key={uniqueKey}>\n <p>{message}</p>\n </div>\n ))}\n </>\n );\n});\n```\n\nIt is not recommended to use the array's index as the key unless you can guarantee that the data for a given key will always be the same. It is always preferred to use some unique identifier from the data as the key.\n\n### Rendering Conditionally\n\nConditional rendering is done with the Javascipt [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) `?`, the `&&` operator, or just by using `if` statements.\n\nQwik also provides the experimental [`Show`](/docs/labs/show.md) component for QRL-based\nconditional control flow once it is enabled with `experimental: ['show']`.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const show = useSignal(false);\n return (\n <>\n <button onClick$={() => show.value = !show.value}>Toggle</button>\n {show.value ? <h1>Visible</h1> : <h1>Hidden</h1>}\n {show.value && <div>Only show when it's visible</div>}\n </>\n );\n});\n```\n\n### `dangerouslySetInnerHTML`\n\nQwik offers an attribute on HTML Elements called `dangerouslySetInnerHTML` as a replacement for calling `innerHTML` on the DOM.\n\nDue to cross-site-scripting (XSS) possibilities when rendering untrustworthy content, you must use `dangerouslySetInnerHTML` as a reminder that this operation might be dangerous.\n\n```tsx\nconst htmlString = \"<strong>hello</strong>\";\n<div dangerouslySetInnerHTML={htmlString}></div>\n```\n\n### `bind` Attribute\n\nThe `bind` attribute is a convenient API for two-way data binding of an `<input>` value to a `Signal`.\n\nFor checkbox inputs, you can use `bind:checked`, which binds the `checked` boolean to the specified signal.\n\n```tsx /bind:value/ /bind:checked/ /firstName/#a /acceptConditions/#b\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const firstName = useSignal('');\n const acceptConditions = useSignal(false);\n\n return (\n <form>\n <input type=\"text\" bind:value={firstName} />\n <input type=\"checkbox\" bind:checked={acceptConditions} />\n\n <div>First name: {firstName.value}</div>\n </form>\n );\n})\n```\n\nThe API does not work with `useStore` since it does not return a signal. You can still use the manual approach, combining value and onInput$ as shown below.\n\nThe `bind:` is compiled away by the Qwik optimizer to a property set and an event handler, ie, it is just syntax sugar.\n\n```tsx /bind:value/ /bind:checked/ /firstName/#a /acceptConditions/#b\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const count = useSignal(0);\n const firstName = useSignal('');\n const acceptConditions = useSignal(false);\n\n return (\n <form>\n {/* For number inputs, use `valueAsNumber` instead of `value` to get the numeric value directly */}\n <input type=\"number\"\n value={count.value}\n onInput$={(_, el) => count.value = el.valueAsNumber }\n />\n <input type=\"text\"\n value={firstName.value}\n onInput$={(_, el) => firstName.value = el.value }\n />\n <input type=\"checkbox\"\n checked={acceptConditions.value}\n onChange$={(_, el) => acceptConditions.value = el.checked }\n />\n <div>First name: {firstName.value}</div>\n </form>\n );\n})\n```\n\nThis API ensures that the `value` of the input is always in sync with the value of the signal, no matter where the change comes from.\n\n## Async Rendering\n\nIt is important for the rendering pipeline to be able to lazy load child components. Since lazy loading is an asynchronous operation, rendering must also be asynchronous. In practice, this means that the `render()` function must return a promise.\n\nMost current-generation frameworks have a synchronous `render()` process. Synchronous rendering can't easily deal with asynchronous code loading, so synchronous rendering necessitates that all dependant components are eagerly present before rendering can commence.\n\n## Render Batching\n\nWhenever the state of the application changes, Qwik will schedule a render operation. The render operation will be scheduled to run after a macro-task (e.g. `setTimeout(0)`). This allows the application to batch multiple state changes into a single render operation.\n\nIn addition, because of the asynchronous nature of Qwik, all DOM writes are buffered and only flushed once all of the components have been downloaded and their JSX functions executed. The result is that the UI will update as an atomic operation, and the user will not see the intermediate steps, even if the application is slow to render.\n\nThe end goal is to enable performance and consistent rendering, even in the context of fast changing state and slow network.\n\n## Rendering Work That Waits\n\nSometimes part of the UI needs to wait before it can show content, such as showing a fallback while a profile card, search result, or other section is still being prepared.\n\nWrap that part of the UI in [`<Pending>`](/docs/labs/pending.md) when you want a fallback boundary:\n\n```tsx /Pending/\nimport { component$, Pending } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <Pending fallback$={() => <p>Loading...</p>}>\n <UserCard />\n </Pending>\n );\n});\n```\n\n`<Pending>` does not define the work. It only controls what renders while that part of the UI waits.\n\n## Fine-grained Reactivity\n\nThanks to the fine-grained reactivity of Qwik, only the components that depend on the state will be updated. This is a big performance gain for two reasons:\n\n1. Less code to execute means application updates will render faster.\n2. Less code to execute means oftentimes the code does not have to be downloaded on application startup (or ever).\n"},{"id":"/docs/core/styles/","title":"Styles","description":"Styling patterns including scoped styles, inline styles, and stylesheet loading.","url":"https://next.qwik.dev/docs/core/styles/","content":"# Styles\n\nQwik does not enforce a specific styling approach, you can style your Qwik app using any method you prefer, such as CSS, CSS-in-JS, CSS modules...\n\n## CSS Modules\n\nQwik supports [CSS Modules](https://github.com/css-modules/css-modules) out of the box thanks to [Vite](https://vitejs.dev/guide/features.html#css-modules).\n\nTo use CSS modules, simply create a `.module.css` file. For example, `MyComponent.module.css` and import it in your component.\n\n```css /container/#a title=\"src/components/MyComponent/MyComponent.module.css\"\n.container {\n background-color: red;\n}\n```\n\nThen, import the CSS module in your component.\n\n```tsx {2} /styles/ /container/#a title=\"src/components/MyComponent/MyComponent.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport styles from './MyComponent.module.css';\n\nexport default component$(() => {\n return <div class={styles.container}>Hello world</div>;\n});\n```\n\nRemember that Qwik uses `class` instead of `className` for CSS classes.\n\nQwik also accepts arrays, objects, or a combination of them to assign multiple classes:\n```tsx title=\"src/components/MyComponent/MyComponent.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport styles from './MyComponent.module.css';\n\nexport default component$((props) => {\n // Array syntax example\n return <div class={[\n styles.container,\n 'p-8',\n props.isHighAttention ? 'text-green-500' : 'text-slate-500',\n { active: true}\n ]}>Hello world</div>;\n\n // Object syntax example\n return <div class={{\n 'text-green-500': props.isHighAttention,\n 'p-4': true\n }}>Hello world</div>;\n});\n```\n\n## Global Styles\n\nMany apps use a global stylesheet for browser resets and defining global styles. This is a good practice, but it is not recommended to use it for styling your components. Qwik is optimized to let the browser download the styles that are needed for the current view. If you use a global stylesheet, all of the styles will be downloaded on the first load, even if they are not needed for the current view.\n\n```tsx\nimport './global.css';\n```\n\nAutomatically, Qwik will try to inline this file in production mode if the amount of CSS is less than 10KB. If the file is larger than 10KB, it will be loaded as a separate file.\n\n## CSS-in-JS\n\nQwik has first-class CSS-in-JS support using [styled-vanilla-extract](https://github.com/wmertens/styled-vanilla-extract), which provides an extremely efficient css-in-js solution without any runtime!\n\n```tsx title=\"style.css.ts\"\nimport { style } from 'styled-vanilla-extract/qwik';\n\nexport const blueClass = style({\n display: 'block',\n width: '100%',\n height: '500px',\n background: 'blue',\n});\n```\n\n```tsx title=\"component.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { blueClass } from './styles.css';\n\nexport const Cmp = component$(() => {\n return <div class={blueClass} />;\n});\n```\n\n```shell\npnpm run qwik add styled-vanilla-extract\n```\n\nPlease refer to the [docs of our official integration](/docs/integrations/styled-vanilla-extract.md) for more information.\n\nWhile extremely popular, emotion and other CSS-in-JS libs are not the best choice for Qwik. [They are not optimized for runtime performance and they don't have a good SSR streaming support](https://dev.to/srmagura/why-were-breaking-up-wiht-css-in-js-4g9b), leading to a degraded server and client performance.\n\n## Styled-components\n\nThe styled-components library is a popular tool in React-land for writing CSS-in-JS. Thanks to the same [styled-vanilla-extract](https://github.com/wmertens/styled-vanilla-extract) plugin, you can write your styles with styled-components syntax in Qwik with zero-runtime cost!\n\n```shell\npnpm run qwik add styled-vanilla-extract\n```\n\nLike this:\n\n```tsx title=\"styles.css.ts\"\nimport { styled } from 'styled-vanilla-extract/qwik';\n\nexport const BlueBox = styled.div`\n display: block;\n width: 100%;\n height: 500px;\n background: blue;\n`;\n```\n\n```tsx title=\"component.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { BlueBox } from './styles.css';\n\nexport const Cmp = component$(() => {\n return <BlueBox />;\n});\n```\n\n## Scoped CSS\n\nTo use scoped CSS, you can use the `useStylesScoped$()` hook exported from `@qwik.dev/core`.\n`useStylesScoped$()` uses an emoji to set a unique name on the selector, to avoid CSS name / selector clashes, and to ensure that the styles are correctly scoped as expected.\n\n```tsx {4-8} title=\"src/components/MyComponent/MyComponent.tsx\"\nimport { component$, useStylesScoped$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n useStylesScoped$(`\n .container {\n background-color: red;\n }\n `);\n return <div class=\"container\">Hello world</div>;\n});\n```\n\nYou can also import an external CSS file. For that you need to add the `?inline` query parameter to the import of the CSS file, and pass the default export of the CSS file to the `useStyleScoped$()` hook.\n\n```css title=\"src/components/MyComponent/MyComponent.css\"\n.container {\n background-color: red;\n}\n```\n\n```tsx {3,6} title=\"src/components/MyComponent/MyComponent.tsx\"\nimport { component$, useStylesScoped$ } from '@qwik.dev/core';\n\nimport styles from './MyComponent.css?inline';\n\nexport default component$(() => {\n useStylesScoped$(styles);\n return <div class=\"container\">Hello world</div>;\n});\n```\n\n### `:global()` selector\n\nUsing `useStylesScoped$` will scope all child selectors in a ruleset to the component. If you need to style child components rendered through a `<Slot />`, you will need to break out of the scoped styles using the `:global()` selector.\n\n```tsx\nimport { useStylesScoped$, component$ } from '@qwik.dev/core';\n\nexport const List = component$(() => {\n useStylesScoped$(`\n .list {\n display: flex;\n\n > :global(*nth-child(3)) {\n width: 100%\n }\n }\n `);\n\n return (\n <div class=\"list\">\n <Slot />\n </div>;\n );\n});\n```\n\nThis will render a css selector of `.list.8vzca0-0 > *:nth-child(3)`, allowing you to target child components. This could be considered the equivalent of using `::ng-deep` in Angular.\n\nBeware that this may have unintended effects that cascade down your component tree.\n\n## `useStyles$()`\n\nA lazy-loadable reference to component's styles.\n\nComponent styles allow Qwik to lazy load the style information for the component only when needed, which avoids double loading during SSR hydration.\n\n```tsx\nimport { useStyles$, component$ } from '@qwik.dev/core';\nimport styles from './code-block.css?inline';\n\nexport const CmpStyles = component$(() => {\n useStyles$(styles);\n return <span class=\"my-text\">Some text</span>;\n});\n```\n\n```css\n// code-block.css\n.my-text {\n color: red;\n}\n```\n\nIn order to import CSS as a string in Vite, you need to add the `?inline` query parameter to the import, like this: `import styles from './code-block.css?inline';`\n\n`useStyles$` uses lazy loading strings that won't dynamically update. If you'd like to evaluate some JS, use a `style` tag instead\n\n```tsx\nexport const CmpStyles = component$(() => {\n const primaryColor = \"red\";\n\n // Does not work\n useStyles$(`\n .my-text {\n --primary-color: ${primaryColor};\n }\n `);\n\n // Adding in the style attribute works\n return (\n <span\n style={{ \"--primary-color\": primaryColor }}\n class=\"my-text\"\n >\n Some text\n </span>\n );\n});\n```\n\n## CSS Preprocessors\n\nThanks to [Vite](https://vitejs.dev/guide/features.html#css-pre-processors), Qwik supports CSS preprocessors like Sass, Less, Stylus, and PostCSS.\n\nThere is no need to install Qwik-specific plugins for them, but the corresponding pre-processor itself must be installed:\n\n```shell\n# .scss and .sass\npnpm add -D sass\n\n# .less\npnpm add -D less\n\n# .styl and .stylus\npnpm add -D stylus\n```\n\nCheck [Vite's docs](https://vitejs.dev/guide/features.html#css-pre-processors) for more information.\n\n## Tailwind\n\nTo use Tailwind in your app, you can add it to your app with our built-in integration:\n\n```shell\npnpm run qwik add tailwind\n```\n\nCheck out [the integration docs](/docs/integrations/tailwind.md) for more information.\n\n## PostCSS\n\nIt is also possible to use PostCSS in your app with our built-in integration:\n\n```shell\npnpm run qwik add postcss\n```\n\nImportant: Since we are using vite, the configuration should look as follows to work:\n\n```shell\n// Configuration with vite\nmodule.exports = {\n plugins: {\n autoprefixer: {},\n \"postcss-preset-env\": {\n stage: 3,\n features: {\n \"nesting-rules\": true,\n },\n },\n },\n}\n```\n\nNow you will be able to use CSS with nesting-rules like the following ones:\n\n```css\nbody {\n & .box {\n background: red;\n\n &:hover {\n background: yellow;\n }\n }\n}\n```\n\nCheck out [the integration docs](/docs/integrations/postcss.md) for more information.\n\n## Why not inline styles using the `<style>` tag?\n\nA naive way to ensure that a component has the correct styles loaded is to inline the style information into a component like so.\n\n```tsx\nexport const MyComponent = () => {\n return (\n <>\n <style>.my-class { color: red; }</style>\n My Component\n </>\n );\n}\n```\n\nThe problem with this approach is that we will load styles twice.\n\n1. The styles are inserted into the HTML as part of the SSR.\n2. Then when the component is invalidated and needs to be re-rendered, the styles are loaded again because they are inlined.\n\nWhat is needed is to load the styles independently from the component. This is what [`useStyles$()`](/docs/core/styles.md#usestyles) is for. There are two scenarios:\n\n1. The component is rendered on the server and the styles are inserted into `<head>` as part of the SSR.\n - Adding a new instance of a component to the application does not require that we load the styles as they are already included as part of SSR.\n2. The component is rendered on the client for the first time. In that case, the new component does not have styles in the `<head>` as the component was not part of SSR.\n - Adding a new component that was not part of SSR requires that styles are loaded and inserted into `<head>`.\n"},{"id":"/docs/routing/","title":"Routing","description":"File-based routing fundamentals, route folders, params, and navigation concepts.","url":"https://next.qwik.dev/docs/routing/","content":"# Routing\n\nRouting in Qwik Router is file-system based like [Next.js](https://nextjs.org/docs/routing/introduction), [SvelteKit](https://kit.svelte.dev/docs/routing), [SolidStart](https://start.solidjs.com/core-concepts/routing) or [Remix](https://remix.run/docs/en/main/guides/routing). Files and directories in the `src/routes` have a role in the routing of your application.\n\n- **Directories:** Define the URL segments to match by the router.\n- **`index.tsx/mdx` files:** Define a [page](/docs/pages.md).\n- **`index.ts` file:** Define an [endpoint](/docs/endpoints.md).\n- **`layout.tsx` files:** Define nested [layout](/docs/layout.md) and/or a [middleware](/docs/middleware.md).\n\n[Video](https://cdn.builder.io/o/assets%2FYJIGb4i01jvw0SRdL5Bt%2Fabf8f471ba884b938d0863d85ed4c50f%2Fcompressed?apiKey=YJIGb4i01jvw0SRdL5Bt&token=abf8f471ba884b938d0863d85ed4c50f&alt=media&optimized=true)\n\n## Directory-based routing\n\nOnly the directory names are used to match the incoming requests to pages/endpoint/middleware.\n\nFor example, if you have a file at `src/routes/some/path/index.tsx`, it will be mapped to the URL path `https://example.com/some/path`.\n\n```bash title=\"Directory layout\"\nsrc/\n`-- routes/\n |-- contact/\n | `-- index.mdx # https://example.com/contact\n |-- about/\n | `-- index.md # https://example.com/about\n |-- docs/\n | `-- [id]/\n | `-- index.ts # https://example.com/docs/1234\n | # https://example.com/docs/anything\n |-- [...catchall]/\n | `-- index.tsx # https://example.com/anything/else/that/didnt/match\n |\n `-- layout.tsx # This layout is used for all pages\n```\n\n- **`[id]`** is a directory that represents a dynamic route segment, in this example `id` is the string parameter accessible by `useLocation().params.id`.\n- **`[...catchall]`** is a directory that represents a dynamic catch-all route, in this example `catchall` is the string parameter accessible by `useLocation().params.catchall`.\n- **`index.tsx|mdx` files** are the pages/endpoints/middleware.\n- **`layout.tsx` files** are the layouts.\n\n### Dynamic route segments\n\nSpecial named directories with square brackets, such as `[paramName]` and `[...catchAll]` can be used to match route segments which are dynamic:\n\n```bash title=\"Directory layout\"\nsrc/routes/blog/index.tsx → /blog\nsrc/routes/user/[username]/index.tsx → /user/:username (/user/foo)\nsrc/routes/post/[...all]/index.tsx → /post/* (/post/2020/id/title)\n```\n\n```bash title=\"Directory layout\"\nsrc/\n`-- routes/\n |-- blog/\n | `-- index.tsx # https://example.com/blog\n |-- post/\n | `-- [...all]/\n | `-- index.tsx # https://example.com/post/2020/id/title\n `-- user/\n `-- [username]/\n `-- index.tsx # https://example.com/user/foo\n```\n\nThe folder `[username]` can be any of the thousands of users that you have in your database. It would be impractical to create a route for each user. Instead, you need to define a Route Parameter (a part of the URL) that will be used to extract the `[username]`.\n\n```tsx title=\"src/routes/user/[username]/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { useLocation } from '@qwik.dev/router';\n\nexport default component$(() => {\n const loc = useLocation();\n return <div>Hello {loc.params.username}!</div>;\n});\n```\n\n### Route priority\n\nWhen more than one route matches a URL, the most specific one wins. Qwik Router compares matching routes segment by segment, from left to right: a static segment beats a `[param]`, and a `[param]` beats a `[...catchAll]`. The folder order and route group names don't matter.\n\n```bash title=\"Directory layout\"\nsrc/routes/(marketing)/pricing/index.tsx → /pricing\nsrc/routes/(rss)/[section]/feed.xml/index.tsx → /news/feed.xml\nsrc/routes/(pages)/[section]/[topic]/index.tsx → /news/today\nsrc/routes/(app)/[org]/[...path]/index.tsx → /acme/settings/billing\n```\n\n- `/pricing` matches `pricing/`, and also `[org]/[...path]` with an empty `path`. The static segment wins.\n- `/news/feed.xml` matches all three dynamic routes. The static `feed.xml` segment is more specific than `[topic]` or `[...path]`, so the feed wins.\n- `/pricing/plans/pro` doesn't fit `pricing/` or the two-segment routes, so it falls through to `[org]/[...path]` with `org` set to `pricing`. A URL only ends up at a 404 page when no route matches it at all.\n\nIf a catch-all shouldn't handle URLs under a static page, check for that prefix in the catch-all's `onRequest` or `onGet` handler and throw `error(404, ...)`.\n\n## `index` files\n\nInside the `src/routes` directory, all files named `index` are considered pages/endpoint/middleware, Qwik supports the following extensions: `.ts`, `.tsx`, `.md` and `.mdx`.\n\nPages/endpoint/middleware are the leaf nodes of the routing tree, i.e., **the modules that will handle the request and return an HTTP response**.\n\n### Page `index.tsx`\n\nWhen an `index.tsx` or `index.ts` file exports a Qwik component as the default export, Qwik Router will render the component and return an HTML response as a webpage.\n\n```tsx title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return <h1>Hello World</h1>;\n});\n```\n\n### Endpoint `index.ts`\n\nAn `index.ts` file can access the HTTP request directly and return a raw HTTP response without involving any Qwik Component. This is done by exporting any of the following methods: `onRequest`, `onGet`, `onPost`, `onPut` or `onDelete` depending on how you want to handle a specific HTTP request.\n\n```tsx title=\"src/routes/index.ts\"\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = ({ json }) => {\n json(200, { message: 'Hello World' });\n};\n```\n\nIn the last example, there is no default export. This is because you are not rendering a Qwik component, but rather you are handling the request directly and returning a JSON response. This is useful for implementing RESTful APIs or any other type of HTTP endpoint.\n\n### Page + Endpoint\n\nIn Qwik Router there is no clear separation between pages and endpoints. An `index.tsx` file handles both and exports a Qwik component or an `onRequest` method. However, it's possible to combine both approaches. For example, you can export an `onRequest` method that will handle the request, and then render a Qwik component.\n\n```tsx title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onRequest: RequestHandler = ({ headers, query, json }) => {\n headers.set('Cache-Control', 'private');\n if (query.get('format') === 'json') {\n json(200, { message: 'Hello World' });\n }\n};\n\nexport default component$(() => {\n return <h1>Hello World</h1>;\n});\n```\n\nIn this example, a request handle will always set the `Cache-Control` header to `private` and the page will be rendered as an HTML page, but if the request contains a `format=json` query param, the endpoint will return a JSON response instead.\n\n## `layout.tsx` files\n\nLayout modules are very similar to `index` files. Both can handle requests and render Qwik components. However, layouts are designed to work like middleware, allowing to **share UI and request handling (middleware)** to a set of routes.\n\nUsually, different pages need some common request handling and share some UI. For example, picture a dashboard site where all the pages are under the `/admin/*` directory:\n\n- **Shared request handling:** The request cookies need to be validated before even rendering the page, otherwise, render a blank 401 page.\n- **Shared UI:** All pages share a common header showing the user's name and profile picture.\n\nInstead of repeating the same code in each route, use layouts to automatically reuse common parts. Layouts also support adding middleware to the route.\n\nTake this `src/routes` directory as an example:\n\n```bash title=\"Directory layout\"\nsrc/\n`-- routes/\n |-- admin/\n | |-- layout.tsx <-- This layout is used for all pages under /admin/*\n | `-- index.tsx\n |-- layout.tsx <-- This layout is used for all pages\n `-- index.tsx\n```\n\n### Middleware Layouts\n\nLayouts can implement request handling using any of the following methods: `onRequest`, `onGet`, `onPost`, `onPut` or `onDelete`. This means they can be used to implement middleware. For example, they can be used to validate the request cookies before rendering the page.\n\nFor the route `https://example.com/admin`, the `onRequest` methods will be executed in the following order:\n\n1. `src/routes/layout.tsx`'s `onRequest`\n2. `src/routes/admin/layout.tsx`'s `onRequest`\n3. `src/routes/admin/index.tsx`'s `onRequest`\n4. `src/routes/admin/index.tsx`'s component\n\nAn `onRequest` handler in `src/routes/index.tsx` doesn't get executed.\n\n### Full Execution order\n\n```bash\n1 --> [entry.express.ts or entry.preview.ts]\n2 --> [plugin@some-name.ts] #Alphabetical order\n3 --> [server$]\n4 --> [entry.ssr.ts]\n5 --> [root.tsx]\n6 --> [layout.tsx onRequest -> onGet/onHttpVerb]\n7 --> [globalLoaders]\n8 --> [routeLoaders]\n9 --> [jsx/components on a route]\n```\n\n### Nested Layouts\n\nLayouts also **provide a way to add common UI to the rendered page**. For example, if you want to add a common header to all of the routes, add a Header component to the root layout.\n\nFor the given example, the Qwik components will be rendered in the following order:\n\n1. `src/routes/layout.tsx`'s component\n2. `src/routes/admin/layout.tsx`'s component\n3. `src/routes/admin/index.tsx`'s component\n\n```tsx\n<RootLayout>\n <AdminLayout>\n <AdminPage />\n </AdminLayout>\n</RootLayout>\n```\n\n## SPA Navigation\n\nWith Qwik, the distinction between MPA and SPA disappears; every app can be both at the same time.\nThe choice is no longer an architectural design determined at the beginning of the project,\ninstead, this decision can be made for every link.\n\nQwik provides a `<Link>` component and `useNavigate()` hook.\nThese can be used to initiate an SPA refresh or navigation between pages.\n\nThe `Link` component is the recommended way to navigate as it uses the HTML `<a>` tag,\n which is the most accessible way to move between pages.\nHowever, if you need to navigate programmatically, you can use the `useNavigate()` hook.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Link, useNavigate } from '@qwik.dev/router';\n\nexport default component$(() => {\n const nav = useNavigate();\n return (\n <div>\n <Link href=\"/about\">About (preferred)</Link>\n <button onClick$={() => nav('/about')}>About</button>\n </div>\n );\n});\n```\n\nThe `Link` component uses the `useNavigate()` hook internally.\n\n### Preventing navigation\n\nUse [`usePreventNavigate$`](/docs/advanced/prevent-navigation.md) to prevent navigation while your app's state is unsaved.\n\n### `<Link reload>`\n\nThe `Link` component with the `reload` prop can be used together to refresh the current page.\nYou can also call the `nav()` function from the `useNavigate()` hook, without arguments.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Link, routeLoader$, useNavigate } from '@qwik.dev/router';\n\nexport const useServerTime = routeLoader$(() => {\n // This will re-execute in the server when the page refreshes.\n return Date.now();\n});\n\nexport default component$(() => {\n const nav = useNavigate();\n const serverTime = useServerTime();\n\n return (\n <div>\n <Link reload>Refresh (better accessibility)</Link>\n <button onClick$={() => nav()}>Refresh</button>\n <p>Server time: {serverTime.value}</p>\n </div>\n );\n});\n```\n\nWhen the page refreshes, all the matching `routeLoader$` and server handlers (`onRequest`) will re-execute in the server and the UI will re-render accordingly.\n\nWhile refreshing the page, the `isNavigating` boolean from `useLocation()` will be `true` until the page is fully rendered.\n\n### `<Link>` prefetching\n\nUse `prefetchBundles` and `prefetchData` to control what a link prefetches and when it starts.\n\nBy default, `prefetchBundles` uses `visible`, while `prefetchData` uses `intent`, so route bundles\nare prefetched when the link enters the viewport and route data is prefetched when the user shows\nnavigation intent.\n\nFor the full list of strategies, examples, and deprecated `prefetch` behavior, see\n[`<Link>` prefetch in the API reference](/docs/api.md#prefetch).\n\n### Scroll Restoration\n\nQwik provides best-in-class scroll restoration for SPA's that closely mimics the native browser experience.\nYour users should receive the exact same experience they've come to expect natively from an MPA,\nexcept with all the added benefits of an SPA.\n\nAfter you use one of the above methods to navigate, the user is automatically upgraded to an SPA.\nThis means that the current page, and the page they came from, now have an `SPA` context associated with them.\n\nIf a user then clicks a regular `<a>` tag, they will perform a regular navigation. This new page will have no SPA context,\nand is effectively downgraded back to an MPA. You can swap between these as necessary,\nand the user's experience will seamlessly switch between MPA and SPA as if it were all the same.\n\nWhen a user re-visits the SPA-enabled history entries, such as with a refresh, back/forward button, browser session restarts, etc.,\nQwik will automatically restore their scroll position and bootstrap itself back into the SPA context as needed.\n\nThe script required to provide this robust experience never loads, nor is it ever even sent to the user's browser, unless the history entry has had an SPA context. Pure MPA pages never load this script. This is the magic of Qwik.\n\nScroll restoration in Qwik always occurs synchronously with render. When combined with Qwik's resumable and first-class SSR/MPA nature, the user should never experience scroll flashing.\n\nQwik's scroll restoration is entirely `history` based. This is different from many other frameworks\nwhich rely on things like `sessionStorage`.\n\nQwik's ability to remember and restore scroll positions is extremely robust\nand will survive everything from browser session restarts to users clearing their browser data,\nwhich is not the case for many other frameworks.\n\n**Using pushState() and replaceState() during SPA**\n\nOn a page with an SPA context, Qwik will patch the `pushState()` and `replaceState()` functions on the global `history`.\nThis is to ensure that any custom states you add as a developer, also receive the SPA context.\n\nWhile these are patched, states you `push` or `replace` should always be an actual `Object` type.\nThis is because Qwik needs to be able to automatically append the SPA context to the state as a property.\n\nIf you provide a value that is not an object, Qwik will create a new object for state and add your provided\nvalue to a new key: `{ _data: <your_value> }`\n\nQwik will also warn you in the browser's console in `dev` mode when this occurs.\n\n## Request Event\n\nEach request handler, such as `onRequest`, `onGet`, `onPost`, etc., are passed in a `RequestEvent` object as the first argument to the handler. The `RequestEvent` object contains utility functions and properties to get and set values to the server's request and response. This object contains the following properties:\n\n- `basePathname`: The base pathname of the request, which can be configured at build time. Defaults to `/`.\n- `cacheControl`: Convenience function to set the [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) response header.\n- `cookie`: HTTP request and response [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies). Use the `get()` method to retrieve a request cookie value. Use the `set()` method to set a response cookie value.\n- `env`: Platform provided environment variables.\n- `error`: When called, the response will immediately end with the given status code. This could be useful to end a response with `404`, and use the 404 handler in the routes directory. See [Status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) for which status code should be used.\n- `getWritableStream`: Low-level access to write to the HTTP response stream. Once `getWritableStream()` is called, the status and headers can no longer be modified and will be sent over the network.\n- `headers`: HTTP [response headers](https://developer.mozilla.org/en-US/docs/Glossary/Response_header).\n- `html`: Convenience method to send an HTML body response. The response will be automatically set the `Content-Type` header to`text/html; charset=utf-8`. An `html()` response can only be called once.\n- `internalRequest`: Identifies Qwik Router internal JSON requests as `'loader'` or `'action'`. Returns `false` for normal page requests. Check this before applying broad rewrite rules.\n- `json`: Convenience method to JSON stringify the data and send it in the response. The response will be automatically set the `Content-Type` header to`application/json; charset=utf-8`. A `json()` response can only be called once.\n- `locale`: Which locale the content is in. The locale value can be retrieved from selected methods using `getLocale()`.\n- `method`: HTTP request [method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) value.\n- `next`: Call the next request handler. This is useful for middleware.\n- `params`: URL path params which have been parsed from the current url pathname segments. Use `query` to instead retrieve the query string search params.\n- `parseBody`: This method will check the request headers for a `Content-Type` header and parse the body accordingly. It supports `application/json`, `application/x-www-form-urlencoded`, and `multipart/form-data` content types. If the `Content-Type` header is not set, it will return `null`.\n- `pathname`: URL pathname value. Does not include the protocol, domain, query string (search params) or hash.\n- `platform`: Platform specific data and functions.\n- `query`: URL query string [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) value. Use `params` to instead retrieve the route params found in the url pathname.\n- `redirect`: URL to redirect to. When called, the response will immediately end with the correct redirect status and headers. See [Redirects](https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections) for which status code should be used.\n- `request`: HTTP [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request).\n- `send`: Send a body response. The `Content-Type` response header is not automatically set when using `send()` and must be set manually. A `send()` response can only be called once.\n- `sharedMap`: Shared Map across all the request handlers. Every HTTP request will get a new instance of the shared map. The shared map is useful for sharing data between request handlers.\n- `status`: HTTP response [status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status). Sets the status code when called with an argument. Always returns the status code, so calling `status()` without an argument can be used to return the current status code.\n- `text`: Convenience method to send a text body response. The response will be automatically set the `Content-Type` header to`text/plain; charset=utf-8`. A `text()` response can only be called once.\n- `url`: HTTP request [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL).\n\n## Rewrite Routes\n\nYou can rewrite your pathnames in order to reuse one single page component with its own middlewares and layouts for multiple pages.\nThis could be useful for SEO purposes or to translate your pages in different languages.\n\n**Translate localized urls with prefix**\n\nFor localization purposes you may want to translate your routes from `/products` to `/it/prodotti`\nor to `/fr/produits` and `/products/product-name` to `/it/prodotti/nome-prodotto` or `/fr/produits/nom-du-produit`\nwithout having multiple routes files for each locale but reusing the same page component, layouts, middlewares and so on.\n\nThe parameters name will not be changed so if the route file is `/products/[slug]/index.tsx` and the url is `/products/product-name`,\n`/it/prodotti/nome-prodotto` or `/fr/produits/nom-du-produit` you will receive the same path parameter `slug` with\nthe values `product-name`, `nome-prodotto` or `nom-du-produit`.\n\n**Rewrite urls without prefix**\n\nIt's rare but you may want to have aliases for the same path.\nFor example you may want both `/docs` and `/documents` to be rendered from the same page component or\nyou may want to translate `/products` to `/prodotti` without adding the `/it` prefix.\n\nIn each folder within the routes directory where there are instances of the paths keys in the pathname, the route node will be duplicated, and all occurrences of paths keys will be replaced with their corresponding paths values.\nAll path parameters will preserve the same name. If there is a prefix it will be added at the beginning of the rewritten pathname.\n\nYou can set the rewrite rules as follows in your `vite.config.ts`:\n\n```tsx\nimport { defineConfig } from 'vite';\nimport { qwikRouter } from '@qwik.dev/router/vite';\n\nexport default defineConfig(async () => {\n return {\n plugins: [\n qwikRouter({\n rewriteRoutes: [\n {\n paths: {\n 'docs': 'documentation'\n },\n },\n {\n prefix: 'it',\n paths: {\n 'docs': 'documentazione',\n 'getting-started': 'per-iniziare',\n 'products': 'prodotti',\n },\n },\n ],\n }),\n ],\n };\n});\n```\n\nBy default a config rewrites every matching route. Add `exclude` to skip routes that should not be rewritten under that config. The patterns use the same glob syntax as the SSG `include`/`exclude` and are matched per config:\n\n```tsx\nrewriteRoutes: [\n {\n prefix: 'it',\n paths: {\n 'docs': 'documentazione',\n 'products': 'prodotti',\n },\n // `/blog` stays English-only: no `/it` mirror is generated for it.\n exclude: ['/blog/*'],\n },\n],\n```\n\n## Advanced routing\n\nQwik Router also supports:\n\n- [Route Parameters](/docs/advanced/routing.md)\n- [Nested layouts](/docs/advanced/routing.md#nested-layout)\n- [Menus](/docs/advanced/menu.md)\n- [Request Handling](/docs/advanced/request-handling.md)\n\n## Typesafe Routing\n- [Typed Routes](/docs/labs/typed-routes.md#-typed-routes)\n- [Declarative Routing](/docs/labs/typed-routes.md#declarative-routing)\n\nThese are discussed later.\n"},{"id":"/docs/advanced/routing/","title":"Advanced Routing","description":"Advanced matching behavior and route structure patterns for larger applications.","url":"https://next.qwik.dev/docs/advanced/routing/","content":"# Advanced Routing\n\n## 404 Page Handling\n\nIt's possible for any user to visit a URL that doesn't exist on your site. For example, if a user visits `https://example.com/does-not-exist`, then the server should respond with a [404 HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404), and the page should have at least some sort of explanation, rather than just a blank page.\n\nFor any given route, Qwik Router can choose how to best handle the 404 response for the user, whether it's with the default 404 page, a custom 404 page, or a dynamically generated 404 page.\n\n### Default 404 Page\n\nRather than showing a blank page, by default Qwik Router provides a generic 404 page for any route that isn't handled. The default 404 page is rendered as a fallback when a custom 404 page was not found. We recommend providing a custom 404 page for a better user experience. Including the common header and navigation in a custom 404 page would help the user find the page they're looking for.\n\n### Custom 404 Page\n\nInstead of showing the generic (boring) 404 response, it's possible to provide a custom 404 page using the same familiar layouts as the rest of your site.\n\nTo create a custom 404 page, add a `404.tsx` file to the root `src/routes` directory.\n\n```bash\nsrc/\n`-- routes/\n |-- 404.tsx # Custom 404\n |-- layout.tsx # Default layout\n `-- index.tsx # https://example.com/\n```\n\nIn the example above, the `404.tsx` page will also use the `layout.tsx` layout, since it is a sibling of the layout in the same directory.\n\nAdditionally, using Qwik Router's directory-based routing allows for custom 404 pages to be created at different paths. For example, if `src/routes/account/404.tsx` was also added to the structure, then the custom account 404 page would only be applied to the `/account/*` routes, while all other 404s would use the root `404.tsx` page.\n\nDuring development and in preview mode, the custom 404 pages will not be rendered, but instead the default Qwik Router 404 page will show. However, when building the app for production, the custom 404 page will be statically generated as a static `404.html` file.\n\n```bash\nsrc/\n`-- routes/\n |-- account/\n | `-- 404.tsx # Custom Account 404\n | `-- index.tsx # https://example.com/account/\n |-- 404.tsx # Custom 404\n |-- layout.tsx # Default layout\n `-- index.tsx # https://example.com/\n```\n\nIt's worth noting that custom 404 pages are statically generated at build time, resulting in a static 404.html file, rather than individually server-side rendered pages. This strategy reduces the load on your HTTP server, avoiding server-side rendering of 404 pages, and thus preserving resources.\n\n### Dynamic 404 Page\n\nWhen rendering a page, the default is to always respond with a [200 HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200), which tells the browser all is good and the route exists. However, it's also possible to handle rendering the page, but manually setting the response status code to something other than 200, such as 404.\n\nFor example, let's say we have a product page with a URL such as `https://example.com/product/abc`. The product page would be handled using `src/routes/product/[id]/index.tsx` directory-based route, and `[id]` is a dynamic param in the URL.\n\nIn this example, `id` is used as a key to load the product data from the database. When the product data is found, great, we'll correctly render data. However, if the product data is not found in the database, we can still handle rendering the page, but instead respond with a 404 HTTP status code.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductLoader = routeLoader$(async ({ params, status }) => {\n // Example database call using the id param\n // The database could return null if the product is not found\n const data = await productDatabase.get(params.id);\n\n if (!data) {\n // Product data was not found\n // Set the status code to 404\n status(404);\n }\n\n // return the data (which may be null)\n return data;\n});\n\nexport default component$(() => {\n // get the product data from the loader\n const product = useProductLoader();\n\n if (!product.value) {\n // no product data found\n // so render our own custom product 404\n return <p>Sorry, looks like we don't have this product.</p>;\n }\n\n // product data was found, so let's render it\n return (\n <div>\n <h1>{product.value.name}</h1>\n <p>{product.value.price}</p>\n <p>{product.value.description}</p>\n </div>\n );\n});\n```\n\n## Grouped Layouts\n\nCommon purpose routes are often placed into directories so they can share layouts, and so related source files are logically grouped next to each other. However, it may be desirable that the directory, which was used to group similar files and share layouts, is excluded from the public-facing URL. This is where \"grouped\" layouts come in (also referred to as a \"pathless\" layout route).\n\nBy surrounding any directory name with parentheses, such as `(name)`, then the directory name itself will not be included in the URL pathname.\n\nFor example, let's say an app placed all _account_ routes together in a directory. `/account/` could be dropped from the URL for cleaner, shorter URLs. In the example below, notice that the paths are within the `src/routes/(account)/` directory, but the URL paths exclude `(account)/`.\n\n```bash\nsrc/\n`-- routes/\n `-- (account)/ # Notice the parentheses\n |-- layout.tsx # Shared account layout\n `-- profile/\n `-- index.tsx # https://example.com/profile\n `-- settings/\n `-- index.tsx # https://example.com/settings\n```\n\n## Named Layout\n\nAt times related routes need to have drastically different layouts from their siblings. It is possible to define multiple layouts for different sibling routes by using a single default layout and any number of named layouts. The child route can then request a specific named-layout.\n\nQwik Router defines the convention that layouts are within `src/routes` and the filename starts with `layout`. That's why the default layout is named `layout.tsx`. A named layout also starts with `layout` followed by a dash `-` and a unique name, such as `layout-narrow.tsx`.\n\nTo reference a named layout, the route's `index.tsx` file must be suffixed with `@<name>`. For example, `index@narrow.tsx` would use the `layout-narrow.tsx` layout.\n\n```bash\nsrc/\n`-- routes/\n |-- contact/\n | `-- index@narrow.tsx # https://example.com/contact (Layout: layout-narrow.tsx)\n |-- layout.tsx # Default layout\n |-- layout-narrow.tsx # Named layout\n `-- index.tsx # https://example.com/ (Layout: layout.tsx)\n```\n\n- `https://example.com/`\n ```\n ┌--------------------------------------------------┐\n | src/routes/layout.tsx |\n | ┌--------------------------------------------┐ |\n | | src/routes/index.tsx | |\n | | | |\n | `--------------------------------------------┘ |\n | |\n `--------------------------------------------------┘\n ```\n- `https://example.com/contact`\n ```\n ┌--------------------------------------------------┐\n | src/routes/layout-narrow.tsx |\n | ┌--------------------------------------------┐ |\n | | src/routes/contact/index@narrow.tsx | |\n | | | |\n | `--------------------------------------------┘ |\n | |\n `--------------------------------------------------┘\n ```\n\n## Nested Layout\n\nMost times it is desirable to nest layouts within each other. A page's content can be nested in numerous wrapping layouts, which is determined by the directory structure.\n\n```bash\nsrc/\n`-- routes/\n |-- layout.tsx # Parent layout\n `-- about/\n |-- layout.tsx # Child layout\n `-- index.tsx # https://example.com/about\n```\n\nIn the above example, there are two layouts that apply themselves around the `/about` page component.\n\n1. `src/routes/layout.tsx`\n2. `src/routes/about/layout.tsx`\n\nIn this case, the layouts will be nested within each other on the page.\n\n```\n┌------------------------------------------------┐\n| src/routes/layout.tsx |\n| ┌------------------------------------------┐ |\n| | src/routes/about/layout.tsx | |\n| | ┌------------------------------------┐ | |\n| | | src/routes/about/index.tsx | | |\n| | | | | |\n| | `------------------------------------┘ | |\n| | | |\n| `------------------------------------------┘ |\n| |\n`------------------------------------------------┘\n```\n\n```tsx title=\"src/routes/layout.tsx\"\nimport { component$, Slot } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <main>\n <Slot /> {/* <== Child layout/route inserted here */}\n </main>\n );\n});\n```\n\n```tsx title=\"src/routes/about/layout.tsx\"\nimport { component$, Slot } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <section>\n <Slot /> {/* <== Child layout/route inserted here */}\n </section>\n );\n});\n```\n\n```tsx title=\"src/routes/about/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return <h1>About</h1>;\n});\n```\n\nThe above example would render the html:\n\n```html\n<main>\n <section>\n <h1>About</h1>\n </section>\n</main>\n```\n\n## Plugin with `plugin@` -> `plugin@<name>.ts`\n\n`plugin.ts` and `plugin@<name>.ts` files can be created in the root of the `src/routes` directory to handle any incoming request before even the root layout executes.\n\nYou can have multiple `plugin.ts` files, each with a different name. For example, `plugin@auth.ts` and `plugin@security.ts`. The `@<name>` is optional and it's only used for developers to help identify the plugin.\n\nRequests handlers like `onRequest`, `onGet`, `onPost`, etc. are called before `server$` functions are executed.\n\n### The order of execution of `plugin.ts` files\n\n If `plugin.ts` file exists and if it has exported request handlers, then they are executed first.\n\nThen exported request handlers from `plugin@<name>.ts` files are executed in alphabetical order of the file names. For example, `onGet` from `plugin@auth.ts` is executed before `onGet` from `plugin@security.ts` because `auth` is alphabetically before `security`.\n\nFinally, if a `server$` function exists, it's executed last.\n"},{"id":"/docs/advanced/prevent-navigation/","title":"Prevent Navigation","description":"How to use `usePreventNavigate$` to guard unsaved state during SPA and browser navigation.","url":"https://next.qwik.dev/docs/advanced/prevent-navigation/","content":"# Preventing navigation\n\nIf the user can lose state by navigating away from the page, you can use `usePreventNavigate$()` to conditionally prevent the navigation.\n\nThe callback will be called with the URL that the user is trying to navigate to. If the callback returns `true`, the navigation will be prevented.\n\nYou can return a Promise, and qwik-router will wait until the promise resolves before navigating.\n\nHowever, in some cases the browser will navigate without calling qwik-router, such as when the user reloads the tab or navigates using `<a/>` instead of `<Link />`. When this happens, the answer must be synchronous, and user interaction is not allowed.\n\nYou can tell the difference between qwik-router and browser navigation by looking at the provided URL. If the URL is `undefined`, the browser is navigating away, and you must respond synchronously.\n\nExamples:\n\n- using a modal library:\n\n```tsx\nexport default component$(() => {\n const okToNavigate = useSignal(true);\n usePreventNavigate$((url) => {\n if (!okToNavigate.value) {\n // we we didn't get a url, the browser is navigating away\n // and we must respond synchronously without dialogs\n if (!url) return true;\n\n // Here we assume that the confirmDialog function shows a modal and returns a promise for the result\n return confirmDialog(\n `Do you want to lose changes and go to ${url}?`\n ).then(answer => !answer);\n // or simply using the browser confirm dialog:\n // return !confirm(`Do you want to lose changes and go to ${url}?`);\n }\n });\n\n return (\n <div>\n <button onClick$={() => (okToNavigate.value = !okToNavigate.value)}>\n toggle user state\n </button>\n application content\n </div>\n );\n});\n```\n\n- Using a separate modal:\n\n```tsx\nexport default component$(() => {\n const okToNavigate = useSignal(true);\n const navSig = useSignal<URL | number>();\n const showConfirm = useSignal(false);\n const nav = useNavigate();\n usePreventNavigate$((url) => {\n if (!okToNavigate.value) {\n if (url) {\n navSig.value = url;\n showConfirm.value = true;\n }\n return true;\n }\n });\n\n return (\n <div>\n <button onClick$={() => (okToNavigate.value = !okToNavigate.value)}>\n toggle user state\n </button>\n application content\n {showConfirm.value && (\n <div>\n <div>\n Do you want to lose changes and go to {String(navSig.value)}?\n </div>\n <button\n onClick$={() => {\n showConfirm.value = false;\n okToNavigate.value = true;\n nav(navSig.value!);\n }}\n >\n Yes\n </button>\n <button onClick$={() => (showConfirm.value = false)}>No</button>\n </div>\n )}\n </div>\n );\n});\n```\n"},{"id":"/docs/guides/rewrites/","title":"Rewrites","description":"How to use `request.rewrite()` in route middleware to render another path while keeping the visible URL.","url":"https://next.qwik.dev/docs/guides/rewrites/","content":"# Rewrites\n\nSometimes you want to redirect a user from the current page to another page,\nbut you want to keep the current URL in the browser history.\n\nLet's say a user tries to access an article which is indexed by its name,\ne.g `/articles/qwik-is-very-quick`.\nbut in our code, we access it by its id, on our directory structure.\n\n```\nsrc/routes/articles/\n|-- [id]\n|--- index.tsx\n```\n\n```tsx title=\"src/routes/plugin@article-rewrite.tsx\"\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onRequest: RequestHandler = async ({ url, rewrite, internalRequest }) => {\n if (internalRequest) {\n return;\n }\n\n const pattern = /^\\/articles\\/(.*)$/;\n // Detects /articles/<article-name>, returns null if url does not match the pattern.\n const match = url.pathname.match(pattern);\n if (match) {\n const articleName = match[1];\n const { id } = await db.getArticleByName(articleName);\n throw rewrite(`/articles/${id}`);\n }\n};\n```\n\nCheck `internalRequest` before applying broad rewrite rules. Qwik Router uses internal JSON\nrequests for route loader fetches and fetch-based action submissions, and those requests must keep\ntheir internal routing behavior.\n\nThe `rewrite()` function, which was destructured in the RequestHandler function arguments, is invoked with a pathname string.\n\n```tsx\nthrow rewrite(`/articles/777/`);\n```\n"},{"id":"/docs/route-loader/","title":"Route Loader","description":"Server-side data loading with `routeLoader$`, typed access, and route-level data dependencies.","url":"https://next.qwik.dev/docs/route-loader/","content":"# `routeLoader$()`\n\nRoute Loaders load data on the server so it becomes available inside Qwik Components during rendering. They load on every navigation that hits their route.\n\n```tsx /routeLoader$/ /useProductDetails/#a title=\"src/routes/product/[productId]/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductDetails = routeLoader$(async ({ params }) => {\n // Runs only on the server, on this route, on every navigation\n const res = await fetch(`https://.../products/${params.productId}`);\n return (await res.json()) as Product;\n});\n\nexport default component$(() => {\n // ComputedSignal<Product> — read .value\n const product = useProductDetails();\n return <p>Product name: {product.value.name}</p>;\n});\n```\n\n`routeLoader$()`s must be exported from a `layout.tsx` or `index.tsx` file. To share one across routes, define it in a separate file and [re-export](/docs/re-exporting-loaders.md) it from each `index.tsx` / `layout.tsx` that needs it.\n\nDon't use `routeLoader$()` to build a REST API — use [Endpoints](/docs/endpoints.md) for that. Loaders are for data your own Qwik Components consume.\n\n## How it works\n\nA few properties of route loaders:\n\n- **Server-only.** The loader function only runs on the server; the browser never sees the closure body.\n- **Keyed by route, not by call site.** Two visits to the same URL share one logical \"result\" per \"route + url params + search params\" set, not one per `useProductDetails()` call.\n- **Result is a `ComputedSignal`.** Components read `.value`. While the data is loading, reading `.value` suspends; if the loader threw, it re-throws the error.\n- **Each loader has its own JSON endpoint.** The client fetches `q-loader-{id}.{hash}.json` for navigation, polling, and post-action invalidation. The browser HTTP cache, ETags, and the `cacheControl` option all apply.\n- **Blocks SSR by default.** The server awaits the loader before rendering the page, so a `throw redirect()` or `throw error()` controls the response. Opt out with `blockSSR: false` to run it in the background — see [Background loaders](#background-loaders-blockssr).\n\nThis means a `routeLoader$()` should be a **pure function of the URL**: same `params` and `search` → same response. Mixing in any other input (action state, request bodies, one-shot tokens) makes the cached responses inconsistent — see [Loaders cannot read action state](#loaders-cannot-read-action-state).\n\n## Reading the result in a component\n\nHooks return a `ComputedSignal<T>`. Read `.value` to get the data. Wrap the component that reads it in [`<Pending>`](/docs/labs/pending.md) to show a placeholder while it loads, and in [`<Catch>`](/docs/labs/catch.md) to render a fallback if the loader throws:\n\n```tsx /Pending/ /Catch/ /product.value/#a title=\"src/routes/product/[productId]/index.tsx\"\nimport { $, component$, Catch, Pending } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductDetails = routeLoader$(async ({ params, fail }) => {\n const product = await db.products.findById(params.productId);\n if (!product) {\n return fail(404, { message: 'Product not found' });\n }\n return product;\n});\n\nconst ProductDetails = component$(() => {\n const product = useProductDetails();\n return product.value.failed ? (\n <div>{product.value.message}</div>\n ) : (\n <div>Product name: {product.value.name}</div>\n );\n});\n\nexport default component$(() => (\n <Catch fallback$={$((error) => <div>Error: {error.message}</div>)}>\n <Pending fallback$={() => <div>Loading…</div>}>\n <ProductDetails />\n </Pending>\n </Catch>\n));\n```\n\nWhile the signal is in error state, accessing `.value` re-throws the error.\n\n### Signaling failure from a loader\n\nLoaders signal failure two ways:\n\n- **`throw requestEvent.error(status, data)`** — throw a `ServerError` directly. Reading `signal.value` re-throws the `ServerError {status, data}`, so wrap the reader in a `<Catch>`. This is the recommended way to signal failure from a loader.\n- **`return requestEvent.fail(status, data)`** — returns an inline failure. `signal.value.failed` is `true` and `signal.value` contains the rest of the data.\n\nIn both cases the result is not cacheable. For a blocking loader (the default) the HTTP response status is also set to `status`; a `blockSSR: false` loader is isolated from the page response — see [Background loaders](#background-loaders-blockssr).\n\n## Multiple `routeLoader$`s\n\nMultiple loaders are allowed in any combination, including in the same file. They execute in parallel — declaring more does not slow rendering down by itself.\n\n```tsx title=\"src/routes/admin/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useLoginStatus = routeLoader$(async ({ cookie }) => ({\n isUserLoggedIn: checkCookie(cookie),\n}));\n\nexport const useCurrentUser = routeLoader$(async ({ cookie }) => ({\n user: currentUserFromCookie(cookie),\n}));\n\nexport default component$(() => {\n const loginStatus = useLoginStatus();\n const currentUser = useCurrentUser();\n return (\n <section>\n <h1>Admin</h1>\n {loginStatus.value.isUserLoggedIn ? (\n <p>Welcome {currentUser.value.user.name}</p>\n ) : (\n <p>You are not logged in</p>\n )}\n </section>\n );\n});\n```\n\n## When does the loader re-run?\n\nA loader is re-fetched when:\n\n- the app navigates (every SPA navigation re-fetches every loader except `cacheControl: 'immutable'` ones, which only re-fetch when their URL inputs change; the browser HTTP cache decides whether a fetch hits the network — see [Cache & freshness](#cache--freshness)),\n- it's invalidated by an action (see [`routeAction$`](/docs/action.md) and the action's `invalidate` option),\n- you invalidate its signal manually, for example from `usePoll` (see [Polling](#polling)).\n\nA re-fetch that returns unchanged data doesn't rerender anything: the response text is compared to the previous one and the signal keeps the same object.\n\nA loader in `src/routes/product/[productId]/index.tsx` runs when the user navigates to `/product/1` or `/product/2`, but not when they navigate to `/about`.\n\nReading a loader hook from a component on a route where that loader is **not** declared returns `undefined` at runtime. The TypeScript signature does not reflect this — it's intentional, because route loaders that redirect can transiently be in this state during navigation. Treat it as an error on your part: if a component uses a loader, that loader's route must be the active route.\n\n### Search params (`search`)\n\nThe `search` option declares which URL search parameters (not the route params) the loader actually depends on:\n\n- **What gets sent.** The loader's JSON request URL only includes the listed params, sorted into a stable order. Other params are stripped, so unrelated query strings don't bust the cache.\n- **What the loader sees.** During SSR and loader JSON requests, the loader's `url` and `query` are filtered to those same params. The original is still visible on `request.url`, but you should not use it.\n- **When it re-fetches.** The signal only re-fetches when a listed search param (or the route path) changes.\n\n```tsx title=\"src/routes/products/index.tsx\"\nexport const useFilteredProducts = routeLoader$(\n async ({ url }) => {\n const category = url.searchParams.get('category');\n const sort = url.searchParams.get('sort') ?? 'newest';\n return await db.products.list({ category, sort });\n },\n {\n // Only `?category=` and `?sort=` matter; `?utm_source=` etc. are ignored.\n search: ['category', 'sort'],\n }\n);\n```\n\n`search: []` means the loader doesn't depend on any search params — pure path-keyed cache, best reuse across visits. When `search` is omitted, all search params are forwarded (subject to `strictLoaders`, below).\n\nThe `strictLoaders` Vite plugin option (default `true` in v2) applies `search: []` to every loader that doesn't set it explicitly. This is the better default: each unique URL produces at most one cache entry per loader, so unrelated tracking params (`?utm_source=…`, `?fbclid=…`) don't generate fresh, never-reused cache entries for an identical response. To opt a loader into reacting to a query string, set `search` explicitly. Pass `strictLoaders: false` to `qwikRouter()` to restore \"all params, all re-fetches\" globally.\n\n## Cache & freshness\n\nLoader responses come from per-loader JSON endpoints, and the browser HTTP cache is the single freshness authority: every navigation re-fetches every loader, and the loader's `Cache-Control` header decides whether that fetch is served from cache, revalidated, or hits the server.\n\n### `cacheControl`\n\nSets the `Cache-Control` header on the loader's JSON responses. It accepts everything the [`cacheControl()`](/docs/caching.md) request method accepts — `'immutable'`, a max-age number in seconds, an options object — or a function of the request event (return `null` to skip the header). A `Cache-Control` header set inside the loader function wins over the option.\n\nThe default is `no-cache`: the browser always revalidates, which pairs well with `eTag` for cheap 304 responses.\n\n```tsx title=\"src/routes/product/[productId]/index.tsx\"\nexport const useProductDetails = routeLoader$(\n async ({ params }) => fetchProduct(params.productId),\n { cacheControl: 60 } // fresh for 1 minute, no requests during that time\n);\n```\n\n**`cacheControl: 'immutable'` is special.** It means the data for a URL never changes until the application is rebuilt (the manifest hash busts the cache). Immutable loaders are fully lazy on the client: they are skipped by the per-navigation re-fetch, the eager navigation fetch, and link data prefetching, so their JSON downloads only when a component actually reads the signal — and is then browser-cached for the life of the deploy. For SSG they are pre-generated as static `.json` files on disk, so route loaders work even on fully static sites.\n\n### Polling\n\nTo keep loader data fresh while the user stays on the page, use `usePoll` from `@qwik.dev/utils`. It invalidates the signal on an interval (starting once the document is idle, resetting whenever new data lands), and each refetch goes through the browser cache like any other:\n\n```tsx\nimport { usePoll } from '@qwik.dev/utils';\n\nexport default component$(() => {\n const stock = useStockLevel();\n usePoll(stock, 30_000); // refetch every 30s\n return <p>{stock.value} in stock</p>;\n});\n```\n\nYou can also drive this manually: `signal.invalidate()` re-fetches while keeping the current value readable, and `signal.clear()` additionally drops the value so readers suspend until fresh data arrives.\n\n### `eTag`\n\nAdds an `ETag` header on the loader response and honors `If-None-Match`. Two modes:\n\n- **`eTag: 'some-string'`** — static eTag.\n- **`eTag: (requestEvent) => string | null`** — compute the eTag from request context (params, headers, cookies). The loader is skipped entirely on a 304. Return `null` or an empty string to disable for this request.\n\nQwik normalizes eTag values by stripping weak-form `W/` prefixes, quotes, and forbidden chars, then sends a strong `ETag` header. Values that normalize to an empty string are treated as \"no eTag provided\".\n\nWhen a loader `cacheKey` callback needs the loader-filtered search string, read `ev.url.search`, which always reflects the loader's `search` option.\n\n```tsx title=\"src/routes/subscription/index.tsx\"\nexport const useSubscription = routeLoader$(\n async (ev) => {\n const user = ev.sharedMap.get('user')!;\n return getSubscription(user.id);\n },\n {\n cacheControl: 'no-cache',\n eTag: (ev) => {\n const { id } = ev.sharedMap.get('user')!;\n const day = new Date().getDate();\n return `${id}-${day}`; // valid for the rest of the day, per user\n },\n }\n);\n```\n\n### `serializationStrategy`\n\nBy default the HTML response does **not** embed loader data. When the client resumes, the loader signal is empty until the browser fetches the JSON endpoint — meaning fast first paint, but a brief pending state for code that reads `.value` immediately.\n\n| Value | Behavior |\n| ---------- | ----------------------------------------------------------------------- |\n| `'never'` | Default. Data is discarded after SSR; the client refetches lazily. |\n| `'always'` | Embed data in the HTML. Available immediately, no refetch, bigger HTML. |\n| `'auto'` | Embed when small, lazy-load when large. |\n\n```tsx title=\"src/routes/product/[productId]/index.tsx\"\nexport const useProductDetails = routeLoader$(\n async ({ params }) => fetchProduct(params.productId),\n { serializationStrategy: 'always' }\n);\n```\n\nTo set the default for the whole app, configure the Vite plugin:\n\n```ts title=\"vite.config.ts\"\nimport { qwikRouter } from '@qwik.dev/router/vite';\n\nexport default () => ({\n plugins: [\n qwikRouter({\n defaultLoadersSerializationStrategy: 'always',\n }),\n ],\n});\n```\n\nWhen using lazy-loaded data, wrap the reader in `<Pending>` to show a placeholder until it arrives — see [Reading the result in a component](#reading-the-result-in-a-component).\n\n## Background loaders (`blockSSR`)\n\nBy default a loader **blocks SSR**: the server awaits it before rendering, so a `throw redirect()` or `throw error()` short-circuits the HTTP response. When several loaders block, the first one to error, in route order, decides the error, however the last one to set the status, in chronological order, decides the status.\n\nSet `blockSSR: false` to run a loader in the background instead. The server starts it but does not wait: rendering begins immediately, and reading `.value` suspends only that read until the loader resolves. This starts SSR sooner, and is the recommended setting, unless you need to control the request from the loader.\n\n`blockSSR: false` is experimental — to use it, you must add `experimental: ['blockSSR']` to your `qwikVite` plugin options.\n\n```tsx title=\"src/routes/product/[productId]/index.tsx\"\nexport const useRecommendations = routeLoader$(\n async ({ params }) => fetchRecommendations(params.productId),\n { blockSSR: false }\n);\n```\n\nA background loader is treated as a **separate request**: it cannot redirect or error the page response. If it calls `redirect()` or `error()`, that control flow is captured on its own signal (surfacing when `.value` is read) and never changes the page's status or headers. Keep route guards that must redirect or set a status in a [request handler](/docs/middleware.md) such as `onRequest`, or in a blocking loader.\n\nNote: when the client fetches a background loader for SPA navigation, there is no difference between a blocking and non-blocking loader — the SPA fetch is always async, and the page is already rendered. Errors are not surfaced directly, but redirects are followed automatically.\n\n## Accessing `RequestEvent`\n\nThe loader function receives the same [`RequestEvent`](/docs/middleware.md#requestevent) as middleware. Use it to read params, headers, cookies, the URL, and so on.\n\n```tsx title=\"src/routes/recommendations/[user]/index.tsx\"\nexport const useRecommendations = routeLoader$(async (requestEvent) => {\n const userId = requestEvent.params.user;\n const lang = requestEvent.request.headers.get('accept-language') ?? 'en';\n const res = await fetch(\n `https://.../recommendations?user=${userId}&lang=${lang}`\n );\n return (await res.json()) as Product[];\n});\n```\n\n## Composing loaders with `resolveValue`\n\nA loader can read another loader's result via `requestEvent.resolveValue(otherLoader)`:\n\n```tsx title=\"src/routes/user/[userId]/index.tsx\"\nexport const useUser = routeLoader$(async ({ params }) =>\n fetchUser(params.userId)\n);\n\nexport const useUserPosts = routeLoader$(async ({ resolveValue }) => {\n const user = await resolveValue(useUser);\n return fetchPostsFor(user.id);\n});\n```\n\n`resolveValue` runs the dependency loader once per request and caches the result, so reading the same loader from multiple places doesn't duplicate work.\n\n`resolveValue` only resolves other `routeLoader$`s — actions are **not** visible to it. See [Loaders cannot read action state](#loaders-cannot-read-action-state) below.\n\n## Loaders cannot read action state\n\n`requestEvent.resolveValue(actionQrl)` always returns `undefined` inside a loader, regardless of how the loader was triggered (initial render, navigation, post-action invalidation, polling).\n\nThe reason is the same as everywhere else on this page: **a loader's output must be a pure function of the URL.** Action results are transient — they only exist on the request that handled the submission, and the loader refetch that follows an action is a separate GET with no action context. Letting loaders see action state would silently produce different data on the inline-render path (no JS) than on the JSON refetch path (SPA), so the API does not expose action state to loaders at all. The same rule applies to anything else valid for one request — request bodies, one-shot tokens, `Set-Cookie` values written by middleware on this request.\n\nRead action state directly from the action signal where you render.\n\n```tsx /resolveValue/#a title=\"src/routes/[id]/index.tsx\"\nexport const useNameAction = routeAction$(async (data) => data);\n\n// `form` is always undefined, regardless of whether an action just ran.\nexport const useGreetingBroken = routeLoader$(async ({ resolveValue, params }) => {\n const form = await resolveValue(useNameAction);\n return { name: form?.name ?? params.id };\n});\n\n// Loader is a pure function of the URL; component blends in transient action state.\nexport const useGreeting = routeLoader$(({ params }) => ({ name: params.id }));\n\nexport default component$(() => {\n const greeting = useGreeting();\n const action = useNameAction();\n const name = action.value?.name ?? greeting.value.name;\n return (\n <Form action={action}>\n <p>Hello, {name}!</p>\n <input name=\"name\" />\n <button type=\"submit\">Update</button>\n </Form>\n );\n});\n```\n\n### What did people use action-state-in-loaders for?\n\n| Use case | Workaround |\n| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Echo the just-submitted form value back to the page | Loader returns the URL-derived value; the component overlays `action.value` on top, e.g. `action.value?.name ?? loader.value.name`. |\n| Recompute derived data from the submission | Put the inputs in the URL (search params, or `goto()` after the action) so the loader reads them like any other route input. |\n| Refresh authoritative data after a mutation | The action writes to your store (DB, KV, etc.); the loader reads from that store. The action's `invalidate` list re-runs the loader and it picks up the new state — no action result needed. |\n| Show success / error feedback | Read the action signal directly: `action.value`, `action.isRunning`, `action.value?.failed`. Ephemeral UI feedback doesn't belong in a loader. |\n\n## Options reference\n\n| Option | Default | Effect |\n| ----------------------- | ------------ | ----------------------------------------------------------------------------------------------------- |\n| `cacheControl` | `no-cache` | `Cache-Control` for the JSON responses; the browser cache decides freshness. `'immutable'` enables SSG loader files. |\n| `serializationStrategy` | `'never'` | `'never'` / `'always'` / `'auto'` — embed loader data in the SSR HTML? |\n| `blockSSR` | `true` | Await the loader before SSR (can redirect/error the response). `false` runs it in the background (experimental). |\n| `eTag` | — | `true` (auto-hash), string, or `(ev) => string \\| null`. Returns 304 on match. |\n| `search` | `[]` * | Allowlist of search params the loader depends on. *(default `[]` when `strictLoaders` is enabled)* |\n| `validation` | — | Array of [`DataValidator`](/docs/validator.md)s applied before the loader runs. |\n\nThe Vite plugin `qwikRouter()` exposes app-wide defaults via `defaultLoadersSerializationStrategy` and `strictLoaders`.\n"},{"id":"/docs/action/","title":"Action","description":"Mutations and form actions with `routeAction$`, validation, and progressive enhancement.","url":"https://next.qwik.dev/docs/action/","content":"# `routeAction$()`\n\n`routeAction$()` is used to define functions called actions that execute exclusively on the server, and only when explicitly called. Actions can have side effects such as writing to a database or sending an email, that cannot happen during client-side rendering. This makes them ideal for handling form submissions, performing operations with side effects, and then returning data back to the client/browser where it can be used to update the UI.\n\nActions can be declared using `routeAction$()` or `globalAction$()` exported from `@qwik.dev/router`.\n\n```tsx {4,16} /useAddUser/ /firstName/#a /lastName/#b /email/#c title=\"src/routes/layout.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$, Form } from '@qwik.dev/router';\n\nexport const useAddUser = routeAction$(async (data, requestEvent) => {\n // This will only run on the server when the user submits the form (or when the action is called programmatically)\n const userID = await db.users.add({\n firstName: data.firstName,\n lastName: data.lastName,\n });\n return {\n success: true,\n userID,\n };\n});\n\nexport default component$(() => {\n const action = useAddUser();\n\n return (\n <>\n <Form action={action}>\n <input name=\"firstName\" />\n <input name=\"lastName\" />\n <button type=\"submit\">Add user</button>\n </Form>\n {action.value?.success && (\n // When the action is done successfully, the `action.value` property will contain the return value of the action\n <p>User {action.value.userID} added successfully</p>\n )}\n </>\n );\n});\n```\n\nSince actions are not executed during rendering, they can have side effects such as writing to a database, or sending an email. An action only runs when called explicitly.\n\n## Using actions with `<Form/>`\n\nThe best way to call an action is using the `<Form/>` component exported in `@qwik.dev/router`.\n\n```tsx title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$, Form } from '@qwik.dev/router';\n\nexport const useAddUser = routeAction$(async (user) => {\n const userID = await db.users.add(user);\n return {\n success: true,\n userID,\n };\n});\n\nexport default component$(() => {\n const action = useAddUser();\n return (\n <Form action={action}>\n <input name=\"name\" />\n <button type=\"submit\">Add user</button>\n {action.value?.success && <p>User added successfully</p>}\n </Form>\n );\n});\n```\n\nUnder the hood, the `<Form/>` component uses a native HTML `<form>` element, so it will work without JavaScript.\n\nWhen JS is enabled, the `<Form/>` component will intercept the form submission and trigger the action in SPA mode. Allowing for a full SPA experience.\n\nThe server re-renders the whole page and re-executes everything, so if you have any [routeLoader$](/docs/route-loader.md) they will be executed too.\n\n[Complex forms](/docs/advanced/complex-forms.md) can be created using dot notation.\n\n## Using actions programmatically\n\nActions can also be triggered programmatically using the `action.submit()` method (i.e. you don't need a `<Form/>` component). However, you can trigger the action from a button click or any other event, just like you would do with a function.\n\n```tsx {18} title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$ } from '@qwik.dev/router';\n\nexport const useAddUser = routeAction$(async (user) => {\n const userID = await db.users.add(user);\n return {\n success: true,\n userID,\n };\n});\n\nexport default component$(() => {\n const action = useAddUser();\n return (\n <section>\n <button\n onClick$={async () => {\n const { value } = await action.submit({ name: 'John' });\n console.log(value);\n }}\n >\n Add user\n </button>\n {action.value?.success && <p>User added successfully</p>}\n </section>\n );\n});\n```\n\nIn the example above, the `addUser` action is triggered when the user clicks the button. The `action.submit()` method returns a `Promise` that resolves when the action is done.\n\n### Uploading files\n\nWhen using `<Form>` with a file input, the submission will be sent as a `multipart/form-data` request.\n\nBut when using actions programmatically, you can still upload files by passing a `File` object to the `action.submit()` method by creating a `FormData` object and appending the file to it.\n\n```tsx title=\"src/routes/index.tsx\"\n\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$ } from '@qwik.dev/router';\n\nexport const useUploadFile = routeAction$(async ({file}) => {\n // save the file somewhere...\n return {\n success: true,\n };\n});\n\nexport default component$(() => {\n const action = useUploadFile();\n const fileUploadRef = useSignal<HTMLInputElement | undefined>();\n return (\n <section>\n <input type=\"file\" ref={fileUploadRef}/>\n <button\n onClick$={async () => {\n\n const file = fileUploadRef.value?.files?.[0];\n\n if (file){\n const formData = new FormData();\n formData.append('file', file);\n const { value } = await action.submit(formData);\n console.log(value);\n }\n }}\n >\n Upload file\n </button>\n\n </section>\n );\n});\n\n```\n\n## Actions with Event Handlers\n\nThe `onSubmitCompleted$` event handler can be used after an action is successfully executed and returns some data. This is useful for performing tasks, such as resetting UI elements or updating the application state, once an action has been completed.\n\nHere's an example of the `onSubmitCompleted$` handler used to edit an item in a EditForm component of a todo app.\n\n```tsx title=\"src/components/EditForm.tsx\"\nimport { component$, type Signal, useSignal } from '@qwik.dev/core';\nimport { Form } from '@qwik.dev/router';\nimport { type ListItem, useEditFromListAction } from '../../routes/index';\n\nexport interface EditFormProps {\n item: listItem;\n editingIdSignal: Signal<string>;\n}\n\nconst EditForm = component$(\n ({ item, editingIdSignal }: EditFormProps) => {\n const editAction = useEditFromListAction();\n\n return (\n <div>\n <Form\n action={editAction}\n onSubmitCompleted$={() => {\n editingIdSignal.value = '';\n }}\n spaReset\n >\n <input\n type=\"text\"\n value={item.text}\n name=\"text\"\n id={`edit-${item.id}`}\n />\n {/* Sends item.id with form data on submission. */}\n <input type=\"hidden\" name=\"id\" value={item.id} />\n <button type=\"submit\">\n Submit\n </button>\n </Form>\n\n <div>\n <button onClick$={() => (editingIdSignal.value = '')}>\n Cancel\n </button>\n </div>\n </div>\n );\n }\n);\n\nexport default EditForm;\n```\n\nIn this example, `onSubmitCompleted$` is used to reset the editingIdSignal value to an empty string once the form submission is completed successfully. This allows the application to update its state and return to the default view.\n\n## Validation and type safety\n\nQwik comes with built-in support for [Zod](https://zod.dev/), a TypeScript-first schema validation that can be used directly with actions, using the `zod$()` function.\n\nActions + [Zod](https://zod.dev/) allows to create type safe forms, where the data is validated server side before the action is executed.\n\n```tsx {16-20} /firstName/#a /lastName/#b title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$, Form } from '@qwik.dev/router';\nimport { zod$, z } from '@qwik.dev/utils';\n\nexport const useAddUser = routeAction$(\n async (user) => {\n // The \"user\" is strongly typed: { firstName: string, lastName: string }\n const userID = await db.users.add({\n firstName: user.firstName,\n lastName: user.lastName,\n });\n return {\n success: true,\n userID,\n };\n },\n // Zod schema is used to validate that the FormData includes \"firstName\" and \"lastName\"\n zod$({\n firstName: z.string(),\n lastName: z.string(),\n })\n);\n\nexport default component$(() => {\n const action = useAddUser();\n return (\n <>\n <Form action={action}>\n <input name=\"firstName\" />\n <input name=\"lastName\" />\n\n {action.value?.failed && <p>{action.value.fieldErrors?.firstName}</p>}\n <button type=\"submit\">Add user</button>\n </Form>\n {action.value?.success && (\n <p>User {action.value.userID} added successfully</p>\n )}\n </>\n );\n});\n```\n\nWhen submitting data to a `routeAction()`, the data is validated against the Zod schema. If the data is invalid, the action will put the validation error in the `routeAction.value` property.\n\nPlease refer to the [Zod documentation](https://zod.dev/) for more information on how to use Zod schemas.\n\n### Advanced event based validation\n\nThe constructor of ```zod$``` can also take a function, as the first argument is zod itself, so you can use this directly to build the schema.\nThe second parameter is the RequestEvent to construct an event-based zod schema.\nEspecially in combination with ```refine``` and ```superRefine``` in zod, the only limit is your imagination.\n\n```tsx {5-5} /ev/#a title=\"Advanced event based validation\"\nexport const useAddUser = routeAction$(\n async (user) => {\n // The \"user\" is still strongly typed, but firstname\n // is now optional: { firstName?: string | undefined, lastName: string }\n const userID = await db.users.add({\n firstName: user.firstName,\n lastName: user.lastName,\n });\n return {\n success: true,\n userID,\n };\n },\n // Zod schema is used to validate that the FormData includes \"firstName\" and \"lastName\"\n zod$((z, ev) => {\n // The first name is optional if the url contains the query parameter \"firstname=optional\"\n const firstName =\n ev.url.searchParams.get(\"firstname\") === \"optional\"\n ? z.string().optional()\n : z.string().nonempty();\n\n return z.object({\n firstName,\n lastName: z.string(),\n });\n })\n);\n```\n\n## HTTP request and response\n\n`routeAction$` and `globalAction$` have access to the `RequestEvent` object which includes information about the current HTTP request and response.\n\nThis allows actions to access the request headers, cookies, url and environment variables within the `routeAction$` function.\n\n```tsx /requestEvent/ title=\"src/routes/product/[user]/index.tsx\"\nimport { routeAction$ } from '@qwik.dev/router';\n\n// The second argument of the action is the `RequestEvent` object\nexport const useProductRecommendations = routeAction$(\n async (_data, requestEvent) => {\n console.log('Request headers:', requestEvent.request.headers);\n console.log('Request cookies:', requestEvent.cookie);\n console.log('Request url:', requestEvent.url);\n console.log('Request params:', requestEvent.params);\n console.log('MY_ENV_VAR:', requestEvent.env.get('MY_ENV_VAR'));\n }\n);\n\n```\n\n## Action Failures\n\nIn order to return non-success values, the action must use the `fail()` method.\n\n```tsx /fail/\nimport { routeAction$ } from '@qwik.dev/router';\nimport { zod$, z } from '@qwik.dev/utils';\n\nexport const useAddUser = routeAction$(\n async (user, { fail }) => {\n // `user` is typed { name: string }\n const userID = await db.users.add(user);\n if (!userID) {\n return fail(500, {\n message: 'User could not be added',\n });\n }\n return {\n userID,\n };\n },\n zod$({\n name: z.string(),\n })\n);\n```\n\nFailures are stored in the `action.value` property, just like the success value. However, the `action.value.failed` property is set to `true` when the action fails. Futhermore, failure messages can be found in the `fieldErrors` object according to properties defined in your Zod schema.\n\nThe `fieldErrors` become a dot notation object. See [Complex forms](/docs/advanced/complex-forms.md) for more information.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Form } from '@qwik.dev/router';\n\nexport default component$(() => {\n const action = useAddUser();\n return (\n <Form action={action}>\n <input name=\"name\" />\n <button type=\"submit\">Add user</button>\n {action.value?.failed && <p>{action.value.fieldErrors.name}</p>}\n {action.value?.userID && <p>User added successfully</p>}\n </Form>\n );\n});\n```\n\nThanks to Typescript type discrimination, you can use the `action.value.failed` property to discriminate between success and failure.\n\n## Previous form state\n\nWhen an action is triggered, the previous state is stored in the `action.formData` property. This is useful to display a loading state while the action is running.\n\n```tsx {12} /action.formData/\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$, Form } from '@qwik.dev/router';\nimport { zod$, z } from '@qwik.dev/utils';\n\nexport const useAddUser = routeAction$(async (user) => {\n // handle action...\n});\n\nexport default component$(() => {\n const action = useAddUser();\n return (\n <Form action={action}>\n <input name=\"name\" value={action.formData?.get('name')} />\n <button type=\"submit\">Add user</button>\n </Form>\n );\n});\n```\n\nThe `action.formData` is especially useful for retaining user-filled form data even after a page refresh. This enables a seamless SPA experience, even with JS disabled.\n\n## Route vs Global actions\n\nActions can be declared using the `routeAction$()` or `globalAction$()` exported from `@qwik.dev/router`, the only difference between the two is that `routeAction$()` is scoped to a route, while `globalAction$()` is globally available across the whole app.\n\nIt's recommended to start with `routeAction$()`. Use `globalAction$()` only when sharing an action across multiple routes, or if you wish to use the action in a component that is not a route.\n\n### `routeAction$()`\n\n`routeAction$()` can only be declared inside the `src/routes` folder, in a `layout.tsx` or `index.tsx` file, and they MUST be exported, just like a `routeLoader$()`. Since `routeAction$()`s are only accessible within the route it's declared, they are recommended when the action needs to access some user data, or it's a protected route. Think about it like a \"private\" action.\n\nIf you want to manage common reusable routeAction$() it is essential that this function is re-exported from within 'layout.tsx' or 'index.tsx file of the existing route otherwise it will not run or throw exception. For more information [check this section](/docs/re-exporting-loaders.md).\n\n```tsx title=\"src/routes/form/index.tsx\"\nimport { routeAction$ } from '@qwik.dev/router';\n\nexport const useChangePassword = routeAction$((data) => {\n // ...\n});\n```\n\n### `globalAction$()`\n\n`globalAction$()` can be declared anywhere in the `src` folder. Since `globalAction$()` are globally available, they are recommended when the action needs to be shared across multiple routes, or when the action doesn't need to access any user data. For example, a `useLogin` action that logs in a user. Think about it like a \"public\" action.\n\n```tsx title=\"src/components/login/login.tsx\"\nimport { globalAction$ } from '@qwik.dev/router';\n\nexport const useLogin = globalAction$((data) => {\n // ...\n});\n```\n\n## Redirecting after a POST\n\nWhen JavaScript is disabled, a native form `POST` is stored in browser history. Reloading the page triggers a **\"Confirm Form Resubmission\"** warning and re-runs the action. To prevent this, use the [Post/Redirect/Get (PRG)](https://en.wikipedia.org/wiki/Post/Redirect/Get) pattern: detect if the submission came from the browser (no-JS) and redirect to a `GET` request instead.\n\nA native browser form submission always includes `text/html` in the `Accept` header. Use that to detect when to apply the redirect:\n\n```tsx title=\"src/routes/index.tsx\" // without PRG\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$, zod$, z } from '@qwik.dev/router';\n\nexport const useCreatePost = routeAction$(\n async (data) => {\n const postId = await db.posts.create(data);\n return { postId };\n },\n zod$({ title: z.string() })\n);\n\nexport default component$(() => {\n const action = useCreatePost();\n return (\n // Native form POST — reloading the result page triggers \"Confirm Form Resubmission\"\n <form method=\"POST\" action={action.actionPath}>\n <input name=\"title\" />\n <button type=\"submit\">Create post</button>\n </form>\n );\n});\n```\n\nTo fix this, detect the submission type using the `Accept` header and `throw redirect()` for browser submissions:\n\n```tsx title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$, routeLoader$, Form, zod$, z } from '@qwik.dev/router';\n\nexport const useCreatePost = routeAction$(\n async (data, { request, redirect }) => {\n const postId = await db.posts.create(data);\n\n // Browser (no-JS) submissions include text/html in the Accept header.\n // Redirect to a GET so the user can safely reload the result page.\n if (request.headers.get('accept')?.includes('text/html')) {\n throw redirect(303, `/?created=${postId}`);\n }\n\n return { postId };\n },\n zod$({ title: z.string() })\n);\n\n// Read the search param set by the redirect on the destination page\nexport const useCreatedId = routeLoader$(({ url }) => {\n return { createdId: url.searchParams.get('created') };\n});\n\nexport default component$(() => {\n const action = useCreatePost();\n const loader = useCreatedId();\n\n // JS path: action.value holds the result directly.\n // No-JS path: loader.value holds the param passed via the redirect.\n const createdId = action.value?.postId ?? loader.value.createdId;\n\n return (\n <Form action={action}>\n <input name=\"title\" />\n <button type=\"submit\">Create post</button>\n {createdId && <p>Post {createdId} created!</p>}\n </Form>\n );\n});\n```\n\nWhen JS is enabled, Qwik intercepts the form submission as a fetch and the redirect is never triggered — `action.value` holds the result as usual. The redirect only fires for native browser submissions. However, `<Form/>` uses [progressive enhancement](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement) and falls back to a native form `POST` if JS has not yet loaded or fails to load, so the PRG pattern is still needed for these cases.\n\nYou can also pass state across a redirect using cookies instead of search params, which is useful for flash messages or session data. See the [cookie section in the middleware docs](/docs/(qwikrouter)/middleware/#cookie) for usage.\n"},{"id":"/docs/server$/","title":"server$","description":"RPC-style server functions callable from the client with serialization and request context support.","url":"https://next.qwik.dev/docs/server$/","content":"# `server$()`\n\n`server$()` allows you to define functions that execute exclusively on the server, making it ideal for server-only operations and database access. It functions as an RPC (Remote Procedure Call) mechanism between the client and server. This is similar to a traditional HTTP endpoint, but strongly typed with TypeScript and easier to maintain.\n\n`server$` can accept any number of arguments and return any value that can be serialized by Qwik. This includes primitives, objects, arrays, bigint, JSX nodes, and even Promises, just to name a few.\n\n## Server-only modules\n\nQwik treats files named `.server.*`, such as `db.server.ts`, and files inside\n`src/**/server/**` folders as server-only modules. These modules can be imported by SSR code,\nroute loaders, route actions, endpoint handlers, and `server$` implementations, but the client\nbuild will fail if client code imports them.\n\n```ts title=\"src/db.server.ts\"\nexport const loadSecret = async () => {\n return process.env.API_KEY;\n};\n```\n\n```tsx title=\"src/routes/index.tsx\"\nimport { routeLoader$ } from '@qwik.dev/router';\nimport { loadSecret } from '../db.server';\n\nexport const useSecret = routeLoader$(async () => {\n return loadSecret();\n});\n```\n\nDo not import server-only modules from browser code such as components, event handlers, or visible\ntasks. If client code needs to trigger server work, expose that work through `server$`, a route\naction, or an endpoint.\n\n`AbortSignal` is optional, and allows you to cancel a long running request by terminating the connection.\nYour new function will have the following signature:\n`([AbortSignal, ...yourOtherArgs]): Promise<T>`\nDepending on your server runtime, the function on the server may not terminate immediately. It depends on how client disconnections are handled by the runtime.\n\n```tsx\nimport { component$, useSignal, $ } from '@qwik.dev/core';\nimport { server$ } from '@qwik.dev/router';\n\n// By wrapping a function with `server$()` we mark it to always\n// execute on the server. This is a form of RPC mechanism.\nexport const serverGreeter = server$(\n function (firstName: string, lastName: string) {\n const greeting = `Hello ${firstName} ${lastName}`;\n console.log('Prints in the server', greeting);\n return greeting;\n }\n);\n\nexport default component$(() => {\n const firstName = useSignal('');\n const lastName = useSignal('');\n\n return (\n <section>\n <label>First name: <input bind:value={firstName} /></label>\n <label>Last name: <input bind:value={lastName} /></label>\n\n <button\n onClick$={\n $(async () => {\n const greeting = await serverGreeter(firstName.value, lastName.value);\n alert(greeting);\n })\n }\n >\n greet\n </button>\n </section>\n );\n});\n```\n\n## Accessing Request Information with `RequestEvent`\n\nWhen using `server$`, you have access to the `RequestEvent` object through `this`. This object provides useful information about the HTTP request, including environment variables, cookies, URL, and headers. Here's how you can use it:\n\n### Environment Variables\n\nYou can access environment variables using `this.env.get()`.\n\n```tsx\nexport const getEnvVariable = server$(\n function () {\n const dbKey = this.env.get('DB_KEY');\n console.log('Database Key:', dbKey);\n return dbKey;\n }\n);\n```\n\n### Cookies\n\nYou can read cookies using `this.cookie.get()` and `this.cookie.set()`.\n\nWhen using `handleCookies` (in our example below) if it’s used within a `useTask$` function that runs during the initial request, setting cookies won’t work as expected. This is because, during server-side rendering (SSR), the response is streamed, and HTTP requires all headers to be set before sending the first response. However, if handleCookies is used in useVisibleTask$, this issue doesn’t occur. If you need to set cookies for the initial document request you can use `plugin@.ts` or Middleware.\n\n```tsx\nexport const handleCookies = server$(\n function () {\n const userSession = this.cookie.get('user-session')?.value;\n if (!userSession) {\n this.cookie.set('user-session', 'new-session-id', { path: '/', httpOnly: true });\n }\n return userSession;\n }\n);\n```\n\n### URL\n\nYou can access the request URL and its components using `this.url`.\n\n```tsx\nexport const getRequestUrl = server$(\n function () {\n const requestUrl = this.url;\n console.log('Request URL:', requestUrl);\n return requestUrl;\n }\n);\n```\n\n### Headers\n\nYou can read headers using `this.headers.get()`.\n\n```tsx\nexport const getHeaders = server$(\n function () {\n const userAgent = this.headers.get('User-Agent');\n console.log('User-Agent:', userAgent);\n return userAgent;\n }\n);\n```\n\n### Using Multiple RequestEvent Information\n\nHere's an example that combines environment variables, cookies, URL, and headers in a single function.\n\n```tsx\nexport const handleRequest = server$(\n function () {\n // Access environment variable\n const dbKey = this.env.get('DB_KEY');\n\n // Access cookies\n const userSession = this.cookie.get('user-session')?.value;\n if (!userSession) {\n this.cookie.set('user-session', 'new-session-id', { path: '/', httpOnly: true });\n }\n\n // Access request URL\n const requestUrl = this.url;\n\n // Access headers\n const userAgent = this.headers.get('User-Agent');\n\n console.log('Environment Variable:', dbKey);\n console.log('User Session:', userSession);\n console.log('Request URL:', requestUrl);\n console.log('User-Agent:', userAgent);\n\n return {\n dbKey,\n userSession,\n requestUrl,\n userAgent\n };\n }\n);\n```\n\n## Streaming Responses\n\n`server$` can return a stream of data by using an async generator function, which is useful for streaming data from the server to the client.\n\nTerminating the generator on the client side (e.g., by calling `.return()` on the generator or by breaking out from your async for-of loop) will terminate the connection. Similar to `AbortSignal`, how the generator terminates on the server side depends on the server runtime and how client disconnects are handled.\n\n```tsx\nimport { component$, useSignal, $ } from '@qwik.dev/core';\nimport { server$ } from '@qwik.dev/router';\n\nexport const streamFromServer = server$(\n // Async Generator Function\n async function* () {\n // Creation of an array with 10 undefined values\n const iterationRange = Array(10).fill().entries();\n\n for (const [value] of iterationRange) {\n // Yield returns the array value during each iteration\n yield value;\n\n // Waiting for 1 second before the next iteration\n // This simulates a delay in the execution\n await new Promise((resolve) => setTimeout(resolve, 1000));\n }\n }\n);\n\nexport default component$(() => {\n const message = useSignal('');\n return (\n <div>\n <button\n onClick$={\n $(async () => {\n // call the async stream function and wait for the response\n const response = await streamFromServer();\n // use a for-await-of loop to asynchronously iterate over the response\n for await (const value of response) {\n // add each value from the response to the message value\n message.value += ` ${value}`;\n }\n // do anything else\n })\n }\n >\n start\n </button>\n <div>{message.value}</div>\n </div>\n );\n});\n```\n\nThis API is actually used to implement QwikGPT streaming responses in our docs site.\n\n## How does `server$()` work?\n\n`server$()` wraps a function and returns an async proxy to the function. On the server, the proxy function directly calls the wrapped function, and a HTTP endpoint is automatically created by the `server$()` function.\n\nOn the client, the proxy function invokes the wrapped function via an HTTP request, using `fetch()`.\n\nThe `server$()` function must ensure that the server and client have the same version of the code executing. If there is a version skew the behavior is undefined and may result in an error. If version skew is a common problem then a more formal RPC mechanism should be used such as a tRPC or other library.\n\n**Important Gotcha**\n\nWhen defining and calling `server$()` inside an `onClick$`, be aware that this can lead to potential errors. To avoid them, make sure the handlers have `$` wrapped around them.\n\nDon't do this: `onClick$={() => server$(() => // some server code!)}`\n\nDo this: `onClick$={$(() => server$(() => // some server code!))}`\n\n## Middleware and `server$`\n\n**Security: authorize every server function**\n\n`server$` creates a public RPC endpoint. Its function hash is not a secret, and a request can invoke\nthe function through any matched page route. Never rely on `layout` or page middleware to authorize\na `server$` function because that middleware does not run for server function requests.\n\nAuthorize sensitive operations inside the `server$` function by checking `this.cookie`, headers, or\nsession data. For application-wide authentication, use middleware in `plugin.ts`; plugin middleware\nruns before server functions.\n\nSee [plugin middleware](/docs/advanced/plugins.md) for application-wide request guards.\n"},{"id":"/docs/guides/react-cheat-sheet/","title":"React Cheat Sheet","description":"Maps common React concepts to Qwik primitives for teams migrating or comparing frameworks.","url":"https://next.qwik.dev/docs/guides/react-cheat-sheet/","content":"# React Vs Qwik\n\nSeveral examples comparing React and Qwik.\n\n## Hello world component\n\n### From React\n\n```tsx\nexport const HelloWorld = () => {\n return <div>Hello world</div>;\n}\n```\n\n### To Qwik\n\n```tsx\nexport const HelloWorld = component$(() => {\n return <div>Hello world</div>;\n});\n```\n\n**What is component$ and $?**\n\ncomponent$ is used to declare a [Qwik component.](https://qwik.dev/docs/core/overview/#component)\n\n[The dollar sign](https://qwik.dev/docs/advanced/dollar/#the-dollar--sign) $ is used to signal both the optimizer and the developer when Qwik splits up your application into many small pieces we call symbols.\n\n## Button with a click handler\n\n### From React\n\n```tsx\nexport const Button = () => {\n return <button onClick={() => console.log('click')}>Click me</button>;\n}\n```\n\n### To Qwik\n\n```tsx\nexport const Button = component$(() => {\n return <button onClick$={() => console.log('click')}>Click me</button>;\n});\n```\n\n**Remember $?**\n\nEvent handlers in qwik behave in the same way as in other frameworks, you just have to keep in mind that their content will be loaded in a lazy way thanks to the dollar suffix.\n\nAttention : JSX [handlers](https://qwik.dev/docs/core/events/#inline-handler) such as onClick$ and onInput$ are only executed on the client. This is because they are DOM events, since there is no DOM on the server, they will not be executed on the server.\n\n## Declare local state\n\n### From React\n\n```tsx\nexport function UseStateExample() {\n const [value, setValue] = useState(0);\n return <div>Value is: {value}</div>;\n}\n```\n\n### To Qwik\n\n```tsx\nexport const LocalStateExample = component$(() => {\n const count = useSignal(0);\n return <div>Value is: {count.value}</div>;\n});\n```\n\n**What if I have a more complex state?**\n\n[useStore()](https://qwik.dev/docs/core/state/#usestore) Works very similarly to useSignal(), but it takes an object as its initial value and the reactivity extends to nested objects and arrays by default. One can think of a store as a multiple-value signal or an object made of several signals.\n\n## Create a counter component\n\n### From React\n\n```tsx\nexport function Counter() {\n const [count, setCount] = useState(0);\n return (\n <>\n <p>Value is: {count}</p>\n <button onClick={() => setCount(count + 1)}>Increment</button>\n </>\n );\n}\n```\n\n### To Qwik\n\n```tsx\nexport const Counter = component$(() => {\n const count = useSignal(0);\n return (\n <>\n <p>Value is: {count.value}</p>\n <button onClick$={() => count.value++}>Increment</button>\n </>\n );\n});\n```\n\n## Using Props\n\n### From React\n\n```tsx\nexport const Parent = (() => {\n const [ count, setCount ] = useState<number>(0);\n\n const increment = (() => {\n setCount((prev) => prev + 1)\n })\n return <Child count={count} increment={increment} />;\n})\n\ninterface ChildProps {\n count: number;\n increment: () => void;\n}\n\nexport const Child = ((props: ChildProps) => {\n return (\n <>\n <button onClick={props.increment}>Increment</button>\n <p>Count: {props.count}</p>\n </>\n );\n})\n```\n\n### To Qwik\n\n```tsx\nexport const Parent = component$(() => {\n const userData = useStore({ count: 0 });\n return <Child userData={userData} />;\n});\n\ninterface ChildProps {\n userData: { count: number };\n}\n\nexport const Child = component$<ChildProps>(({ userData }) => {\n return (\n <>\n <button onClick$={() => userData.count++}>Increment</button>\n <p>Count: {userData.count}</p>\n </>\n );\n});\n```\n\n**Wait, I don't need to pass the handler as a prop?**\n\nThe reactive signal returned by [useSignal()](https://qwik.dev/docs/core/state/#usesignal) consists of an object with a single property .value. If you change the value property of the signal, any component that depends on it will be updated automatically.\n\n## Create a clock that increments every second\n\n### From React\n\n```tsx\nexport function Clock() {\n const [seconds, setSeconds] = useState(0);\n useEffect(() => {\n const interval = setInterval(() => {\n setSeconds(seconds + 1);\n }, 1000);\n return () => clearInterval(interval);\n });\n return <p>Seconds: {seconds}</p>;\n}\n```\n\n### To Qwik\n\n```tsx\nexport const Clock = component$(() => {\n const seconds = useSignal(0);\n useVisibleTask$(({ cleanup }) => {\n const interval = setInterval(() => {\n seconds.value++;\n }, 1000);\n cleanup(() => clearInterval(interval));\n });\n\n return <p>Seconds: {seconds.value}</p>;\n});\n```\n\n## Perform a fetch request every time the state changes\n\n### From React\n\n```tsx\nexport function Fetch() {\n const [url, setUrl] = useState('https://api.github.com/repos/QwikDev/qwik');\n const [responseJson, setResponseJson] = useState(undefined);\n\n useEffect(() => {\n fetch(url)\n .then((res) => res.json())\n .then((json) => setResponseJson(json));\n }, [url]);\n\n return (\n <>\n <p>{responseJson?.name} has {responseJson?.stargazers_count} 's</p>\n <input name=\"url\" value={url} onChange={(e) => setUrl(e.target.value)} />\n </>\n );\n}\n```\n\n### To Qwik\n\n```tsx\nexport const Fetch = component$(() => {\n const url = useSignal('https://api.github.com/repos/QwikDev/qwik');\n const responseJson = useSignal(undefined);\n\n useTask$(async ({ track }) => {\n track(() => url.value);\n const res = await fetch(url.value);\n const json = await res.json();\n responseJson.value = json;\n });\n\n return (\n <>\n <p>{responseJson.value?.name} has {responseJson.value?.stargazers_count} 's</p>\n <input name=\"url\" bind:value={url} />\n </>\n );\n});\n```\n\n**What is useTask$ and bind?**\n\n[useTask$()](https://qwik.dev/docs/core/tasks/#usetask) registers a hook to be executed upon component creation, it will run at least once either in the server or in the browser, depending on where the component is initially rendered.\n\n[bind attribute](https://qwik.dev/docs/core/rendering/#bind-attribute) is a convenient API to two-way data bind the value of an `input` to a Signal.\n\n## Declare some context and consume it\n\n### From React\n\n```tsx\nexport const MyContext = createContext({ message: 'some example value' });\n\nexport default function Parent() {\n return (\n <MyContext.Provider value={{ message: 'updated example value' }}>\n <Child />\n </MyContext.Provider>\n );\n}\n\nexport const Child = () => {\n const value = useContext(MyContext);\n return <p>{value.message}</p>;\n};\n```\n\n### To Qwik\n\n```tsx\nexport const MyContext = createContextId('my-context');\n\nexport const Parent = component$(() => {\n const message = useSignal('some example value');\n useContextProvider(MyContext, message);\n return (\n <>\n <Child />\n </>\n );\n});\n\nexport const Child = component$(() => {\n const message = useContext(MyContext);\n return <p>{message.value}</p>;\n});\n```\n\n**How can I avoid prop drilling?**\n\nYou simply need to create a [context](https://qwik.dev/docs/core/context/#context).\n\nJust create the context in the component where you need to store the information and then, in its descendants, get the information through the corresponding ContextId.\n\n## Create a debounced input\n\n### From React\n\n```tsx\nexport const DebouncedInput = () => {\n const [value, setValue] = useState('');\n const [debouncedValue, setDebouncedValue] = useState(value);\n\n useEffect(() => {\n const debounced = setTimeout(() => setDebouncedValue(value), 1000);\n return () => clearTimeout(debounced);\n }, [value]);\n\n return (\n <>\n <input\n value={value}\n onChange={(ev) => setValue((ev.target as HTMLInputElement).value)}\n />\n <p>{debouncedValue}</p>\n </>\n );\n};\n```\n\n### To Qwik\n\n```tsx\nexport const DebouncedInput = component$(() => {\n const inputText = useSignal('');\n const debouncedValue = useSignal('');\n\n useTask$(({ track, cleanup }) => {\n track(() => inputText.value);\n\n const debounced = setTimeout(() => {\n debouncedValue.value = inputText.value;\n }, 1000);\n cleanup(() => clearTimeout(debounced));\n });\n\n return (\n <>\n <input bind:value={inputText} />\n <p>{debouncedValue.value}</p>\n </>\n );\n});\n```\n\n## Change background color randomly every button click\n\n### From React\n\n```tsx\nexport function DynamicBackground() {\n const [red, setRed] = useState(0);\n const [green, setGreen] = useState(0);\n const [blue, setBlue] = useState(0);\n return (\n <div\n style={{\n background: `rgb(${red}, ${green}, ${blue})`,\n }}\n >\n <button\n onClick={() => {\n setRed(Math.random() * 256);\n setGreen(Math.random() * 256);\n setBlue(Math.random() * 256);\n }}\n >\n Change background\n </button>\n </div>\n );\n}\n```\n\n### To Qwik\n\n```tsx\nexport const DynamicBackground = component$(() => {\n const red = useSignal(0);\n const green = useSignal(0);\n const blue = useSignal(0);\n\n return (\n <div\n style={{\n background: `rgb(${red.value}, ${green.value}, ${blue.value})`,\n }}\n >\n <button\n onClick$={() => {\n red.value = Math.random() * 256;\n green.value = Math.random() * 256;\n blue.value = Math.random() * 256;\n }}\n >\n Change background\n </button>\n </div>\n );\n});\n```\n\n## Create a component that renders a list of the presidents\n\n### From React\n\n```tsx\nexport function Presidents() {\n const presidents = [\n { name: 'George Washington', years: '1789-1797' },\n { name: 'John Adams', years: '1797-1801' },\n { name: 'Thomas Jefferson', years: '1801-1809' },\n { name: 'James Madison', years: '1809-1817' },\n { name: 'James Monroe', years: '1817-1825' },\n { name: 'John Quincy Adams', years: '1825-1829' },\n { name: 'Andrew Jackson', years: '1829-1837' },\n { name: 'Martin Van Buren', years: '1837-1841' },\n { name: 'William Henry Harrison', years: '1841-1841' },\n { name: 'John Tyler', years: '1841-1845' },\n { name: 'James K. Polk', years: '1845-1849' },\n { name: 'Zachary Taylor', years: '1849-1850' },\n { name: 'Millard Fillmore', years: '1850-1853' },\n { name: 'Franklin Pierce', years: '1853-1857' },\n { name: 'James Buchanan', years: '1857-1861' },\n { name: 'Abraham Lincoln', years: '1861-1865' },\n { name: 'Andrew Johnson', years: '1865-1869' },\n { name: 'Ulysses S. Grant', years: '1869-1877' },\n { name: 'Rutherford B. Hayes', years: '1877-1881' },\n { name: 'James A. Garfield', years: '1881-1881' },\n { name: 'Chester A. Arthur', years: '1881-1885' },\n { name: 'Grover Cleveland', years: '1885-1889' },\n ];\n return (\n <ul>\n {presidents.map((president) => (\n <li key={president.name + president.years}>\n {president.name} ({president.years})\n </li>\n ))}\n </ul>\n );\n}\n```\n\n### To Qwik\n\n```tsx\nexport const Presidents = component$(() => {\n const presidents = [\n { name: 'George Washington', years: '1789-1797' },\n { name: 'John Adams', years: '1797-1801' },\n { name: 'Thomas Jefferson', years: '1801-1809' },\n { name: 'James Madison', years: '1809-1817' },\n { name: 'James Monroe', years: '1817-1825' },\n { name: 'John Quincy Adams', years: '1825-1829' },\n { name: 'Andrew Jackson', years: '1829-1837' },\n { name: 'Martin Van Buren', years: '1837-1841' },\n { name: 'William Henry Harrison', years: '1841-1841' },\n { name: 'John Tyler', years: '1841-1845' },\n { name: 'James K. Polk', years: '1845-1849' },\n { name: 'Zachary Taylor', years: '1849-1850' },\n { name: 'Millard Fillmore', years: '1850-1853' },\n { name: 'Franklin Pierce', years: '1853-1857' },\n { name: 'James Buchanan', years: '1857-1861' },\n { name: 'Abraham Lincoln', years: '1861-1865' },\n { name: 'Andrew Johnson', years: '1865-1869' },\n { name: 'Ulysses S. Grant', years: '1869-1877' },\n { name: 'Rutherford B. Hayes', years: '1877-1881' },\n { name: 'James A. Garfield', years: '1881-1881' },\n { name: 'Chester A. Arthur', years: '1881-1885' },\n { name: 'Grover Cleveland', years: '1885-1889' },\n ];\n return (\n <ul>\n {presidents.map((president) => (\n <li key={president.name + president.years}>\n {president.name} ({president.years})\n </li>\n ))}\n </ul>\n );\n});\n```\n"},{"id":"/docs/upgrade/","title":"Upgrade","description":"Migration notes, upgrade guidance, and version transition details.","url":"https://next.qwik.dev/docs/upgrade/","content":"# Migrating to Qwik v2\n\nQwik v2 is a ground-up rewrite of the framework. This guide covers what's new, how to run the automated migration, and what to verify afterward.\n\n## What's New in v2\n\n- **Vite environment API** — Better monorepo and adapter support\n- **Vite 8 / Rolldown** — Out of the box compatibility\n- **Smaller serialized state** — Up to 30% smaller HTML\n- **HMR** — Instant browser updates without losing state\n- **Async `useComputed$`** — Replaces `useResource$` with auto-tracking, polling, concurrency control, and abort\n- **`<Pending>`** — Shows fallback UI while part of the page waits\n\n## Quick Start\n\n1. [Run the CLI](#run-the-migration-cli)\n2. [Handle third-party libraries](#third-party-libraries)\n3. [Check behavioral changes](#behavioral-changes)\n4. [Migrate deprecated APIs](#deprecated-apis)\n5. [Update your tests](#tests)\n6. [Run the checklist](#verification-checklist)\n\n---\n\n## Run the Migration CLI\n\n```shell\npnpm qwik migrate-v2\n```\n\nThe CLI handles package renames, identifier changes, config updates, and dependency migration automatically.\n\n**What the CLI renames**\n\n**Packages**\n\n| v1 | v2 |\n|---|---|\n| `@builder.io/qwik` | `@qwik.dev/core` |\n| `@builder.io/qwik-city` | `@qwik.dev/router` |\n| `@builder.io/qwik-react` | `@qwik.dev/react` |\n| `@qwik-city-plan` | `getRouterConfig()` from `@qwik.dev/router` (`@qwik-router-config` still works) |\n| `@builder.io/qwik/jsx-runtime` | `@qwik.dev/core/jsx-runtime` |\n\n**Identifiers**\n\n| v1 | v2 |\n|---|---|\n| `QwikCityProvider` | `QwikRouterProvider` |\n| `qwikCity` | `qwikRouter` |\n| `QwikCityPlugin` | `QwikRouterPlugin` |\n| `createQwikCity` | `createQwikRouter` |\n| `qwikCityPlan` | `qwikRouterConfig` |\n| `jsxs` | `jsx` |\n\n---\n\n## Third-Party Libraries\n\nIf you use third-party libraries that depend on `@builder.io/qwik`, you may need to configure overrides and SSR bundling.\n\n### Package manager overrides\n\nRedirect the old package name so your package manager doesn't install v1 alongside v2:\n\n```json\n{\n \"pnpm\": {\n \"overrides\": {\n \"@builder.io/qwik\": \"npm:@qwik.dev/core@^2\",\n \"@builder.io/qwik-city\": \"npm:@qwik.dev/router@^2\"\n }\n }\n}\n```\n\n### ssr.noExternal\n\nQwik libraries no longer need to be bundled into the server build. The Vite plugin finds them in your dependencies and excludes them from dependency optimization. A production server build treats them like any other dependency, so your config decides whether they are external, and an external library shares Qwik's runtime state with your app, Qwik Router included. The dev server and builds with a `NODE_ENV` other than `production` always bundle them, because those builds contain the development version of Qwik, while Node loads the production version for an external library.\n\nA production server loads an external library from `node_modules` at runtime, and the library imports `@qwik.dev/core` (and often `@qwik.dev/router`) there too. Keep those packages in `dependencies` rather than `devDependencies` when you deploy with `npm install --omit=dev`, and make the library resolve the same `@qwik.dev/core` version as your app; the server refuses to load two Qwik versions. Otherwise add the library to `resolve.noExternal` to bundle it. The production build warns about each of these.\n\nLibraries built for Qwik v1 import `@builder.io/qwik`, which only the bundler resolves, so they must stay bundled. Add them to `resolve.noExternal`, which reaches every server environment, including the one static site generation adapters build in, together with the [package manager overrides](#package-manager-overrides):\n\n```typescript\n// vite.config.ts\nexport default defineConfig({\n resolve: {\n noExternal: ['some-v1-qwik-library'],\n },\n});\n```\n\n---\n\n## Behavioral Changes\n\nThese won't cause compile errors but will break runtime behavior if not addressed.\n\n### useComputed$ now supports async\n\nIn v1 `useComputed$` rejected async functions. In v2 it accepts them: pass an `async` function (or return a Promise) and `.value` holds the resolved result. Qwik auto-tracks the signals and stores the function reads before the first `await`; reads after an `await` must use the `track()` provided on the context argument.\n\n```typescript\n// v2 — useComputed$ handles async directly\nconst data = useComputed$(async ({ abortSignal }) => {\n const result = await fetch('/api/data', { signal: abortSignal });\n return result.json();\n});\n```\n\n**READING COMPUTEDSIGNAL.VALUE**\n\n`.value` throws while unresolved, and re-throws the error if the computation failed. Read it inside [`<Pending>`](/docs/labs/pending.md) and [`<Catch>`](/docs/labs/catch.md), or provide an `initial` value.\n\n```tsx\nconst DataView = component$((props: { data: Signal<unknown> }) => {\n return <p>{JSON.stringify(props.data.value)}</p>;\n});\n\n// In the component that owns `data`:\nreturn (\n <Catch fallback$={$((error) => <p>Error: {error.message}</p>)}>\n <Pending fallback$={() => <p>Loading...</p>}>\n <DataView data={data} />\n </Pending>\n </Catch>\n);\n```\n\n### useVisibleTask$ eagerness removed\n\nThe `eagerness` option (`'load'` / `'idle'`) was removed in v2. Delete it if present.\n\n### QwikCityProvider → useQwikRouter\n\nReplace the `<QwikCityProvider>` wrapper with the `useQwikRouter()` hook:\n\n```tsx\n// v1\nimport { QwikCityProvider, RouterOutlet } from '@builder.io/qwik-city';\n\nexport default component$(() => {\n return (\n <QwikCityProvider>\n <head>\n <meta charset=\"utf-8\" />\n </head>\n <body>\n <RouterOutlet />\n </body>\n </QwikCityProvider>\n );\n});\n```\n\n```tsx\n// v2\nimport { RouterOutlet, useQwikRouter } from '@qwik.dev/router';\n\nexport default component$(() => {\n useQwikRouter();\n\n return (\n <>\n <head>\n <meta charset=\"utf-8\" />\n </head>\n <body>\n <RouterOutlet />\n </body>\n </>\n );\n});\n```\n\nIf your root component is reactive (reads signals), use `` instead. `useQwikRouter()` only runs once during SSR.\n\n### Event attribute names changed\n\nThe attributes Qwik writes into the HTML for listeners were renamed. This only matters if you inspect, query, or assert on them — JSX (`onClick$`, `document:onKeyDown$`) and `useOn*()` are unchanged.\n\n| Scope | v1 attribute | v2 attribute | v2 passive |\n|---|---|---|---|\n| Element | `on:click` | `q-e:click` | `q-ep:click` |\n| Document | `on-document:click` | `q-d:click` | `q-dp:click` |\n| Window | `on-window:click` | `q-w:click` | `q-wp:click` |\n\nPassive listeners (`{ passive: true }`) are new in v2 and get their own prefix, so a query for `q-e:scroll` will not match a passive scroll listener.\n\nThe event name itself is still lowercased unless you opt into case sensitivity with a leading `-`, but v2 adds two rules: `--` is a literal `-` (`dbl--click` → `dbl-click`), and `DOMContentLoaded` is stored as `-d-o-m-content-loaded`.\n\n### Signal is a wider type\n\nIn v1 `Signal<T>` was `{ value: T }`. In v2 it also has `untrackedValue` and `trigger()`:\n\n```typescript\nexport interface Signal<T = any> {\n value: T;\n untrackedValue: T;\n trigger(): void;\n}\n```\n\nHand-rolled `{ value }` objects therefore no longer satisfy `Signal<T>`. This shows up most in tests and in helpers that fake a signal. Use the now-public `createSignal()` instead of a literal:\n\n```typescript\n// v1 — no longer type-checks in v2\nconst fake: Signal<number> = { value: 0 };\n\n// v2\nimport { createSignal } from '@qwik.dev/core';\nconst fake = createSignal(0);\n```\n\n### client.devInput removed\n\nThe `client.devInput` option of `qwikVite()` (v1 default `src/entry.dev.tsx`) is gone. Remove it from `vite.config.ts`. For SSR apps the dev server renders through `ssr.input`; for CSR apps (`csr: true`) it uses Vite's `index.html`.\n\n### Module-level variable mutated inside a closure no longer builds\n\nThe v2 Optimizer extracts closures more aggressively than v1. If an extracted closure mutates an exported module-level `let`, the Optimizer rewrites the reference as an `import`, and assigning to an import binding fails at build time — a path v1's less aggressive extraction didn't reach.\n\n```tsx\n// Fails to build in v2\nexport let count = 0;\ncomponent$(() => {\n return <button onClick$={() => count++}>{count}</button>;\n});\n```\n\nMove the mutation into an exported accessor function in a separate module:\n\n```tsx\n// counter.ts\nlet count = 0;\nexport const getCount = () => count;\nexport const incrementCount = () => count++;\n```\n\n```tsx\nimport { getCount, incrementCount } from './counter';\n\ncomponent$(() => {\n return <button onClick$={() => incrementCount()}>{getCount()}</button>;\n});\n```\n\nSee [Module-level variables cannot be mutated after extraction](/advanced/dollar/#module-level-variables-cannot-be-mutated-after-extraction).\n\n### Serialization\n\nv1 serialized state into `<script type=\"qwik/json\">` tags. v2 uses `<script type=\"qwik/vnode\">` and `<script type=\"qwik/state\">` at the end of the document. No code change needed, but tooling that parses the old tags will need updating.\n\n---\n\n## Deprecated APIs\n\nStill compile in v2, removed in v3.\n\n### useResource$ → async useComputed$\n\n| Aspect | v1 `useResource$` | v2 async `useComputed$` |\n|---|---|---|\n| Return type | `.value: Promise<T>` | `.value: T` |\n| Track deps | `ctx.track(() => sig.value)` | read `sig.value` directly before the first `await` (auto-tracked); use `ctx.track()` after an `await` |\n| Abort | Manual `AbortController` | `ctx.abortSignal` |\n| Previous value | - | `ctx.previous` |\n| Polling | - | `usePoll(signal, ms)` from `@qwik.dev/utils` |\n| Initial value | - | `options.initial` |\n| Rendering | `<Resource onResolved={} />` | read `.value` inside `<Pending>` / `<Catch>` |\n\n**Full before/after example**\n\nv1:\n\n```tsx\nimport { useResource$, Resource } from '@builder.io/qwik';\n\nconst Cmp = component$(() => {\n const city = useSignal('');\n\n const weather = useResource$(async ({ track, cleanup }) => {\n const cityName = track(() => city.value);\n const controller = new AbortController();\n cleanup(() => controller.abort());\n const res = await fetch(`/api/weather?city=${cityName}`, {\n signal: controller.signal,\n });\n return res.json() as Promise<{ temp: number }>;\n });\n\n return (\n <div>\n <input name=\"city\" bind:value={city} />\n <Resource\n value={weather}\n onPending={() => <span>Loading...</span>}\n onRejected={(e) => <span>Error: {e.message}</span>}\n onResolved={(data) => <span>Temperature: {data.temp}</span>}\n />\n </div>\n );\n});\n```\n\nv2:\n\n```tsx\nimport { $, Catch, Pending, useComputed$, type Signal } from '@qwik.dev/core';\n\nconst Temperature = component$((props: { weather: Signal<{ temp: number }> }) => {\n return <div>Temperature: {props.weather.value.temp}</div>;\n});\n\nconst Cmp = component$(() => {\n const city = useSignal('');\n\n const weather = useComputed$(async ({ abortSignal }) => {\n const cityName = city.value;\n const res = await fetch(`/api/weather?city=${cityName}`, {\n signal: abortSignal,\n });\n return res.json() as Promise<{ temp: number }>;\n });\n\n return (\n <div>\n <input name=\"city\" bind:value={city} />\n <Catch fallback$={$((error) => <div>Error: {error.message}</div>)}>\n <Pending fallback$={() => <div>Loading...</div>}>\n <Temperature weather={weather} />\n </Pending>\n </Catch>\n </div>\n );\n});\n```\n\n`useComputed$()` owns the work that creates the value. [`<Pending>`](/docs/labs/pending.md) owns the fallback UI if you want to read `.value` directly while the value may still be pending.\n\nWhat changed:\n\n- `track(() => signal.value)` → read `signal.value` directly before the first `await` (auto-tracked); after an `await`, keep using the provided `track()`\n- Manual `AbortController` + `cleanup()` → `ctx.abortSignal`\n- `<Resource onPending onRejected onResolved />` → `<Pending>` and `<Catch>`\n- `.value` is `T` directly, not `Promise<T>`\n- `.error` is `Error | undefined`\n- For unlimited parallel fetches, pass `{ concurrency: 0 }`\n\n### `ReadonlySignal` → `Readonly<Signal<T>>`\n\nIn v1 `ReadonlySignal<T>` was an alias for `Readonly<Signal<T>>`. In v2 it is a standalone interface exposing only `value`, so it is no longer interchangeable with a real signal. Replace it:\n\n```typescript\n// v1\nconst label: ReadonlySignal<string> = useComputed$(() => name.value);\n\n// v2\nconst label: Readonly<Signal<string>> = useComputed$(() => name.value);\n```\n\n### qwik-labs\n\n`@builder.io/qwik-labs` is removed in v2:\n\n| Feature | v2 Replacement |\n|---|---|\n| Insights | `@qwik.dev/core/insights` + `@qwik.dev/core/insights/vite` |\n| Typed Routes | Built into `@qwik.dev/router` via `qwikTypes()` |\n\n**Migrating Insights step-by-step**\n\n1. Remove the old package: `pnpm remove @builder.io/qwik-labs`\n\n2. Enable the experimental feature and add the plugin:\n\n```typescript\n// vite.config.ts\nimport { qwikVite } from '@qwik.dev/core/optimizer';\nimport { qwikInsights } from '@qwik.dev/core/insights/vite';\n\nexport default defineConfig(() => ({\n plugins: [\n qwikVite({ experimental: ['insights'] }),\n qwikInsights(),\n ],\n}));\n```\n\n3. Update the import in `root.tsx`:\n\n```typescript\n// Before\nimport { Insights } from '@builder.io/qwik-labs';\n// After\nimport { Insights } from '@qwik.dev/core/insights';\n```\n\n---\n\n## Tests\n\n`@qwik.dev/core/testing` still exports `createDOM()` and `trigger()`, but v2 dispatches closer to what the browser does, which surfaces test code that relied on the old shortcuts.\n\n### event.target is not populated\n\n`trigger()` builds a real `Event` and invokes each handler as `handler(event, element)` rather than calling `element.dispatchEvent()`, so `event.target` stays `null`. Read the element from the second argument:\n\n```tsx\n// v1 — target was often good enough\nconst onInput$ = $((event: Event) => {\n value.value = (event.target as HTMLInputElement).value;\n});\n\n// v2 — use the element argument\nconst onInput$ = $((event: Event, element: HTMLInputElement) => {\n value.value = element.value;\n});\n```\n\n### Rendering over an existing container\n\nv2 refuses to re-render into an element that already has a `q:container`. Create a fresh DOM per test instead of reusing one across cases.\n\n### trigger() returns the event\n\n`trigger()` now returns the dispatched `Event` (or `null` if nothing matched), so you can assert on `defaultPrevented` or on payload fields you passed in. It also waits for the container to settle by default; pass `{ waitForIdle: false }` to opt out.\n\n### Faking signals\n\nUse `createSignal()` rather than a `{ value }` literal — see [Signal is a wider type](#signal-is-a-wider-type).\n\n---\n\n## Troubleshooting\n\nFind your error message below.\n\n### useComputed$ QRL ... cannot return a Promise\n\nNo longer thrown in v2: `useComputed$` now supports async functions. See [useComputed$ now supports async](#usecomputed-now-supports-async).\n\n### Only primitive and object literals can be serialized\n\nA class instance or plain function in a store/signal/prop (error Q3). Wrap with `noSerialize()` or convert to a QRL with `$()`.\n\n### Qwik version X already imported while importing Y\n\nTwo different Qwik versions loaded on the server (error Q30). Add [package manager overrides](#package-manager-overrides) so every library resolves to the same `@qwik.dev/core`.\n\n### IMPORTANT: This dependency was pre-bundled by Vite\n\nAdd the library to `optimizeDeps.exclude`. See [ssr.noExternal](#ssrnoexternal).\n\n### [package] is being treated as an external dependency\n\nThe dev server and development builds bundle every Qwik library, but this one is not listed in your `package.json`, for example because another library depends on it. Add it to your dependencies, or to both `resolve.noExternal` and `optimizeDeps.exclude`. See [ssr.noExternal](#ssrnoexternal).\n\n### Cannot find module '@builder.io/qwik'\n\nUsually a stale `jsxImportSource` in `tsconfig.json`. Run the CLI again or check your `tsconfig.json`.\n\n### Cannot find module '@builder.io/qwik-labs'\n\nPackage removed in v2. See [qwik-labs](#qwik-labs).\n\n### ERR_REQUIRE_ESM / require() of ES Module\n\nAdd `\"type\": \"module\"` to `package.json`. Run the CLI again if this wasn't set automatically.\n\n### Calling a 'use*()' method outside 'component$(...)'\n\nMove the hook inside `component$` (error Q10).\n\n### Property 'untrackedValue' is missing in type\n\nA `{ value }` object literal used where a `Signal` is expected. See [Signal is a wider type](#signal-is-a-wider-type).\n\n### Cannot read properties of null (reading 'value') in a test\n\n`event.target` is `null` under `trigger()`. See [event.target is not populated](#eventtarget-is-not-populated).\n\n### Cannot assign to import ... / Illegal reassignment of import ...\n\nA module-level `let` mutated inside a `$`-extracted closure. The exact wording depends on the bundler: esbuild says `Cannot assign to import \"x\"`, Rollup/Rolldown say `Illegal reassignment of import \"x\"`. See [Module-level variable mutated inside a closure no longer builds](#module-level-variable-mutated-inside-a-closure-no-longer-builds).\n\n### Move qwik packages [...] to devDependencies\n\nOlder starters check this in `vite.config.ts`. Remove the check: a production server that loads Qwik libraries from `node_modules` needs `@qwik.dev/core` in `dependencies`. See [ssr.noExternal](#ssrnoexternal).\n\n---\n\n## Verification Checklist\n\nEvery item should pass before your migration is done.\n"},{"id":"/docs/labs/pending/","title":"Pending","description":"Experimental fallback boundaries for async rendering and out-of-order streaming, including `useComputed$`, `delay`, and `Reveal` patterns.","url":"https://next.qwik.dev/docs/labs/pending/","content":"# Pending\n\n**Stage:** `implementation`\n\n `Pending` and out-of-order streaming are experimental. Their API and rendering behavior may still\n change as the feature develops.\n\n`<Pending>` shows a fallback while its content is loading.\n\nWhen the content is ready, Qwik hides the fallback and shows the real content.\n\nPending does not fetch data or create async values. It only decides what to show while rendering is paused.\n\nThe high-level model is:\n\n```tsx\nuseSignal() // state you set directly\nuseComputed$() // state calculated synchronously or from async work\n\n<Pending> // fallback UI while content loads\n```\n\nThe loading work happens elsewhere. Pending only shows the fallback.\n\n## Basic Usage\n\nWrap loading content with `<Pending>` and pass a `fallback$`:\n\n```tsx /Pending/ /fallback$/ /delay/\nimport { component$, Pending, useSignal, type JSXOutput } from '@qwik.dev/core';\n\nconst AsyncMessage = component$(() => {\n const content = new Promise<JSXOutput>((resolve) => {\n setTimeout(() => resolve(<p>Async content resolved.</p>), 1000);\n });\n\n return <>{content}</>;\n});\n\nexport default component$(() => {\n const show = useSignal(false);\n\n return (\n <section>\n <button onClick$={() => (show.value = !show.value)}>\n {show.value ? 'Hide' : 'Show'} content\n </button>\n\n {show.value && (\n <Pending fallback$={() => <p>Loading content...</p>} delay={150}>\n <AsyncMessage />\n </Pending>\n )}\n </section>\n );\n});\n```\n\nWhile `AsyncMessage` is loading, Qwik shows the fallback. Once it resolves, Qwik shows the real content.\n\n## With `useComputed$()`\n\nThe computed signal loads the data. Pending shows the fallback while `user.value` is not ready.\n\n```tsx /useComputed$/ /Pending/ /user.value/\nimport { component$, Pending, useComputed$, useSignal } from '@qwik.dev/core';\n\ntype User = {\n name: {\n first: string;\n last: string;\n };\n email: string;\n};\n\nconst UserCard = component$(() => {\n const user = useComputed$(async ({ abortSignal }) => {\n const response = await fetch('https://randomuser.me/api/', {\n signal: abortSignal,\n });\n const data = (await response.json()) as {\n results: User[];\n };\n\n return data.results[0];\n });\n\n return (\n <p>\n User: {user.value.name.first} {user.value.name.last} ({user.value.email})\n </p>\n );\n});\n\nexport default component$(() => {\n const show = useSignal(false);\n\n return (\n <section>\n <button onClick$={() => (show.value = !show.value)}>\n {show.value ? 'Hide user' : 'Load random user'}\n </button>\n\n {show.value && (\n <Pending fallback$={() => <p>Loading user...</p>}>\n <UserCard />\n </Pending>\n )}\n </section>\n );\n});\n```\n\nWhen `UserCard` reads `user.value` before the request finishes, Qwik shows the nearest `<Pending>` fallback.\n\nIf the computation fails, reading `user.value` re-throws the error. Wrap the section in [`<Catch>`](/docs/labs/catch.md) to render a fallback instead.\n\n## What Can Trigger Pending\n\nPending can show its fallback when content inside it is still loading, including:\n\n- reading an async `useComputed$()` value before it is ready\n- returning a `Promise` from JSX\n- rendering a child component that is still loading\n- running descendant work that blocks rendering\n\nPending does not do the loading work. It only controls the fallback while that work finishes.\n\n## Out-of-order Streaming\n\nOut-of-order streaming is an optional server rendering mode for `<Pending>`.\n\nServer rendering means Qwik creates HTML on the server and sends it to the browser. Streaming means\nthe browser can receive that HTML in chunks, within the same HTTP connection, instead of waiting for\none complete HTML string.\n\nOut-of-order streaming helps when one section of the page is slow, but the rest of the page is ready.\n\nWithout out-of-order streaming, the server renders the page in order. If a Pending child is still\nwaiting, the server waits at that point before it can continue sending the next HTML.\n\nWith out-of-order streaming, Qwik can:\n\n1. Send the HTML that is ready.\n2. Send the Pending fallback for that section.\n3. Continue sending the rest of the page, such as the footer or nearby buttons.\n4. Send the real Pending content later, when it finishes.\n5. Hide the fallback and show the real content in the browser.\n\nDuring SSR, Qwik includes the fallback in the stream when the boundary has a fallback. Qwik hides\nthat fallback when the resolved content is shown. It stays in the DOM; it is not removed.\n\nIf the boundary has a positive `delay`, Qwik still sends the fallback HTML immediately, but starts\nit hidden. If the delay finishes before the content, Qwik reveals the fallback. If the content\nfinishes before the delay, the fallback remains hidden and the resolved content is shown instead.\n\nFrom the user's point of view, the page appears sooner. They can see the shell of the page while\none slower section is still loading.\n\nOut-of-order streaming only applies to promises inside `<Pending>`. A promise outside Pending still\nfollows the normal SSR rendering behavior.\n\nYou do not need to write the streaming markers or reveal scripts yourself. Keep writing\n`<Pending>` and fallbacks normally; Qwik handles the streamed HTML and browser-side reveal.\n\n### Enable Pending\n\nPending is experimental, so first enable it in `vite.config.ts`:\n\n```ts title=\"vite.config.ts\" /experimental/\nimport { qwikVite } from '@qwik.dev/core/optimizer';\nimport { qwikRouter } from '@qwik.dev/router/vite';\nimport { defineConfig } from 'vite';\nimport tsconfigPaths from 'vite-tsconfig-paths';\n\nexport default defineConfig(() => ({\n plugins: [\n qwikRouter(),\n qwikVite({\n experimental: ['pendingBoundary'],\n }),\n tsconfigPaths(),\n ],\n}));\n```\n\n### Configure Out-of-order Streaming\n\nAfter Pending is enabled, out-of-order streaming is enabled by default. You can also set it\nexplicitly in your server entry point.\n\nMost Qwik apps have a `src/entry.ssr.tsx` file. That file receives render options from the adapter\nand returns the JSX and options that should be rendered.\n\nAdd `streaming.outOfOrder` to those options if you want to set it directly:\n\n```tsx title=\"src/entry.ssr.tsx\" /outOfOrder/\nimport { createRenderer } from '@qwik.dev/router';\nimport Root from './root';\n\nexport default createRenderer((opts) => {\n return {\n jsx: <Root />,\n options: {\n ...opts,\n streaming: {\n ...opts.streaming,\n outOfOrder: true,\n },\n },\n };\n});\n```\n\nThe enabled value is:\n\n```ts\noutOfOrder: true\n```\n\nTo turn it off again, use:\n\n```ts\noutOfOrder: false\n```\n\nIf your project calls `renderToStream()` directly, pass the same `streaming` option when you want to\nset it explicitly:\n\n```tsx title=\"src/entry.ssr.tsx\" /outOfOrder/\nimport { renderToStream, type RenderToStreamOptions } from '@qwik.dev/core/server';\nimport Root from './root';\n\nexport default function (opts: RenderToStreamOptions) {\n return renderToStream(<Root />, {\n ...opts,\n streaming: {\n ...opts.streaming,\n outOfOrder: true,\n },\n });\n}\n```\n\n### Example\n\nIn this example, the page shell and fallback can stream before `ProfileDetails` finishes:\n\n```tsx /Pending/ /fallback$/ /profile.value/\nimport { component$, Pending, useComputed$ } from '@qwik.dev/core';\n\nconst ProfileDetails = component$(() => {\n const profile = useComputed$(async ({ abortSignal }) => {\n const response = await fetch('/api/profile', {\n signal: abortSignal,\n });\n\n return response.json() as Promise<{\n name: string;\n plan: string;\n }>;\n });\n\n return (\n <section>\n <h2>{profile.value.name}</h2>\n <p>Plan: {profile.value.plan}</p>\n </section>\n );\n});\n\nexport default component$(() => {\n return (\n <main>\n <h1>Account</h1>\n\n <Pending fallback$={() => <p>Loading profile...</p>}>\n <ProfileDetails />\n </Pending>\n\n <footer>Need help? Contact support.</footer>\n </main>\n );\n});\n```\n\nIf `/api/profile` is slow, Qwik can send:\n\n- the `Account` heading\n- the `Loading profile...` fallback\n- the footer\n\nThen, when the profile request resolves, Qwik sends the finished profile HTML and shows it in the\nPending boundary.\n\nIf the profile request finishes quickly, Qwik still sends the fallback during SSR, but the finished\nprofile can be shown before the user notices it.\n\n### Fallbacks\n\nThe fallback is real UI. Choose markup that is useful while the user waits:\n\n```tsx\n<Pending fallback$={() => <p>Loading recommendations...</p>}>\n <Recommendations />\n</Pending>\n```\n\nIf you do not provide a fallback, the boundary has no visible loading UI. The rest of the page can\nstill stream, but that section will appear empty until the content is ready.\n\nWhen out-of-order streaming is enabled, a boundary that suspends during the initial server render\nstreams its fallback as soon as Qwik reaches that boundary. Without a positive `delay`, the fallback\ncan be visible immediately. With a positive `delay`, the fallback is streamed hidden and is only\nrevealed if the delay finishes before the real content.\n\nFor best results:\n\n- keep fallbacks small\n- reserve enough space to avoid layout shift\n- use accessible text, not only a spinner\n- avoid important actions that disappear immediately when the real content arrives\n\n### Interactivity\n\nQwik keeps the streamed HTML resumable.\n\nThat means the shell of the page can become interactive even while a Pending section is still\nwaiting. If your fallback has buttons or other event handlers, they can also resume while the\nfallback is visible, after the root page state has loaded in the browser.\n\nWhen the real content arrives, Qwik hides the fallback and shows the resolved content. The fallback\nstays in the DOM. The resolved content may be visible before it is interactive. Qwik resumes that\ncontent after the root page state and the content's streamed state have both loaded, then its event\nhandlers and state work like any other server-rendered Qwik HTML.\n\n### When to Use It\n\nOut-of-order streaming is useful for independent page sections that may be slower than the rest of\nthe page, such as:\n\n- account panels\n- recommendations\n- reviews\n- dashboards\n- comments\n- secondary content below the main heading\n\nIt is less useful when the slow content is required before the rest of the page makes sense. In that\ncase, showing a complete page a little later may be clearer than streaming a partial page early.\n\n### Static Builds\n\nOut-of-order streaming is an SSR feature. It helps when the browser is receiving an HTTP response\nwhile the server is still rendering.\n\nFor static site generation, the HTML file is created ahead of time. The user receives the finished\nfile later, so there is no live server stream to reveal a fallback first.\n\nFor this reason, Qwik Router disables out-of-order streaming during SSG. Static pages are written as\ncomplete HTML files even if the server entry point sets `streaming.outOfOrder` to `true`.\n\n### Troubleshooting\n\nIf you see an error that says Pending must be enabled, add `experimental: ['pendingBoundary']` to\n`qwikVite()`.\n\nIf the fallback is not visible, check these common causes:\n\n- the resolved content is shown before the browser paints the fallback\n- the slow promise is outside `<Pending>`\n- there is no `fallback$` prop\n- the hosting platform or proxy buffers the whole response instead of streaming it\n\nIf your site uses a Content Security Policy with script nonces, keep passing the nonce through your\nSSR render options. Qwik will add the nonce to the inline scripts it uses for out-of-order\nstreaming.\n\n## `delay`\n\nThe `delay` prop waits before showing the fallback:\n\n```tsx /delay/\nimport {\n component$,\n Pending,\n useSignal,\n type JSXOutput,\n} from '@qwik.dev/core';\n\nconst LOAD_MS = 2500;\nconst FALLBACK_DELAY_MS = 1000;\n\nconst SlowContent = component$(() => (\n <>\n {new Promise<JSXOutput>((resolve) => {\n setTimeout(() => resolve(<p>Loaded content.</p>), LOAD_MS);\n })}\n </>\n));\n\nexport default component$(() => {\n const run = useSignal(0);\n const elapsed = useSignal(0);\n\n return (\n <section>\n <button\n disabled={run.value > 0 && elapsed.value < LOAD_MS}\n onClick$={() => {\n run.value++;\n elapsed.value = 0;\n\n const start = Date.now();\n const timer = setInterval(() => {\n elapsed.value = Math.min(Date.now() - start, LOAD_MS);\n\n if (elapsed.value === LOAD_MS) {\n clearInterval(timer);\n }\n }, 100);\n }}\n >\n Load content\n </button>\n\n {run.value > 0 && (\n <Pending\n fallback$={() => <p>Fallback shown after {FALLBACK_DELAY_MS}ms.</p>}\n delay={FALLBACK_DELAY_MS}\n >\n <SlowContent key={run.value} />\n </Pending>\n )}\n\n <p>Elapsed: {elapsed.value}ms</p>\n </section>\n );\n});\n```\n\nUse `delay` to avoid flashing a loading state for work that usually resolves quickly.\n\nIf the content resolves before the delay finishes, the fallback is not shown.\n\nDuring out-of-order SSR streaming, Qwik still sends the fallback HTML immediately so the browser can\nreveal it without waiting for another HTML chunk. For `delay > 0`, the fallback starts hidden. If\nthe delay finishes first, Qwik reveals it with a streamed update. If the content finishes first, Qwik\ncancels the reveal and shows the resolved content instead.\n\nAfter a boundary shows its content, later asynchronous updates keep that content visible and do not\nshow the fallback again. A newly rendered boundary can show its fallback during its initial load.\n\n## Coordinating Boundaries with `Reveal`\n\nUse `<Reveal>` when a group of sibling `<Pending>` boundaries should reveal in a specific order.\n\n```tsx /Reveal/ /order/ /collapsed/\nimport { component$, Reveal, Pending } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <Reveal order=\"sequential\" collapsed>\n <Pending fallback$={() => <p>Loading profile...</p>}>\n <Profile />\n </Pending>\n\n <Pending fallback$={() => <p>Loading activity...</p>}>\n <Activity />\n </Pending>\n </Reveal>\n );\n});\n```\n\n`Reveal` does not start or resolve async work. It only coordinates which registered boundary is allowed to show its content.\n\nReveal order options:\n\n- `parallel`: boundaries reveal independently\n- `sequential`: later boundaries wait for earlier pending boundaries\n- `reverse`: earlier boundaries wait for later pending boundaries\n- `together`: no boundary reveals content until all boundaries are ready\n\nBy default, a pending boundary that is blocked by `Reveal` can still show its fallback. Add `collapsed` to hide blocked pending boundaries completely until they are allowed to reveal.\n\n## API\n\n```tsx\ntype PendingProps = {\n fallback$?: QRL<() => JSXOutput>;\n delay?: number;\n};\n\ntype RevealOrder = 'parallel' | 'sequential' | 'reverse' | 'together';\n\ntype RevealProps = {\n order?: RevealOrder;\n collapsed?: boolean;\n};\n```\n\nProps:\n\n- `fallback$`: returns the JSX rendered while the boundary is waiting\n- `delay`: milliseconds to wait before showing the fallback, defaults to `0`\n- `order`: reveal order for child Pending boundaries, defaults to `parallel`\n- `collapsed`: hide pending blocked boundaries instead of showing their fallbacks\n\n## Pending Is Not an Error Boundary\n\n`<Pending>` only handles content that is still loading. It does not catch errors thrown by child components.\n\nFor errors thrown by descendants, reach for [`<Catch>`](/api/qwik.md#catch).\n\n## Choosing the Right Primitive\n\n| API | Best for |\n| --- | --- |\n| `useComputed$()` | Derived values, including async data or other async work that should produce a signal |\n| `<Pending>` | Showing one fallback while a section is loading |\n| `useTask$()` | Running setup or update code that writes to existing state or performs a side effect |\n| `routeLoader$()` | Loading route data before the route renders |\n\nFor async work inside a component, `useComputed$()` with an async function is usually the starting point. Add `<Pending>` when one fallback can cover the loading state for a section. Add `<Catch>` to render a fallback when the async work fails.\n"},{"id":"/api/qwik/","title":"@qwik.dev/qwik","description":"Core framework API reference, including components, QRLs, signals, JSX types, and hooks.","url":"https://next.qwik.dev/api/qwik/","content":"# [API](/api.md) › @qwik.dev/core\n\n## \"q:slot\"\n\n```typescript\n'q:slot'?: string;\n```\n\n## \"xlink:actuate\"\n\n```typescript\n'xlink:actuate'?: string | undefined;\n```\n\n## \"xlink:arcrole\"\n\n```typescript\n'xlink:arcrole'?: string | undefined;\n```\n\n## \"xlink:href\"\n\n```typescript\n'xlink:href'?: string | undefined;\n```\n\n## \"xlink:role\"\n\n```typescript\n'xlink:role'?: string | undefined;\n```\n\n## \"xlink:show\"\n\n```typescript\n'xlink:show'?: string | undefined;\n```\n\n## \"xlink:title\"\n\n```typescript\n'xlink:title'?: string | undefined;\n```\n\n## \"xlink:type\"\n\n```typescript\n'xlink:type'?: string | undefined;\n```\n\n## \"xml:base\"\n\n```typescript\n'xml:base'?: string | undefined;\n```\n\n## \"xml:lang\"\n\n```typescript\n'xml:lang'?: string | undefined;\n```\n\n## \"xml:space\"\n\n```typescript\n'xml:space'?: string | undefined;\n```\n\n## \"xmlns:xlink\"\n\n```typescript\n'xmlns:xlink'?: string | undefined;\n```\n\n## $\n\nQwik Optimizer marker function.\n\nUse `$(...)` to tell Qwik Optimizer to extract the expression in `$(...)` into a lazy-loadable resource referenced by `QRL`.\n\n```typescript\n$: <T>(expression: T) => QRL<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| expression | T | Expression which should be lazy loaded |\n\n**Returns:**\n\n[QRL](#qrl-type-alias)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/qrl.public.ts)\n\n## abort\n\nAbort the current computation and run cleanups if needed.\n\n```typescript\nabort(reason?: any): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| reason | any | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n## AsyncFn\n\n> Warning: This API is now obsolete.\n>\n> Use `ComputedFn` instead.\n\n```typescript\nexport type AsyncFn<T> = ComputedFn<T>;\n```\n\n**References:** [ComputedFn](#computedfn)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-computed.ts)\n\n## AsyncSignal\n\n> Warning: This API is now obsolete.\n>\n> Use `ComputedSignal` instead, it has async support now.\n\nAn AsyncSignal holds the result of the given async function. If the function uses `track()` to track reactive state, and that state changes, the AsyncSignal is recalculated, and if the result changed, all tasks which are tracking the AsyncSignal will be re-run and all subscribers (components, tasks etc) that read the AsyncSignal will be updated.\n\nIf the value has not yet been resolved, reading the AsyncSignal will throw a Promise, which will retry the component or task once the value resolves.\n\nIf the value has been resolved, but the async function is re-running, reading the AsyncSignal will subscribe to it and return the last resolved value until the new value is ready. As soon as the new value is ready, the subscribers will be updated.\n\nIf the async function threw an error, reading the `.value` will throw that same error.\n\n```typescript\nexport type AsyncSignal<T = unknown> = ComputedSignal<T>;\n```\n\n**References:** [ComputedSignal](#computedsignal)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/signal.public.ts)\n\n## AsyncSignalOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `ComputedOptions` instead.\n\n```typescript\nexport type AsyncSignalOptions<T> = ComputedOptions<T>;\n```\n\n**References:** [ComputedOptions](#computedoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/types.ts)\n\n## cache\n\n> Warning: This API is now obsolete.\n>\n> Does not do anything\n\n```typescript\ncache(policyOrMilliseconds: number | 'immutable'): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| policyOrMilliseconds | number \\\\| 'immutable' | |\n\n**Returns:**\n\nvoid\n\n## Catch\n\nRenders `fallback$` instead of its children when a descendant throws.\n\n```typescript\nCatch: Component<CatchProps>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/error/catch.ts)\n\n## CatchInfo\n\nStructured metadata about a caught error, passed to `onError$`.\n\n```typescript\nexport interface CatchInfo\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| boundaryId | | string | Identifies the boundary within the page. Allocated in render order and kept across a resume, so every report from one boundary shares it — but it shifts when render order changes. |\n| digest | | string | The code a production fallback shows for a server-origin error, so a user's bug report matches your logs. An error caught during SSR reports a second, different digest if the client re-derives it — the stacks differ. |\n| phase | | [CatchPhase](#catchphase) | Where the caught error originated. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/error/error-handling.ts)\n\n## CatchPhase\n\nIdentifies where an error caught by an error boundary originated.\n\n```typescript\nexport declare const enum CatchPhase\n```\n\n| Member | Value | Description |\n| --- | --- | --- |\n| Event | `\"event\"` | |\n| Hook | `\"hook\"` | |\n| Render | `\"render\"` | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/error/catch-phase.ts)\n\n## CatchProps\n\n```typescript\nexport interface CatchProps\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| fallback$ | | [QRL](#qrl-type-alias)<(error: Error & \\{ digest?: string; }, reset: [QRL](#qrl-type-alias)<() => void>) => [JSXOutput](#jsxoutput)> | Rendered when a descendant throws. The error is always an `Error`, so `{error.message}` is safe: a non-Error throw is wrapped, and production redacts server-origin errors to a generic message plus `digest`. Client-origin errors render as thrown — their messages already live in the browser bundle. Wrap `reset` in a handler — `onClick$={() => reset()}`, not `onClick$={reset}` — so it stays wired in a streamed fallback. |\n| onError$? | | [QRL](#qrl-type-alias)<(error: Error, info: [CatchInfo](#catchinfo)) => void> | _(Optional)_ Side effect only; never affects rendering. Receives the original `Error` — a non-Error throw arrives wrapped, with `cause` set to the raw value. An error caught during SSR fires again when the client re-derives it, so dedupe in your reporter. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/error/catch.ts)\n\n## ClassList\n\nA class list can be a string, a boolean, an array, or an object.\n\nIf it's an array, each item is a class list and they are all added.\n\nIf it's an object, then the keys are class name strings, and the values are booleans that determine if the class name string should be added or not.\n\n```typescript\nexport type ClassList =\n | string\n | undefined\n | null\n | false\n | Record<string, boolean | string | number | null | undefined>\n | ClassList[];\n```\n\n**References:** [ClassList](#classlist)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## cleanup\n\n```typescript\ncleanup(): void;\n```\n\n**Returns:**\n\nvoid\n\n## clear\n\nClear the value and recompute. Unlike `invalidate()`, readers see the loading state (reads throw the computation promise) instead of the stale value while the new value computes.\n\n```typescript\nclear(): void;\n```\n\n**Returns:**\n\nvoid\n\n## Component\n\nType representing the Qwik component.\n\n`Component` is the type returned by invoking `component$`.\n\n```tsx\ninterface MyComponentProps {\n someProp: string;\n}\nconst MyComponent: Component<MyComponentProps> = component$(\n (props: MyComponentProps) => {\n return <span>{props.someProp}</span>;\n },\n);\n```\n\n```typescript\nexport type Component<PROPS = unknown> = FunctionComponent<PublicProps<PROPS>>;\n```\n\n**References:** [FunctionComponent](#functioncomponent), [PublicProps](#publicprops)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/component.public.ts)\n\n## component$\n\nDeclare a Qwik component that can be used to create UI.\n\nUse `component$` to declare a Qwik component. A Qwik component is a special kind of component that allows the Qwik framework to lazy load and execute the component independently of other Qwik components as well as lazy load the component's life-cycle hooks and event handlers.\n\nSide note: You can also declare regular (standard JSX) components that will have standard synchronous behavior.\n\nQwik component is a facade that describes how the component should be used without forcing the implementation of the component to be eagerly loaded. A minimum Qwik definition consists of:\n\n### Example\n\nAn example showing how to create a counter component:\n\n```tsx\nexport interface CounterProps {\n initialValue?: number;\n step?: number;\n}\nexport const Counter = component$((props: CounterProps) => {\n const state = useSignal(props.initialValue || 0);\n return (\n <div>\n <span>{state.value}</span>\n <button onClick$={() => (state.value += props.step || 1)}>+</button>\n </div>\n );\n});\n```\n\n- `component$` is how a component gets declared. - `{ value?: number; step?: number }` declares the public (props) interface of the component. - `{ count: number }` declares the private (state) interface of the component.\n\nThe above can then be used like so:\n\n```tsx\nexport const OtherComponent = component$(() => {\n return <Counter initialValue={100} />;\n});\n```\n\nSee also: `component`, `useCleanup`, `onResume`, `onPause`, `useOn`, `useOnDocument`, `useOnWindow`, `useStyles`\n\n```typescript\ncomponent$: <PROPS = unknown>(onMount: OnRenderFn<PROPS>) => Component<PROPS>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| onMount | [OnRenderFn](#onrenderfn)<PROPS> | |\n\n**Returns:**\n\n[Component](#component)&lt;PROPS&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/component.public.ts)\n\n## ComponentBaseProps\n\n```typescript\nexport interface ComponentBaseProps\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| [\"q:slot\"?](#componentbaseprops-_q_slot_) | | string | _(Optional)_ |\n| key? | | string \\\\| number \\\\| null \\\\| undefined | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## ComputedFn\n\nThe compute function. The context provides `track()`, `previous` (the last computed value), `info` (the argument of the `invalidate(info)` call that triggered this computation), `cleanup()` and `abortSignal`. Synchronous reactive state reads are tracked automatically, use `untrack()` to read signals without tracking. Return a `Promise` (or use an `async` function) for async values. After the first `await`, reads are no longer tracked automatically and must use `track()`.\n\n```typescript\nexport type ComputedFn<T> = (ctx: ComputeCtx) => ValueOrPromise<T>;\n```\n\n**References:** [ValueOrPromise](#valueorpromise)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-computed.ts)\n\n## ComputedOptions\n\n```typescript\nexport interface ComputedOptions<T = unknown>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| clientOnly? | | boolean | _(Optional)_ When true, the async computation is postponed to the browser. On SSR, the signal remains INVALID and does not execute the function. On the client, it will compute on first read. Defaults to `false`. |\n| concurrency? | | number | _(Optional)_ Maximum number of concurrent computations. Use `0` for unlimited. Defaults to `1`. |\n| container? | | Container | _(Optional)_ |\n| eagerCleanup? | | boolean | _(Optional)_ When subscribers drop to 0, run cleanup in the next tick, instead of waiting for the function inputs to change. Defaults to `false`, meaning cleanup happens only when inputs change. |\n| initial? | | Awaited<T> \\\\| (() => Awaited<T>) | _(Optional)_ Like useSignal's `initial`; prevents the throw on first read when uninitialized |\n| serializationStrategy? | | [SerializationStrategy](#serializationstrategy) | _(Optional)_ |\n| timeout? | | number | _(Optional)_ Maximum time in milliseconds to wait for the async computation to complete. If exceeded, the computation is aborted and an error is thrown. If `0`, no timeout is applied. Defaults to `0`. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/types.ts)\n\n## ComputedReturnType\n\n```typescript\nexport type ComputedReturnType<T> = ComputedSignal<Awaited<T>>;\n```\n\n**References:** [ComputedSignal](#computedsignal)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-computed.ts)\n\n## ComputedSignal\n\nA computed signal is a signal which is calculated from other signals. When the signals change, the computed signal is recalculated, and if the result changed, all tasks which are tracking the signal will be re-run and all components that read the signal will be re-rendered.\n\n```typescript\nexport interface ComputedSignal<T> extends Signal<T>\n```\n\n**Extends:** [Signal](#signal)&lt;T&gt;\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| error | | Error \\\\| undefined | The computation error, if any. Reading it starts a lazy computation if needed. While set, reading `.value` throws the error. |\n| pending | | boolean | Whether the signal is currently loading. Reading it starts a lazy computation if needed. |\n\n| Method | Description |\n| --- | --- |\n| [abort(reason)](#computedsignal-abort) | Abort the current computation and run cleanups if needed. |\n| [clear()](#computedsignal-clear) | Clear the value and recompute. Unlike `invalidate()`, readers see the loading state (reads throw the computation promise) instead of the stale value while the new value computes. |\n| [force()](#computedsignal-force) | |\n| [invalidate()](#computedsignal-invalidate) | Use this to force recalculation. |\n| invalidate(info) | Use this to force recalculation. If you pass `info`, it will be provided to the calculation function. |\n| [promise()](#computedsignal-promise) | A promise that resolves when the value is computed or rejected. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/signal.public.ts)\n\n## ContextId\n\nContextId is a typesafe ID for your context.\n\nContext is a way to pass stores to the child components without prop-drilling.\n\nUse `createContextId()` to create a `ContextId`. A `ContextId` is just a serializable identifier for the context. It is not the context value itself. See `useContextProvider()` and `useContext()` for the values. Qwik needs a serializable ID for the context so that the it can track context providers and consumers in a way that survives resumability.\n\n### Example\n\n```tsx\n// Declare the Context type.\ninterface TodosStore {\n items: string[];\n}\n// Create a Context ID (no data is saved here.)\n// You will use this ID to both create and retrieve the Context.\nexport const TodosContext = createContextId<TodosStore>(\"Todos\");\n\n// Example of providing context to child components.\nexport const App = component$(() => {\n useContextProvider(\n TodosContext,\n useStore<TodosStore>({\n items: [\"Learn Qwik\", \"Build Qwik app\", \"Profit\"],\n }),\n );\n\n return <Items />;\n});\n\n// Example of retrieving the context provided by a parent component.\nexport const Items = component$(() => {\n const todos = useContext(TodosContext);\n return (\n <ul>\n {todos.items.map((item) => (\n <li>{item}</li>\n ))}\n </ul>\n );\n});\n```\n\n```typescript\nexport interface ContextId<STATE>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| \\_\\_brand_context_type\\_\\_ | `readonly` | STATE | Design-time property to store type information for the context. |\n| id | `readonly` | string | A unique ID for the context. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-context.ts)\n\n## CorePlatform\n\nLow-level API for platform abstraction.\n\nDifferent platforms (browser, node, service workers) may have different ways of handling things such as `requestAnimationFrame` and imports. To make Qwik platform-independent Qwik uses the `CorePlatform` API to access the platform API.\n\n`CorePlatform` also is responsible for importing symbols. The import map is different on the client (browser) then on the server. For this reason, the server has a manifest that is used to map symbols to javascript chunks. The manifest is encapsulated in `CorePlatform`, for this reason, the `CorePlatform` can't be global as there may be multiple applications running at server concurrently.\n\nThis is a low-level API and there should not be a need for you to access this.\n\n```typescript\nexport interface CorePlatform\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| chunkForSymbol | | (symbolName: string, chunk: string \\\\| null, parent?: string) => readonly [symbol: string, chunk: string] \\\\| undefined | Retrieve chunk name for the symbol. When the application is running on the server the symbols may be imported from different files (as server build is typically a single javascript chunk.) For this reason, it is necessary to convert the chunks from server format to client (browser) format. This is done by looking up symbols (which are globally unique) in the manifest. (Manifest is the mapping of symbols to the client chunk names.) |\n| importSymbol | | (containerEl: Element \\\\| undefined, url: string \\\\| URL \\\\| undefined \\\\| null, symbol: string) => [ValueOrPromise](#valueorpromise)<unknown> | Retrieve a symbol value from QRL. Qwik needs to lazy load data and closures. For this Qwik uses QRLs that are serializable references of resources that are needed. The QRLs contain all the information necessary to retrieve the reference using `importSymbol`. Why not use `import()`? Because `import()` is relative to the current file, and the current file is always the Qwik framework. So QRLs have additional information that allows them to serialize imports relative to application base rather than the Qwik framework file. |\n| isServer | | boolean | True of running on the server platform. |\n| raf | | (fn: () => any) => Promise<any> | Perform operation on next request-animation-frame. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/platform/types.ts)\n\n## CorrectedToggleEvent\n\nThis corrects the TS definition for ToggleEvent\n\n```typescript\nexport interface CorrectedToggleEvent extends Event\n```\n\n**Extends:** Event\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| newState | `readonly` | 'open' \\\\| 'closed' | |\n| prevState | `readonly` | 'open' \\\\| 'closed' | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## createComputed$\n\nCreate a computed signal which is calculated from the given QRL. A computed signal is a signal which is calculated from other signals. When the signals change, the computed signal is recalculated.\n\nThe QRL must be a function which returns the value of the signal. The function must not have side effects. Every synchronous signal or store read is tracked automatically; reads after the first `await` must use the `track()` provided on the context argument. When the function is async, reading an unresolved `.value` throws the computation promise, and reading a failed `.value` throws the error.\n\n```typescript\ncreateComputed$: <T>(\n qrl: (ctx: ComputeCtx) => ValueOrPromise<T>,\n options?: ComputedOptions<T>,\n) => ComputedReturnType<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | (ctx: ComputeCtx) => [ValueOrPromise](#valueorpromise)<T> | |\n| options | [ComputedOptions](#computedoptions)<T> | _(Optional)_ |\n\n**Returns:**\n\n[ComputedReturnType](#computedreturntype)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/signal.public.ts)\n\n## createContextId\n\nCreate a context ID to be used in your application. The name should be written with no spaces.\n\nContext is a way to pass stores to the child components without prop-drilling.\n\nUse `createContextId()` to create a `ContextId`. A `ContextId` is just a serializable identifier for the context. It is not the context value itself. See `useContextProvider()` and `useContext()` for the values. Qwik needs a serializable ID for the context so that the it can track context providers and consumers in a way that survives resumability.\n\n### Example\n\n```tsx\n// Declare the Context type.\ninterface TodosStore {\n items: string[];\n}\n// Create a Context ID (no data is saved here.)\n// You will use this ID to both create and retrieve the Context.\nexport const TodosContext = createContextId<TodosStore>(\"Todos\");\n\n// Example of providing context to child components.\nexport const App = component$(() => {\n useContextProvider(\n TodosContext,\n useStore<TodosStore>({\n items: [\"Learn Qwik\", \"Build Qwik app\", \"Profit\"],\n }),\n );\n\n return <Items />;\n});\n\n// Example of retrieving the context provided by a parent component.\nexport const Items = component$(() => {\n const todos = useContext(TodosContext);\n return (\n <ul>\n {todos.items.map((item) => (\n <li>{item}</li>\n ))}\n </ul>\n );\n});\n```\n\n```typescript\ncreateContextId: <STATE = unknown>(name: string) => ContextId<STATE>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| name | string | The name of the context. |\n\n**Returns:**\n\n[ContextId](#contextid)&lt;STATE&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-context.ts)\n\n## createSerializer$\n\nCreate a signal that holds a custom serializable value. See [useSerializer$](#useserializer_) for more details.\n\n```typescript\ncreateSerializer$: <T, S>(arg: SerializerArg<T, S>) => T extends Promise<any> ? never : SerializerSignal<T>\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| arg | SerializerArg<T, S> | |\n\n**Returns:**\n\nT extends Promise&lt;any&gt; ? never : SerializerSignal&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/signal.public.ts)\n\n## createSignal\n\nCreates a Signal with the given value. If no value is given, the signal is created with `undefined`.\n\n```typescript\ncreateSignal: {\n <T>(): Signal<T | undefined>;\n <T>(value: T): Signal<T>;\n}\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/signal.public.ts)\n\n## CSSProperties\n\n```typescript\nexport interface CSSProperties extends CSS.Properties<string | number>, CSS.PropertiesHyphen<string | number>\n```\n\n**Extends:** CSS.Properties&lt;string \\| number&gt;, CSS.PropertiesHyphen&lt;string \\| number&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-generated.ts)\n\n## DevJSX\n\n```typescript\nexport interface DevJSX\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| columnNumber | | number | |\n| fileName | | string | |\n| lineNumber | | number | |\n| stack? | | string | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-node.ts)\n\n## DOMAttributes\n\nThe Qwik-specific attributes that DOM elements accept\n\n```typescript\nexport interface DOMAttributes<EL extends Element> extends DOMAttributesBase<EL>, QwikEvents<EL>\n```\n\n**Extends:** DOMAttributesBase&lt;EL&gt;, QwikEvents&lt;EL&gt;\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| class? | | [ClassList](#classlist) \\\\| [Signal](#signal)<[ClassList](#classlist)> \\\\| undefined | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## Each\n\n```typescript\nEach: EachComponent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/control-flow/each.ts)\n\n## Element\n\n```typescript\ntype Element = JSXOutput;\n```\n\n**References:** [JSXOutput](#jsxoutput)\n\n## ElementChildrenAttribute\n\n```typescript\ninterface ElementChildrenAttribute\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| children | | [JSXChildren](#jsxchildren) | |\n\n## ElementType\n\n```typescript\ntype ElementType = string | FunctionComponent<Record<any, any>>;\n```\n\n**References:** [FunctionComponent](#functioncomponent)\n\n## Event\n\n## event$\n\n```typescript\nevent$: <T>(qrl: T) => import(\"./qrl.public\").QRL<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | T | |\n\n**Returns:**\n\nimport(\"./qrl.public\").[QRL](#qrl-type-alias)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/qrl.public.dollar.ts)\n\n## EventHandler\n\nA DOM event handler\n\n```typescript\nexport type EventHandler<EV = Event, EL = Element> = {\n bivarianceHack(event: EV, element: EL): any;\n}[\"bivarianceHack\"];\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## force\n\n> Warning: This API is now obsolete.\n>\n> Use `trigger()` instead\n\n```typescript\nforce(): void;\n```\n\n**Returns:**\n\nvoid\n\n## forceStoreEffects\n\nForce a store to recompute and schedule effects.\n\n```typescript\nforceStoreEffects: (value: StoreTarget, prop: keyof StoreTarget) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| value | StoreTarget | |\n| prop | keyof StoreTarget | |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/impl/store.ts)\n\n## Fragment\n\n```typescript\nFragment: FunctionComponent<{\n children?: any;\n key?: string | number | null;\n}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/jsx-runtime.ts)\n\n## FunctionComponent\n\nAny function taking a props object that returns JSXOutput.\n\nThe `key`, `flags` and `dev` parameters are for internal use.\n\n```typescript\nexport type FunctionComponent<P = unknown> = {\n renderFn(\n props: P,\n key: string | null,\n flags: number,\n dev?: DevJSX,\n ): JSXOutput;\n}[\"renderFn\"];\n```\n\n**References:** [DevJSX](#devjsx), [JSXOutput](#jsxoutput)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-node.ts)\n\n## getClientManifest\n\nReturns the client build manifest, which includes the mappings from symbols to bundles, the bundlegraph etc.\n\n```typescript\ngetClientManifest: () => ServerQwikManifest | undefined;\n```\n\n**Returns:**\n\nServerQwikManifest \\| undefined\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/get-client-manifest.ts)\n\n## getDomContainer\n\n```typescript\nexport declare function getDomContainer(element: Element): IClientContainer;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| element | Element | |\n\n**Returns:**\n\nIClientContainer\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/client/dom-container.ts)\n\n## getLocale\n\nRetrieve the current locale.\n\nIf no current locale and there is no `defaultLocale` the function throws an error.\n\n```typescript\nexport declare function getLocale(defaultLocale?: string): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| defaultLocale | string | _(Optional)_ |\n\n**Returns:**\n\nstring\n\nThe locale.\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-locale.ts)\n\n## getPlatform\n\nRetrieve the `CorePlatform`.\n\nThe `CorePlatform` is also responsible for retrieving the Manifest, that contains mappings from symbols to javascript import chunks. For this reason, `CorePlatform` can't be global, but is specific to the application currently running. On server it is possible that many different applications are running in a single server instance, and for this reason the `CorePlatform` is associated with the application document.\n\n```typescript\ngetPlatform: () => CorePlatform;\n```\n\n**Returns:**\n\n[CorePlatform](#coreplatform)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/platform/platform.ts)\n\n## h\n\nThe legacy transform, used by some JSX transpilers. The optimizer normally replaces this with optimized calls, with the same caveat as `jsx()`.\n\n```typescript\nexport declare function h<\n TYPE extends string | FunctionComponent<PROPS>,\n PROPS extends {} = {},\n>(type: TYPE, props?: PROPS | null, ...children: any[]): JSXNode<TYPE>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| type | TYPE | |\n| props | PROPS \\\\| null | _(Optional)_ |\n| children | any[] | |\n\n**Returns:**\n\n[JSXNode](#jsxnode)&lt;TYPE&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/jsx-runtime.ts)\n\n## Hook\n\n## HTMLElementAttrs\n\n```typescript\nexport interface HTMLElementAttrs extends HTMLAttributesBase, FilterBase<HTMLElement>\n```\n\n**Extends:** HTMLAttributesBase, FilterBase&lt;HTMLElement&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-generated.ts)\n\n## implicit$FirstArg\n\nCreate a `____$(...)` convenience method from `___(...)`.\n\nIt is very common for functions to take a lazy-loadable resource as a first argument. For this reason, the Qwik Optimizer automatically extracts the first argument from any function which ends in `$`.\n\nThis means that `foo$(arg0)` and `foo($(arg0))` are equivalent with respect to Qwik Optimizer. The former is just a shorthand for the latter.\n\nFor example, these function calls are equivalent:\n\n- `component$(() => {...})` is same as `component($(() => {...}))`\n\n```tsx\nexport function myApi(callback: QRL<() => void>): void {\n // ...\n}\n\nexport const myApi$ = implicit$FirstArg(myApi);\n// type of myApi$: (callback: () => void): void\n\n// can be used as:\nmyApi$(() => console.log(\"callback\"));\n\n// will be transpiled to:\n// FILE: <current file>\nmyApi(qrl(\"./chunk-abc.js\", \"callback\"));\n\n// FILE: chunk-abc.js\nexport const callback = () => console.log(\"callback\");\n```\n\n```typescript\nimplicit$FirstArg: <FIRST, REST extends any[], RET>(\n fn: (qrl: QRL<FIRST>, ...rest: REST) => RET,\n ) =>\n (qrl: FIRST, ...rest: REST) =>\n RET;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| fn | (qrl: [QRL](#qrl-type-alias)<FIRST>, ...rest: REST) => RET | A function that should have its first argument automatically `$`. |\n\n**Returns:**\n\n((qrl: FIRST, ...rest: REST) =&gt; RET)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/implicit_dollar.ts)\n\n## inlinedQrl\n\nCreate an inlined QRL. This is mostly useful on the server side for serialization.\n\n```typescript\ninlinedQrl: <T>(\n symbol: T | null,\n symbolName: string,\n lexicalScopeCapture?: Readonly<unknown[]>,\n) => QRL<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| symbol | T \\\\| null | The object/function to register, or `null` to retrieve a previously registered one by hash |\n| symbolName | string | The name of the symbol. |\n| lexicalScopeCapture | Readonly<unknown[]> | _(Optional)_ A set of lexically scoped variables to capture. |\n\n**Returns:**\n\n[QRL](#qrl-type-alias)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/qrl.ts)\n\n## IntrinsicAttributes\n\n```typescript\ninterface IntrinsicAttributes extends QwikIntrinsicAttributes\n```\n\n**Extends:** QwikIntrinsicAttributes\n\n## IntrinsicElements\n\n```typescript\ninterface IntrinsicElements extends LenientQwikElements\n```\n\n**Extends:** LenientQwikElements\n\n## invalidate\n\nUse this to force recalculation.\n\n```typescript\ninvalidate(): void;\n```\n\n**Returns:**\n\nvoid\n\n## isSignal\n\n```typescript\nisSignal: (value: any) => value is Signal<unknown>\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| value | any | |\n\n**Returns:**\n\nvalue is [Signal](#signal)&lt;unknown&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/utils.ts)\n\n## jsx\n\nUsed by the JSX transpilers to create a JSXNode. Note that the optimizer will normally not use this, instead using \\_jsxSplit and \\_jsxSorted directly.\n\nThe optimizer will also replace all `jsx()` calls with the more optimized versions.\n\nThe exception is when the props are not a literal object, which can only happen when the `jsx` call is written directly.\n\n```typescript\njsx: <T extends string | FunctionComponent<any>>(\n type: T,\n props: T extends FunctionComponent<infer PROPS> ? PROPS : Props,\n key?: string | number | null,\n _isStatic?: boolean,\n dev?: JsxDevOpts,\n) => JSXNode<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| type | T | |\n| props | T extends [FunctionComponent](#functioncomponent)<infer PROPS> ? PROPS : Props | |\n| key | string \\\\| number \\\\| null | _(Optional)_ |\n| \\_isStatic | boolean | _(Optional)_ |\n| dev | JsxDevOpts | _(Optional)_ |\n\n**Returns:**\n\n[JSXNode](#jsxnode)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/jsx-runtime.ts)\n\n## JSXChildren\n\n```typescript\nexport type JSXChildren =\n | string\n | number\n | boolean\n | null\n | undefined\n | Function\n | RegExp\n | JSXChildren[]\n | Promise<JSXChildren>\n | Signal<JSXChildren>\n | JSXNode;\n```\n\n**References:** [JSXChildren](#jsxchildren), [Signal](#signal), [JSXNode](#jsxnode)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## jsxDEV\n\nAlias of `jsx` for development purposes.\n\n```typescript\njsxDEV: <T extends string | FunctionComponent<any>>(\n type: T,\n props: T extends FunctionComponent<infer PROPS> ? PROPS : Props,\n key?: string | number | null,\n _isStatic?: boolean,\n dev?: JsxDevOpts,\n) => JSXNode<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| type | T | |\n| props | T extends [FunctionComponent](#functioncomponent)<infer PROPS> ? PROPS : Props | |\n| key | string \\\\| number \\\\| null | _(Optional)_ |\n| \\_isStatic | boolean | _(Optional)_ |\n| dev | JsxDevOpts | _(Optional)_ |\n\n**Returns:**\n\n[JSXNode](#jsxnode)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/jsx-runtime.ts)\n\n## JSXNode\n\nA JSX Node, an internal structure. You probably want to use `JSXOutput` instead.\n\n```typescript\nexport interface JSXNode<T extends string | FunctionComponent | unknown = unknown>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| children | | [JSXChildren](#jsxchildren) \\\\| null | |\n| dev? | | [DevJSX](#devjsx) | _(Optional)_ |\n| key | | string \\\\| null | |\n| props | | T extends [FunctionComponent](#functioncomponent)<infer P> ? P : Record<any, unknown> | |\n| type | | T | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-node.ts)\n\n## JSXOutput\n\nAny valid output for a component\n\n```typescript\nexport type JSXOutput =\n | JSXNode\n | string\n | number\n | boolean\n | null\n | undefined\n | JSXOutput[];\n```\n\n**References:** [JSXNode](#jsxnode), [JSXOutput](#jsxoutput)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-node.ts)\n\n## jsxs\n\nAlias of `jsx` to support JSX syntax.\n\n```typescript\njsxs: <T extends string | FunctionComponent<any>>(\n type: T,\n props: T extends FunctionComponent<infer PROPS> ? PROPS : Props,\n key?: string | number | null,\n _isStatic?: boolean,\n dev?: JsxDevOpts,\n) => JSXNode<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| type | T | |\n| props | T extends [FunctionComponent](#functioncomponent)<infer PROPS> ? PROPS : Props | |\n| key | string \\\\| number \\\\| null | _(Optional)_ |\n| \\_isStatic | boolean | _(Optional)_ |\n| dev | JsxDevOpts | _(Optional)_ |\n\n**Returns:**\n\n[JSXNode](#jsxnode)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/jsx-runtime.ts)\n\n## JSXTagName\n\n```typescript\nexport type JSXTagName =\n | keyof HTMLElementTagNameMap\n | Omit<string, keyof HTMLElementTagNameMap>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## KnownEventNames\n\nThe names of events that Qwik knows about. They are all lowercase, but on the JSX side, they are PascalCase for nicer DX. (`onAuxClick$` vs `onauxclick$`)\n\n```typescript\nexport type KnownEventNames = LiteralUnion<AllEventKeys, string>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeAnimationEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `AnimationEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeAnimationEvent = AnimationEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeClipboardEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `ClipboardEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeClipboardEvent = ClipboardEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeCompositionEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `CompositionEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeCompositionEvent = CompositionEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeDragEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `DragEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeDragEvent = DragEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeFocusEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `FocusEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeFocusEvent = FocusEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeKeyboardEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `KeyboardEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeKeyboardEvent = KeyboardEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeMouseEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `MouseEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeMouseEvent = MouseEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativePointerEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `PointerEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativePointerEvent = PointerEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeTouchEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `TouchEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeTouchEvent = TouchEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeTransitionEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `TransitionEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeTransitionEvent = TransitionEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeUIEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `UIEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeUIEvent = UIEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## NativeWheelEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `WheelEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type NativeWheelEvent = WheelEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## noSerialize\n\nReturned type of the `noSerialize()` function. It will be TYPE or undefined.\n\n```typescript\nexport type NoSerialize<T> =\n | (T & {\n __no_serialize__: true;\n })\n | undefined;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/serdes/verify.ts)\n\n## NoSerialize\n\nReturned type of the `noSerialize()` function. It will be TYPE or undefined.\n\n```typescript\nexport type NoSerialize<T> =\n | (T & {\n __no_serialize__: true;\n })\n | undefined;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/serdes/verify.ts)\n\n## NoSerializeSymbol\n\nIf an object has this property, it will not be serialized. Use this on prototypes to avoid having to call `noSerialize()` on every object.\n\n```typescript\nNoSerializeSymbol: unique symbol\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/serdes/verify.ts)\n\n## OnRenderFn\n\n```typescript\nexport type OnRenderFn<PROPS> = (props: PROPS) => JSXOutput;\n```\n\n**References:** [JSXOutput](#jsxoutput)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/component.public.ts)\n\n## OnVisibleTaskOptions\n\n```typescript\nexport interface OnVisibleTaskOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| strategy? | | [VisibleTaskStrategy](#visibletaskstrategy) | _(Optional)_ The strategy to use to determine when the \"VisibleTask\" should first execute. - `intersection-observer`: the task will first execute when the element is visible in the viewport, under the hood it uses the IntersectionObserver API. - `document-ready`: the task will first execute when the document is ready, under the hood it uses the document `load` event. - `document-idle`: the task will first execute when the document is idle, under the hood it uses the requestIdleCallback API. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-visible-task.ts)\n\n## Pending\n\n```typescript\nPending: Component<PendingProps>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/control-flow/pending.tsx)\n\n## PendingProps\n\n```typescript\nexport type PendingProps = {\n fallback$?: QRL<() => JSXOutput>;\n delay?: number;\n};\n```\n\n**References:** [QRL](#qrl-type-alias), [JSXOutput](#jsxoutput)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/control-flow/pending.tsx)\n\n## PrefetchGraph\n\n> This API is provided as an alpha preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n> Warning: This API is now obsolete.\n>\n> This is no longer needed as the preloading happens automatically in qrl-class. You can remove this component from your app.\n\n```typescript\nPrefetchGraph: (_opts?: {\n base?: string;\n manifestHash?: string;\n manifestURL?: string;\n nonce?: string;\n}) => JSXOutput;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| \\_opts | \\{ base?: string; manifestHash?: string; manifestURL?: string; nonce?: string; } | _(Optional)_ |\n\n**Returns:**\n\n[JSXOutput](#jsxoutput)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/prefetch-service-worker/prefetch.ts)\n\n## PrefetchServiceWorker\n\n> This API is provided as an alpha preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n> Warning: This API is now obsolete.\n>\n> This is no longer needed as the preloading happens automatically in qrl-class.ts. Leave this in your app for a while so it uninstalls existing service workers, but don't use it for new projects.\n\n```typescript\nPrefetchServiceWorker: (opts: {\n base?: string;\n scope?: string;\n path?: string;\n verbose?: boolean;\n fetchBundleGraph?: boolean;\n nonce?: string;\n}) => JSXOutput;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | \\{ base?: string; scope?: string; path?: string; verbose?: boolean; fetchBundleGraph?: boolean; nonce?: string; } | |\n\n**Returns:**\n\n[JSXOutput](#jsxoutput)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/prefetch-service-worker/prefetch.ts)\n\n## promise\n\nA promise that resolves when the value is computed or rejected.\n\n```typescript\npromise(): Promise<void>;\n```\n\n**Returns:**\n\nPromise&lt;void&gt;\n\n## PropFunction\n\nAlias for `QRL<T>`. Of historic relevance only.\n\n```typescript\nexport type PropFunction<T> = QRL<T>;\n```\n\n**References:** [QRL](#qrl-type-alias)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/qrl.public.ts)\n\n## PropsOf\n\nInfers `Props` from the component or tag.\n\n```typescript\nexport type PropsOf<COMP> = COMP extends string\n ? COMP extends keyof QwikIntrinsicElements\n ? QwikIntrinsicElements[COMP]\n : QwikIntrinsicElements[\"span\"]\n : NonNullable<COMP> extends never\n ? never\n : COMP extends FunctionComponent<infer PROPS>\n ? PROPS extends Record<any, infer V>\n ? IsAny<V> extends true\n ? never\n : ObjectProps<PROPS>\n : COMP extends Component<infer OrigProps>\n ? ObjectProps<OrigProps>\n : PROPS\n : never;\n```\n\n**References:** [QwikIntrinsicElements](#qwikintrinsicelements), [FunctionComponent](#functioncomponent), [Component](#component)\n\n```tsx\nconst Desc = component$(\n ({ desc, ...props }: { desc: string } & PropsOf<\"div\">) => {\n return <div {...props}>{desc}</div>;\n },\n);\n\nconst TitleBox = component$(\n ({ title, ...props }: { title: string } & PropsOf<Box>) => {\n return (\n <Box {...props}>\n <h1>{title}</h1>\n </Box>\n );\n },\n);\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/component.public.ts)\n\n## PublicProps\n\nExtends the defined component PROPS, adding the default ones (children and q:slot) and allowing plain functions to QRL arguments.\n\n```typescript\nexport type PublicProps<PROPS> = (PROPS extends Record<any, any>\n ? Omit<PROPS, `${string}$`> & _Only$<PROPS>\n : unknown extends PROPS\n ? {}\n : PROPS) &\n ComponentBaseProps &\n ComponentChildren<PROPS>;\n```\n\n**References:** [ComponentBaseProps](#componentbaseprops)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/component.public.ts)\n\n## qrl\n\nThe `QRL` type represents a lazy-loadable AND serializable resource.\n\nQRL stands for Qwik URL.\n\nUse `QRL` when you want to refer to a lazy-loaded resource. `QRL`s are most often used for code (functions) but can also be used for other resources such as `string`s in the case of styles.\n\n`QRL` is an opaque token that is generated by the Qwik Optimizer. (Do not rely on any properties in `QRL` as it may change between versions.)\n\n\\#\\# Creating `QRL` references\n\nCreating `QRL` is done using `$(...)` function. `$(...)` is a special marker for the Qwik Optimizer that marks that the code should be extracted into a lazy-loaded symbol.\n\n```tsx\nuseOnDocument(\n \"mousemove\",\n $((event) => console.log(\"mousemove\", event)),\n);\n```\n\nIn the above code, the Qwik Optimizer detects `$(...)` and transforms the code as shown below:\n\n```tsx\n// FILE: <current file>\nuseOnDocument(\"mousemove\", qrl(\"./chunk-abc.js\", \"onMousemove\"));\n\n// FILE: chunk-abc.js\nexport const onMousemove = () => console.log(\"mousemove\");\n```\n\nNOTE: `qrl(...)` is a result of Qwik Optimizer transformation. You should never have to invoke this function directly in your application. The `qrl(...)` function should be invoked only after the Qwik Optimizer transformation.\n\n\\#\\# Using `QRL`s\n\nUse `QRL` type in your application when you want to get a lazy-loadable reference to a resource (most likely a function).\n\n```tsx\n// Example of declaring a custom functions which takes callback as QRL.\nexport function useMyFunction(callback: QRL<() => void>) {\n doExtraStuff();\n // The callback passed to `onDocument` requires `QRL`.\n useOnDocument(\"mousemove\", callback);\n}\n```\n\nIn the above example, the way to think about the code is that you are not asking for a callback function but rather a reference to a lazy-loadable callback function. Specifically, the function loading should be delayed until it is actually needed. In the above example, the function would not load until after a `mousemove` event on `document` fires.\n\n\\#\\# Resolving `QRL` references\n\nAt times it may be necessary to resolve a `QRL` reference to the actual value. This can be performed using `QRL.resolve(..)` function.\n\n```tsx\n// Assume you have QRL reference to a greet function\nconst lazyGreet: QRL<() => void> = $(() => console.log(\"Hello World!\"));\n\n// Use `qrlImport` to load / resolve the reference.\nconst greet: () => void = await lazyGreet.resolve();\n\n// Invoke it\ngreet();\n```\n\nNOTE: `element` is needed because `QRL`s are relative and need a base location to resolve against. The base location is encoded in the HTML in the form of `<div q:base=\"/url\">`.\n\n\\#\\# `QRL.resolved`\n\nOnce `QRL.resolve()` returns, the value is stored under `QRL.resolved`. This allows the value to be used without having to await `QRL.resolve()` again.\n\n\\#\\# Question: Why not just use `import()`?\n\nAt first glance, `QRL` serves the same purpose as `import()`. However, there are three subtle differences that need to be taken into account.\n\n1. `QRL`s must be serializable into HTML. 2. `QRL`s must be resolved by framework relative to `q:base`. 3. `QRL`s must be able to capture lexically scoped variables. 4. `QRL`s encapsulate the difference between running with and without Qwik Optimizer. 5. `QRL`s allow expressing lazy-loaded boundaries without thinking about chunk and symbol names.\n\nLet's assume that you intend to write code such as this:\n\n```tsx\nreturn <button onClick={() => (await import('./chunk-abc.js')).onClick}>\n```\n\nThe above code needs to be serialized into DOM such as:\n\n```\n<div q:base=\"/build/\">\n <button q-e:click=\"./chunk-abc.js#onClick\">...</button>\n</div>\n```\n\n1. Notice there is no easy way to extract chunk (`./chunk-abc.js`) and symbol (`onClick`) into HTML. 2. Notice that even if you could extract it, the `import('./chunk-abc.js')` would become relative to where the `import()` file is declared. Because it is our framework doing the load, the `./chunk-abc.js` would become relative to the framework file. This is not correct, as it should be relative to the original file generated by the bundler. 3. Next, the framework needs to resolve the `./chunk-abc.js` and needs a base location that is encoded in the HTML. 4. The QRL needs to be able to capture lexically scoped variables. (`import()` only allows loading top-level symbols which don't capture variables.) 5. As a developer, you don't want to think about `import` and naming the chunks and symbols. You just want to say: \"this should be lazy.\"\n\nThese are the main reasons why Qwik introduces its own concept of `QRL`.\n\n```typescript\nexport type QRL<TYPE = unknown> = {\n __qwik_serializable__?: any;\n __brand__QRL__?: TYPE;\n resolve(): Promise<TYPE>;\n resolved: undefined | TYPE;\n getCaptured(): unknown[] | null;\n getSymbol(): string;\n getHash(): string;\n dev?: QRLDev | null;\n} & BivariantQrlFn<QrlArgs<TYPE>, QrlReturn<TYPE>>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/qrl.ts)\n\n## QRL\n\nThe `QRL` type represents a lazy-loadable AND serializable resource.\n\nQRL stands for Qwik URL.\n\nUse `QRL` when you want to refer to a lazy-loaded resource. `QRL`s are most often used for code (functions) but can also be used for other resources such as `string`s in the case of styles.\n\n`QRL` is an opaque token that is generated by the Qwik Optimizer. (Do not rely on any properties in `QRL` as it may change between versions.)\n\n\\#\\# Creating `QRL` references\n\nCreating `QRL` is done using `$(...)` function. `$(...)` is a special marker for the Qwik Optimizer that marks that the code should be extracted into a lazy-loaded symbol.\n\n```tsx\nuseOnDocument(\n \"mousemove\",\n $((event) => console.log(\"mousemove\", event)),\n);\n```\n\nIn the above code, the Qwik Optimizer detects `$(...)` and transforms the code as shown below:\n\n```tsx\n// FILE: <current file>\nuseOnDocument(\"mousemove\", qrl(\"./chunk-abc.js\", \"onMousemove\"));\n\n// FILE: chunk-abc.js\nexport const onMousemove = () => console.log(\"mousemove\");\n```\n\nNOTE: `qrl(...)` is a result of Qwik Optimizer transformation. You should never have to invoke this function directly in your application. The `qrl(...)` function should be invoked only after the Qwik Optimizer transformation.\n\n\\#\\# Using `QRL`s\n\nUse `QRL` type in your application when you want to get a lazy-loadable reference to a resource (most likely a function).\n\n```tsx\n// Example of declaring a custom functions which takes callback as QRL.\nexport function useMyFunction(callback: QRL<() => void>) {\n doExtraStuff();\n // The callback passed to `onDocument` requires `QRL`.\n useOnDocument(\"mousemove\", callback);\n}\n```\n\nIn the above example, the way to think about the code is that you are not asking for a callback function but rather a reference to a lazy-loadable callback function. Specifically, the function loading should be delayed until it is actually needed. In the above example, the function would not load until after a `mousemove` event on `document` fires.\n\n\\#\\# Resolving `QRL` references\n\nAt times it may be necessary to resolve a `QRL` reference to the actual value. This can be performed using `QRL.resolve(..)` function.\n\n```tsx\n// Assume you have QRL reference to a greet function\nconst lazyGreet: QRL<() => void> = $(() => console.log(\"Hello World!\"));\n\n// Use `qrlImport` to load / resolve the reference.\nconst greet: () => void = await lazyGreet.resolve();\n\n// Invoke it\ngreet();\n```\n\nNOTE: `element` is needed because `QRL`s are relative and need a base location to resolve against. The base location is encoded in the HTML in the form of `<div q:base=\"/url\">`.\n\n\\#\\# `QRL.resolved`\n\nOnce `QRL.resolve()` returns, the value is stored under `QRL.resolved`. This allows the value to be used without having to await `QRL.resolve()` again.\n\n\\#\\# Question: Why not just use `import()`?\n\nAt first glance, `QRL` serves the same purpose as `import()`. However, there are three subtle differences that need to be taken into account.\n\n1. `QRL`s must be serializable into HTML. 2. `QRL`s must be resolved by framework relative to `q:base`. 3. `QRL`s must be able to capture lexically scoped variables. 4. `QRL`s encapsulate the difference between running with and without Qwik Optimizer. 5. `QRL`s allow expressing lazy-loaded boundaries without thinking about chunk and symbol names.\n\nLet's assume that you intend to write code such as this:\n\n```tsx\nreturn <button onClick={() => (await import('./chunk-abc.js')).onClick}>\n```\n\nThe above code needs to be serialized into DOM such as:\n\n```\n<div q:base=\"/build/\">\n <button q-e:click=\"./chunk-abc.js#onClick\">...</button>\n</div>\n```\n\n1. Notice there is no easy way to extract chunk (`./chunk-abc.js`) and symbol (`onClick`) into HTML. 2. Notice that even if you could extract it, the `import('./chunk-abc.js')` would become relative to where the `import()` file is declared. Because it is our framework doing the load, the `./chunk-abc.js` would become relative to the framework file. This is not correct, as it should be relative to the original file generated by the bundler. 3. Next, the framework needs to resolve the `./chunk-abc.js` and needs a base location that is encoded in the HTML. 4. The QRL needs to be able to capture lexically scoped variables. (`import()` only allows loading top-level symbols which don't capture variables.) 5. As a developer, you don't want to think about `import` and naming the chunks and symbols. You just want to say: \"this should be lazy.\"\n\nThese are the main reasons why Qwik introduces its own concept of `QRL`.\n\n```typescript\nexport type QRL<TYPE = unknown> = {\n __qwik_serializable__?: any;\n __brand__QRL__?: TYPE;\n resolve(): Promise<TYPE>;\n resolved: undefined | TYPE;\n getCaptured(): unknown[] | null;\n getSymbol(): string;\n getHash(): string;\n dev?: QRLDev | null;\n} & BivariantQrlFn<QrlArgs<TYPE>, QrlReturn<TYPE>>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/qrl.public.ts)\n\n## QRLEventHandlerMulti\n\nAn event handler for Qwik events, can be a handler QRL or an array of handler QRLs.\n\n```typescript\nexport type QRLEventHandlerMulti<EV extends Event, EL> =\n | QRL<EventHandler<EV, EL>>\n | undefined\n | null\n | QRLEventHandlerMulti<EV, EL>[];\n```\n\n**References:** [QRL](#qrl-type-alias), [EventHandler](#eventhandler), [QRLEventHandlerMulti](#qrleventhandlermulti)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## QwikAnimationEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `AnimationEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikAnimationEvent<T = Element> = NativeAnimationEvent;\n```\n\n**References:** [NativeAnimationEvent](#nativeanimationevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikAttributes\n\nThe Qwik DOM attributes without plain handlers, for use as function parameters\n\n```typescript\nexport interface QwikAttributes<EL extends Element> extends DOMAttributesBase<EL>, QwikEvents<EL, false>\n```\n\n**Extends:** DOMAttributesBase&lt;EL&gt;, QwikEvents&lt;EL, false&gt;\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| class? | | [ClassList](#classlist) \\\\| undefined | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-attributes.ts)\n\n## QwikChangeEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `Event` and use the second argument to the handler function for the current event target. Also note that in Qwik, onInput$ with the InputEvent is the event that behaves like onChange in React.\n\n```typescript\nexport type QwikChangeEvent<T = Element> = Event;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikClipboardEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `ClipboardEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikClipboardEvent<T = Element> = NativeClipboardEvent;\n```\n\n**References:** [NativeClipboardEvent](#nativeclipboardevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikCompositionEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `CompositionEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikCompositionEvent<T = Element> = NativeCompositionEvent;\n```\n\n**References:** [NativeCompositionEvent](#nativecompositionevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikDOMAttributes\n\n```typescript\nexport interface QwikDOMAttributes extends DOMAttributes<Element>\n```\n\n**Extends:** [DOMAttributes](#domattributes)&lt;Element&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik.ts)\n\n## QwikDragEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `DragEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikDragEvent<T = Element> = NativeDragEvent;\n```\n\n**References:** [NativeDragEvent](#nativedragevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikFocusEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `FocusEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikFocusEvent<T = Element> = NativeFocusEvent;\n```\n\n**References:** [NativeFocusEvent](#nativefocusevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikHTMLElements\n\nThe DOM props without plain handlers, for use inside functions\n\n```typescript\nexport type QwikHTMLElements = {\n [tag in keyof HTMLElementTagNameMap]: Augmented<\n HTMLElementTagNameMap[tag],\n SpecialAttrs[tag]\n > &\n HTMLElementAttrs &\n QwikAttributes<HTMLElementTagNameMap[tag]>;\n};\n```\n\n**References:** [HTMLElementAttrs](#htmlelementattrs), [QwikAttributes](#qwikattributes)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-generated.ts)\n\n## QwikIdleEvent\n\nEmitted by qwik-loader on document when the document first becomes idle\n\n```typescript\nexport type QwikIdleEvent = CustomEvent<{}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikInitEvent\n\nEmitted by qwik-loader on document when the document first becomes interactive\n\n```typescript\nexport type QwikInitEvent = CustomEvent<{}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikIntrinsicElements\n\nThe interface holds available attributes of both native DOM elements and custom Qwik elements. An example showing how to define a customizable wrapper component:\n\n```tsx\nimport { component$, Slot, type QwikIntrinsicElements } from \"@qwik.dev/core\";\n\ntype WrapperProps = {\n attributes?: QwikIntrinsicElements[\"div\"];\n};\n\nexport default component$<WrapperProps>(({ attributes }) => {\n return (\n <div {...attributes} class=\"p-2\">\n <Slot />\n </div>\n );\n});\n```\n\nNote: It is shorter to use `PropsOf<'div'>`\n\n```typescript\nexport interface QwikIntrinsicElements extends QwikHTMLElements, QwikSVGElements\n```\n\n**Extends:** [QwikHTMLElements](#qwikhtmlelements), [QwikSVGElements](#qwiksvgelements)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-elements.ts)\n\n## QwikInvalidEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `Event` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikInvalidEvent<T = Element> = Event;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikJSX\n\n```typescript\nexport declare namespace QwikJSX\n```\n\n| Interface | Description |\n| --- | --- |\n| [ElementChildrenAttribute](#qwikjsx-elementchildrenattribute) | |\n| [IntrinsicAttributes](#qwikjsx-intrinsicattributes) | |\n| [IntrinsicElements](#qwikjsx-intrinsicelements) | |\n\n| Type Alias | Description |\n| --- | --- |\n| [Element](#qwikjsx-element) | |\n| [ElementType](#qwikjsx-elementtype) | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik.ts)\n\n## QwikKeyboardEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `KeyboardEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikKeyboardEvent<T = Element> = NativeKeyboardEvent;\n```\n\n**References:** [NativeKeyboardEvent](#nativekeyboardevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikMouseEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `MouseEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikMouseEvent<T = Element, E = NativeMouseEvent> = E;\n```\n\n**References:** [NativeMouseEvent](#nativemouseevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikPointerEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `PointerEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikPointerEvent<T = Element> = NativePointerEvent;\n```\n\n**References:** [NativePointerEvent](#nativepointerevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikResumeEvent\n\nEmitted by qwik-core on the container element when it resumes from a paused state. You cannot put a Qwik event handler on the container so you must listen on the document instead.\n\n```typescript\nexport type QwikResumeEvent = CustomEvent<{}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikSubmitEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `SubmitEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikSubmitEvent<T = Element> = SubmitEvent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikSVGElements\n\nThe SVG props without plain handlers, for use inside functions\n\n```typescript\nexport type QwikSVGElements = {\n [K in keyof Omit<\n SVGElementTagNameMap,\n keyof HTMLElementTagNameMap\n >]: SVGProps<SVGElementTagNameMap[K]>;\n};\n```\n\n**References:** [SVGProps](#svgprops)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-generated.ts)\n\n## QwikSymbolEvent\n\nEmitted by qwik-loader on document when a module was lazily loaded\n\n```typescript\nexport type QwikSymbolEvent = CustomEvent<{\n symbol: string;\n element: Element;\n reqTime: number;\n qBase?: string;\n href?: string;\n}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikTouchEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `TouchEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikTouchEvent<T = Element> = NativeTouchEvent;\n```\n\n**References:** [NativeTouchEvent](#nativetouchevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikTransitionEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `TransitionEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikTransitionEvent<T = Element> = NativeTransitionEvent;\n```\n\n**References:** [NativeTransitionEvent](#nativetransitionevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikUIEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `UIEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikUIEvent<T = Element> = NativeUIEvent;\n```\n\n**References:** [NativeUIEvent](#nativeuievent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikViewTransitionEvent\n\nEmitted by qwik-core on document when the a view transition start\n\n```typescript\nexport type QwikViewTransitionEvent = CustomEvent<ViewTransition>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikVisibleEvent\n\nHandled by qwik-loader when an element becomes visible. Used by `useVisibleTask$`. Does not bubble.\n\n```typescript\nexport type QwikVisibleEvent = CustomEvent<IntersectionObserverEntry>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## QwikWheelEvent\n\n> Warning: This API is now obsolete.\n>\n> Use `WheelEvent` and use the second argument to the handler function for the current event target\n\n```typescript\nexport type QwikWheelEvent<T = Element> = NativeWheelEvent;\n```\n\n**References:** [NativeWheelEvent](#nativewheelevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-qwik-events.ts)\n\n## ReadonlySignal\n\n> Warning: This API is now obsolete.\n>\n> Use `Readonly<Signal<T>>` instead.\n\n```typescript\nexport interface ReadonlySignal<T = unknown>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| value | `readonly` | T | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/signal.public.ts)\n\n## render\n\nRender JSX.\n\nUse this method to render JSX. This function does reconciling which means it always tries to reuse what is already in the DOM (rather then destroy and recreate content.) It returns a cleanup function you could use for cleaning up subscriptions.\n\n```typescript\nrender: (\n parent: Element | Document,\n jsxNode: JSXOutput | FunctionComponent<any>,\n opts?: RenderOptions,\n) => Promise<RenderResult>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| parent | Element \\\\| Document | Element which will act as a parent to `jsxNode`. When possible the rendering will try to reuse existing nodes. |\n| jsxNode | [JSXOutput](#jsxoutput) \\\\| [FunctionComponent](#functioncomponent)<any> | JSX to render |\n| opts | [RenderOptions](#renderoptions) | _(Optional)_ |\n\n**Returns:**\n\nPromise&lt;[RenderResult](#renderresult)&gt;\n\nAn object containing a cleanup function.\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/client/dom-render.ts)\n\n## Render\n\n## RenderOnce\n\n```typescript\nRenderOnce: FunctionComponent<{\n children?: unknown;\n key?: string | number | null | undefined;\n}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/jsx-runtime.ts)\n\n## RenderOptions\n\n```typescript\nexport interface RenderOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| serverData? | | Record<string, any> | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/client/types.ts)\n\n## RenderResult\n\n```typescript\nexport interface RenderResult\n```\n\n| Method | Description |\n| --- | --- |\n| [cleanup()](#renderresult-cleanup) | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/client/types.ts)\n\n## RenderSSROptions\n\n```typescript\nexport interface RenderSSROptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| base? | | string | _(Optional)_ |\n| containerAttributes | | Record<string, string> | |\n| containerTagName | | string | |\n| manifestHash | | string | |\n| serverData? | | Record<string, any> | _(Optional)_ |\n| stream | | StreamWriter | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/ssr/ssr-types.ts)\n\n## Resource\n\n> Warning: This API is now obsolete.\n>\n> Use `useComputed$` instead.\n\n```tsx\nconst Cmp = component$(() => {\n const city = useSignal(\"\");\n\n const weather = useComputed$(async ({ track, cleanup, abortSignal }) => {\n const cityName = track(city);\n const res = await fetch(`http://weatherdata.com?city=${cityName}`, {\n signal: abortSignal,\n });\n const temp = (await res.json()) as { temp: number };\n return temp;\n });\n\n return (\n <div>\n <input name=\"city\" bind:value={city} />\n <div>Temperature: {weather.value.temp}</div>\n </div>\n );\n});\n```\n\n```typescript\nResource: <T>(input: ResourceProps<T>) => JSXOutput;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| \\{ value, onResolved, onPending, onRejected, } | (not declared) | |\n| input | [ResourceProps](#resourceprops)<T> | |\n\n**Returns:**\n\n[JSXOutput](#jsxoutput)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## ResourceCtx\n\n```typescript\nexport interface ResourceCtx<T = unknown> extends ComputeCtx<T>\n```\n\n**Extends:** ComputeCtx&lt;T&gt;\n\n| Method | Description |\n| --- | --- |\n| [cache(policyOrMilliseconds)](#resourcectx-cache) | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## ResourceFn\n\n```typescript\nexport type ResourceFn<T> = (ctx: ResourceCtx) => ValueOrPromise<T>;\n```\n\n**References:** [ResourceCtx](#resourcectx), [ValueOrPromise](#valueorpromise)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## ResourceOptions\n\nOptions to pass to `useResource$()`\n\n```typescript\nexport interface ResourceOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| timeout? | | number | _(Optional)_ Timeout in milliseconds. If the resource takes more than the specified millisecond, it will timeout. Resulting on a rejected resource. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## ResourcePending\n\n```typescript\nexport type ResourcePending<T> = ResourceReturn<T>;\n```\n\n**References:** [ResourceReturn](#resourcereturn)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## ResourceProps\n\n```typescript\nexport interface ResourceProps<T>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| onPending? | | () => [JSXOutput](#jsxoutput) \\\\| Promise<[JSXOutput](#jsxoutput)> | _(Optional)_ |\n| onRejected? | | (reason: Error) => [JSXOutput](#jsxoutput) \\\\| Promise<[JSXOutput](#jsxoutput)> | _(Optional)_ |\n| onResolved | | (value: T) => [JSXOutput](#jsxoutput) \\\\| Promise<[JSXOutput](#jsxoutput)> | |\n| value | `readonly` | [ResourceReturn](#resourcereturn)<T> \\\\| [Signal](#signal)<Promise<T> \\\\| T> \\\\| Promise<T> | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## ResourceRejected\n\n```typescript\nexport type ResourceRejected<T> = ResourceReturn<T>;\n```\n\n**References:** [ResourceReturn](#resourcereturn)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## ResourceResolved\n\n```typescript\nexport type ResourceResolved<T> = ResourceReturn<T>;\n```\n\n**References:** [ResourceReturn](#resourcereturn)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## ResourceReturn\n\n```typescript\nexport type ResourceReturn<T> = {\n readonly value: Promise<T>;\n readonly loading: boolean;\n};\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource.ts)\n\n## Reveal\n\n```typescript\nReveal: typeof revealCmp;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/control-flow/reveal.tsx)\n\n## RevealOrder\n\n```typescript\nexport type RevealOrder = \"parallel\" | \"sequential\" | \"reverse\" | \"together\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/utils/reveal.ts)\n\n## RevealProps\n\n```typescript\nexport type RevealProps = {\n order?: RevealOrder;\n collapsed?: boolean;\n};\n```\n\n**References:** [RevealOrder](#revealorder)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/control-flow/reveal.tsx)\n\n## SerializationStrategy\n\nSerialization strategy for computed and async signals. This determines whether to serialize their value during SSR.\n\n- `never`: The value is never serialized. When the component is resumed, the value will be recalculated when it is first read. - `always`: The value is always serialized. This is the default.\n\n\\*\\*IMPORTANT\\*\\*: When you use `never`, your serialized HTML is smaller, but the recalculation will trigger subscriptions, meaning that other signals using this signal will recalculate, even if this signal didn't change.\n\nThis is normally not a problem, but for async signals it may mean fetching something again.\n\n```typescript\nexport type SerializationStrategy = \"never\" | \"always\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/types.ts)\n\n## SerializerSymbol\n\nIf an object has this property as a function, it will be called with the object and should return a serializable value.\n\nThis can be used to clean up, integrate with other libraries, etc.\n\nThe type your object should conform to is:\n\n```ts\n{\n [SerializerSymbol]: (this: YourType, toSerialize: YourType) => YourSerializableType;\n}\n```\n\n```typescript\nSerializerSymbol: unique symbol\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/serdes/verify.ts)\n\n## setPlatform\n\nSets the `CorePlatform`.\n\nThis is useful to override the platform in tests to change the behavior of, `requestAnimationFrame`, and import resolution.\n\n```typescript\nsetPlatform: (plt: CorePlatform) => CorePlatform;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| plt | [CorePlatform](#coreplatform) | |\n\n**Returns:**\n\n[CorePlatform](#coreplatform)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/platform/platform.ts)\n\n## Show\n\n```typescript\nShow: ShowComponent;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/control-flow/show.ts)\n\n## ShowComponent\n\n```typescript\nexport type ShowComponent = <\n WHEN = unknown,\n THEN extends JSXOutput = JSXOutput,\n ELSE extends JSXOutput = JSXOutput,\n>(\n props: PublicProps<ShowProps<WHEN, THEN, ELSE>>,\n key: string | null,\n flags: number,\n dev?: DevJSX,\n) => JSXOutput;\n```\n\n**References:** [JSXOutput](#jsxoutput), [PublicProps](#publicprops), [ShowProps](#showprops), [DevJSX](#devjsx)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/control-flow/show.ts)\n\n## ShowProps\n\n```typescript\nexport interface ShowProps<WHEN = unknown, THEN extends JSXOutput = JSXOutput, ELSE extends JSXOutput = JSXOutput>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| else$? | | [QRL](#qrl-type-alias)<(when: WHEN) => ELSE> | _(Optional)_ |\n| then$ | | [QRL](#qrl-type-alias)<(when: WHEN) => THEN> | |\n| when$ | | [QRL](#qrl-type-alias)<() => WHEN> | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/control-flow/show.ts)\n\n## Signal\n\nA signal is a reactive value which can be read and written. When the signal is written, all tasks which are tracking the signal will be re-run and all components that read the signal will be re-rendered.\n\nFurthermore, when a signal value is passed as a prop to a component, the optimizer will automatically forward the signal. This means that `return <div title={signal.value}>hi</div>` will update the `title` attribute when the signal changes without having to re-render the component.\n\n```typescript\nexport interface Signal<T = any>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| untrackedValue | | T | Reading from this does not subscribe to updates; writing to this does not trigger updates. |\n| value | | T | Reading from this subscribes to updates; writing to this triggers updates. |\n\n| Method | Description |\n| --- | --- |\n| [trigger()](#signal-trigger) | Use this to trigger running subscribers, for example when the value mutated but remained the same object. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/signal.public.ts)\n\n## SkipRender\n\n```typescript\nSkipRender: JSXNode;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## Slot\n\nAllows to project the children of the current component. `<Slot/>` can only be used within the context of a component defined with `component$`.\n\n```typescript\nSlot: FunctionComponent<{\n name?: string;\n children?: JSXChildren;\n}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/slot.public.ts)\n\n## SnapshotListener\n\n```typescript\nexport interface SnapshotListener\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| el | | Element | |\n| key | | string | |\n| qrl | | [QRL](#qrl-type-alias)<any> | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/ssr/ssr-types.ts)\n\n## SnapshotMeta\n\n```typescript\nexport type SnapshotMeta = Record<string, SnapshotMetaValue>;\n```\n\n**References:** [SnapshotMetaValue](#snapshotmetavalue)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/ssr/ssr-types.ts)\n\n## SnapshotMetaValue\n\n```typescript\nexport interface SnapshotMetaValue\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| c? | | string | _(Optional)_ |\n| h? | | string | _(Optional)_ |\n| s? | | string | _(Optional)_ |\n| w? | | string | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/ssr/ssr-types.ts)\n\n## SnapshotResult\n\n```typescript\nexport interface SnapshotResult\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| funcs | | string[] | |\n| mode | | 'render' \\\\| 'listeners' \\\\| 'static' | |\n| objs? | | any[] | _(Optional)_ |\n| qrls | | [QRL](#qrl-type-alias)[] | |\n| resources | | ResourceReturnInternal<any>[] | |\n| state? | | [SnapshotState](#snapshotstate) | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/ssr/ssr-types.ts)\n\n## SnapshotState\n\n> Warning: This API is now obsolete.\n>\n> not longer used in v2\n\n```typescript\nexport interface SnapshotState\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| ctx | | [SnapshotMeta](#snapshotmeta) | |\n| objs | | any[] | |\n| refs | | Record<string, string> | |\n| subs | | any[] | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/ssr/ssr-types.ts)\n\n## SSRComment\n\n```typescript\nSSRComment: FunctionComponent<{\n data: string;\n}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## SSRHintProps\n\n```typescript\nexport type SSRHintProps = {\n dynamic?: boolean;\n};\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## SSRRaw\n\n```typescript\nSSRRaw: FunctionComponent<{\n data: string;\n}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## SSRStream\n\n```typescript\nSSRStream: FunctionComponent<SSRStreamProps>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## SSRStreamBlock\n\n```typescript\nSSRStreamBlock: FunctionComponent<{\n children?: JSXOutput;\n}>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## SSRStreamChildren\n\n```typescript\nexport type SSRStreamChildren =\n | AsyncGenerator<JSXChildren, void, any>\n | ((stream: SSRStreamWriter) => Promise<void>)\n | (() => AsyncGenerator<JSXChildren, void, any>);\n```\n\n**References:** [JSXChildren](#jsxchildren), [SSRStreamWriter](#ssrstreamwriter)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## SSRStreamProps\n\n```typescript\nexport type SSRStreamProps = {\n children: SSRStreamChildren;\n};\n```\n\n**References:** [SSRStreamChildren](#ssrstreamchildren)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## SSRStreamWriter\n\n```typescript\nexport interface SSRStreamWriter\n```\n\n| Method | Description |\n| --- | --- |\n| [write(chunk)](#ssrstreamwriter-write) | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/utils.public.ts)\n\n## SVGAttributes\n\nThe TS types don't include the SVG attributes so we have to define them ourselves\n\nNOTE: These props are probably not complete\n\n```typescript\nexport interface SVGAttributes<T extends Element = Element> extends AriaAttributes\n```\n\n**Extends:** AriaAttributes\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| \"accent-height\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"alignment-baseline\"? | | 'auto' \\\\| 'baseline' \\\\| 'before-edge' \\\\| 'text-before-edge' \\\\| 'middle' \\\\| 'central' \\\\| 'after-edge' \\\\| 'text-after-edge' \\\\| 'ideographic' \\\\| 'alphabetic' \\\\| 'hanging' \\\\| 'mathematical' \\\\| 'inherit' \\\\| undefined | _(Optional)_ |\n| \"arabic-form\"? | | 'initial' \\\\| 'medial' \\\\| 'terminal' \\\\| 'isolated' \\\\| undefined | _(Optional)_ |\n| \"baseline-shift\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"cap-height\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"clip-path\"? | | string \\\\| undefined | _(Optional)_ |\n| \"clip-rule\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"color-interpolation-filters\"? | | 'auto' \\\\| 's-rGB' \\\\| 'linear-rGB' \\\\| 'inherit' \\\\| undefined | _(Optional)_ |\n| \"color-interpolation\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"color-profile\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"color-rendering\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"dominant-baseline\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"edge-mode\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"enable-background\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"fill-opacity\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"fill-rule\"? | | 'nonzero' \\\\| 'evenodd' \\\\| 'inherit' \\\\| undefined | _(Optional)_ |\n| \"flood-color\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"flood-opacity\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"font-family\"? | | string \\\\| undefined | _(Optional)_ |\n| \"font-size-adjust\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"font-size\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"font-stretch\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"font-style\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"font-variant\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"font-weight\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"glyph-name\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"glyph-orientation-horizontal\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"glyph-orientation-vertical\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"horiz-adv-x\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"horiz-origin-x\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"image-rendering\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"letter-spacing\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"lighting-color\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"marker-end\"? | | string \\\\| undefined | _(Optional)_ |\n| \"marker-mid\"? | | string \\\\| undefined | _(Optional)_ |\n| \"marker-start\"? | | string \\\\| undefined | _(Optional)_ |\n| \"overline-position\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"overline-thickness\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"paint-order\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"pointer-events\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"rendering-intent\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"shape-rendering\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"stop-color\"? | | string \\\\| undefined | _(Optional)_ |\n| \"stop-opacity\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"strikethrough-position\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"strikethrough-thickness\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"stroke-dasharray\"? | | string \\\\| number \\\\| undefined | _(Optional)_ |\n| \"stroke-dashoffset\"? | | string \\\\| number \\\\| undefined | _(Optional)_ |\n| \"stroke-linecap\"? | | 'butt' \\\\| 'round' \\\\| 'square' \\\\| 'inherit' \\\\| undefined | _(Optional)_ |\n| \"stroke-linejoin\"? | | 'miter' \\\\| 'round' \\\\| 'bevel' \\\\| 'inherit' \\\\| undefined | _(Optional)_ |\n| \"stroke-miterlimit\"? | | string \\\\| undefined | _(Optional)_ |\n| \"stroke-opacity\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"stroke-width\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"text-anchor\"? | | string \\\\| undefined | _(Optional)_ |\n| \"text-decoration\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"text-rendering\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"underline-position\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"underline-thickness\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"unicode-bidi\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"unicode-range\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"units-per-em\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"v-alphabetic\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"v-hanging\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"v-ideographic\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"v-mathematical\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"vector-effect\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"vert-adv-y\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"vert-origin-x\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"vert-origin-y\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"word-spacing\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"writing-mode\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| \"x-channel-selector\"? | | string \\\\| undefined | _(Optional)_ |\n| \"x-height\"? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| [\"xlink:actuate\"?](#svgattributes-_xlink_actuate_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xlink:arcrole\"?](#svgattributes-_xlink_arcrole_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xlink:href\"?](#svgattributes-_xlink_href_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xlink:role\"?](#svgattributes-_xlink_role_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xlink:show\"?](#svgattributes-_xlink_show_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xlink:title\"?](#svgattributes-_xlink_title_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xlink:type\"?](#svgattributes-_xlink_type_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xml:base\"?](#svgattributes-_xml_base_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xml:lang\"?](#svgattributes-_xml_lang_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xml:space\"?](#svgattributes-_xml_space_) | | string \\\\| undefined | _(Optional)_ |\n| [\"xmlns:xlink\"?](#svgattributes-_xmlns_xlink_) | | string \\\\| undefined | _(Optional)_ |\n| accumulate? | | 'none' \\\\| 'sum' \\\\| undefined | _(Optional)_ |\n| additive? | | 'replace' \\\\| 'sum' \\\\| undefined | _(Optional)_ |\n| allowReorder? | | 'no' \\\\| 'yes' \\\\| undefined | _(Optional)_ |\n| alphabetic? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| amplitude? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| ascent? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| attributeName? | | string \\\\| undefined | _(Optional)_ |\n| attributeType? | | string \\\\| undefined | _(Optional)_ |\n| autoReverse? | | Booleanish \\\\| undefined | _(Optional)_ |\n| azimuth? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| baseFrequency? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| baseProfile? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| bbox? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| begin? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| bias? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| by? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| calcMode? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| clip? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| clipPathUnits? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| color? | | string \\\\| undefined | _(Optional)_ |\n| contentScriptType? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| contentStyleType? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| crossOrigin? | | HTMLCrossOriginAttribute | _(Optional)_ |\n| cursor? | | number \\\\| string | _(Optional)_ |\n| cx? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| cy? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| d? | | string \\\\| undefined | _(Optional)_ |\n| decelerate? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| descent? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| diffuseConstant? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| direction? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| display? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| divisor? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| dur? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| dx? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| dy? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| elevation? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| end? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| exponent? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| externalResourcesRequired? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| fill? | | string \\\\| undefined | _(Optional)_ |\n| filter? | | string \\\\| undefined | _(Optional)_ |\n| filterRes? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| filterUnits? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| focusable? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| format? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| fr? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| from? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| fx? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| fy? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| g1? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| g2? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| glyphRef? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| gradientTransform? | | string \\\\| undefined | _(Optional)_ |\n| gradientUnits? | | string \\\\| undefined | _(Optional)_ |\n| hanging? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| height? | | Size \\\\| undefined | _(Optional)_ |\n| href? | | string \\\\| undefined | _(Optional)_ |\n| id? | | string \\\\| undefined | _(Optional)_ |\n| ideographic? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| in? | | string \\\\| undefined | _(Optional)_ |\n| in2? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| intercept? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| k? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| k1? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| k2? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| k3? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| k4? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| kernelMatrix? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| kernelUnitLength? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| kerning? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| keyPoints? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| keySplines? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| keyTimes? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| lang? | | string \\\\| undefined | _(Optional)_ |\n| lengthAdjust? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| limitingConeAngle? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| local? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| markerHeight? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| markerUnits? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| markerWidth? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| mask? | | string \\\\| undefined | _(Optional)_ |\n| maskContentUnits? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| maskUnits? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| mathematical? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| max? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| media? | | string \\\\| undefined | _(Optional)_ |\n| method? | | string \\\\| undefined | _(Optional)_ |\n| min? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| mode? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| name? | | string \\\\| undefined | _(Optional)_ |\n| numOctaves? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| offset? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| opacity? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| operator? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| order? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| orient? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| orientation? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| origin? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| overflow? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| panose1? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| path? | | string \\\\| undefined | _(Optional)_ |\n| pathLength? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| patternContentUnits? | | string \\\\| undefined | _(Optional)_ |\n| patternTransform? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| patternUnits? | | string \\\\| undefined | _(Optional)_ |\n| points? | | string \\\\| undefined | _(Optional)_ |\n| pointsAtX? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| pointsAtY? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| pointsAtZ? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| preserveAlpha? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| preserveAspectRatio? | | string \\\\| undefined | _(Optional)_ |\n| primitiveUnits? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| r? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| radius? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| refX? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| refY? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| repeatCount? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| repeatDur? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| requiredextensions? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| requiredFeatures? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| restart? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| result? | | string \\\\| undefined | _(Optional)_ |\n| role? | | string \\\\| undefined | _(Optional)_ |\n| rotate? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| rx? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| ry? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| scale? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| seed? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| slope? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| spacing? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| specularConstant? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| specularExponent? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| speed? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| spreadMethod? | | string \\\\| undefined | _(Optional)_ |\n| startOffset? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| stdDeviation? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| stemh? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| stemv? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| stitchTiles? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| string? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| stroke? | | string \\\\| undefined | _(Optional)_ |\n| style? | | [CSSProperties](#cssproperties) \\\\| string \\\\| undefined | _(Optional)_ |\n| surfaceScale? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| systemLanguage? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| tabindex? | | number \\\\| undefined | _(Optional)_ |\n| tableValues? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| target? | | string \\\\| undefined | _(Optional)_ |\n| targetX? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| targetY? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| textLength? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| to? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| transform? | | string \\\\| undefined | _(Optional)_ |\n| type? | | string \\\\| undefined | _(Optional)_ |\n| u1? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| u2? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| unicode? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| values? | | string \\\\| undefined | _(Optional)_ |\n| version? | | string \\\\| undefined | _(Optional)_ |\n| viewBox? | | string \\\\| undefined | _(Optional)_ |\n| viewTarget? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| visibility? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| width? | | Size \\\\| undefined | _(Optional)_ |\n| widths? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| x? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| x1? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| x2? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| xmlns? | | string \\\\| undefined | _(Optional)_ |\n| y? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| y1? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| y2? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| yChannelSelector? | | string \\\\| undefined | _(Optional)_ |\n| z? | | number \\\\| string \\\\| undefined | _(Optional)_ |\n| zoomAndPan? | | string \\\\| undefined | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-generated.ts)\n\n## SVGProps\n\n```typescript\nexport interface SVGProps<T extends Element> extends SVGAttributes, QwikAttributes<T>\n```\n\n**Extends:** [SVGAttributes](#svgattributes), [QwikAttributes](#qwikattributes)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/jsx/types/jsx-generated.ts)\n\n## sync$\n\nExtract function into a synchronously loadable QRL.\n\nNOTE: Synchronous QRLs functions can't close over any variables, including exports.\n\n```typescript\nsync$: <T extends Function>(fn: T) => SyncQRL<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| fn | T | Function to extract. |\n\n**Returns:**\n\n[SyncQRL](#syncqrl)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/qrl.public.ts)\n\n## SyncQRL\n\n```typescript\nexport type SyncQRL<TYPE extends Function> = QRL<TYPE> & {\n __brand__SyncQRL__: TYPE;\n resolved: TYPE;\n dev?: QRLDev | null;\n} & BivariantQrlFn<QrlArgs<TYPE>, QrlReturn<TYPE>>;\n```\n\n**References:** [QRL](#qrl-type-alias)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/qrl/qrl.public.ts)\n\n## TaskCtx\n\n```typescript\nexport interface TaskCtx\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| cleanup | | (callback: () => [ValueOrPromise](#valueorpromise)<void>) => void | |\n| track | | [Tracker](#tracker) | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-task.ts)\n\n## TaskFn\n\n```typescript\nexport type TaskFn = (\n ctx: TaskCtx,\n) => ValueOrPromise<void | (() => ValueOrPromise<void>)>;\n```\n\n**References:** [TaskCtx](#taskctx), [ValueOrPromise](#valueorpromise)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-task.ts)\n\n## TaskOptions\n\n```typescript\nexport interface TaskOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| deferUpdates? | | boolean | _(Optional)_ Block the rendering of the component until the task completes. Default is `true` |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-task.ts)\n\n## Tracker\n\nUsed to signal to Qwik which state should be watched for changes.\n\nThe `Tracker` is passed into the `taskFn` of `useTask`. It is intended to be used to wrap state objects in a read proxy which signals to Qwik which properties should be watched for changes. A change to any of the properties causes the `taskFn` to rerun.\n\n### Example\n\nThe `obs` passed into the `taskFn` is used to mark `state.count` as a property of interest. Any changes to the `state.count` property will cause the `taskFn` to rerun.\n\n```tsx\nconst Cmp = component$(() => {\n const store = useStore({ count: 0, doubleCount: 0 });\n const signal = useSignal(0);\n useTask$(({ track }) => {\n // Any signals or stores accessed inside the task will be tracked\n const count = track(() => store.count);\n // For stores you can also pass the store and specify the property\n track(store, \"count\");\n // You can also pass a signal to track() directly\n const signalCount = track(signal);\n store.doubleCount = count + signalCount;\n });\n return (\n <div>\n <span>\n {store.count} / {store.doubleCount}\n </span>\n <button\n onClick$={() => {\n store.count++;\n signal.value++;\n }}\n >\n +\n </button>\n </div>\n );\n});\n```\n\n```typescript\nexport interface Tracker\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-task.ts)\n\n## trigger\n\nUse this to trigger running subscribers, for example when the value mutated but remained the same object.\n\n```typescript\ntrigger(): void;\n```\n\n**Returns:**\n\nvoid\n\n## untrack\n\nGet the value of the expression without tracking listeners. A function will be invoked, signals will return their value, and stores will be unwrapped (they return the backing object).\n\nWhen you pass a function, you can also pass additional arguments that the function will receive.\n\nNote that stores are not unwrapped recursively.\n\n```typescript\nuntrack: <T, A extends any[]>(\n expr: ((...args: A) => T) | Signal<T> | T,\n ...args: A\n) => T;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| expr | ((...args: A) => T) \\\\| [Signal](#signal)<T> \\\\| T | The function or object to evaluate without tracking. |\n| args | A | Additional arguments to pass when `expr` is a function. |\n\n**Returns:**\n\nT\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-core.ts)\n\n## unwrapStore\n\nGet the original object that was wrapped by the store. Useful if you want to clone a store (structuredClone, IndexedDB,...)\n\n```typescript\nunwrapStore: <T>(value: T) => T;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| value | T | |\n\n**Returns:**\n\nT\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/reactive-primitives/impl/store.ts)\n\n## useComputed$\n\nCreates a computed signal which is calculated from the given function. A computed signal is a signal which is calculated from other signals. When the signals change, the computed signal is recalculated, and if the result changed, all tasks which are tracking the signal will be re-run and all components that read the signal will be re-rendered.\n\nEvery synchronous signal or store read is tracked automatically. Reads after an `await` are not: the tracking context is lost, so track them explicitly with the `track()` provided on the context argument. When the function is async, reading an unresolved `.value` throws the computation promise, and reading a failed `.value` throws the error.\n\nThe function must not have any side effects.\n\n```typescript\nuseComputed$: <T>(\n qrl: ComputedFn<T>,\n options?: ComputedOptions<T> | undefined,\n) => ComputedReturnType<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | [ComputedFn](#computedfn)<T> | |\n| options | [ComputedOptions](#computedoptions)<T> \\\\| undefined | _(Optional)_ |\n\n**Returns:**\n\n[ComputedReturnType](#computedreturntype)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-computed.ts)\n\n## useConstant\n\nStores a value which is retained for the lifetime of the component. Subsequent calls to `useConstant` will always return the first value given.\n\nIf the value is a function, the function is invoked once to calculate the actual value. You can then also pass arguments to call the function with, so that you don't need to create a new function on every render.\n\n```typescript\nuseConstant: <T, A extends any[]>(value: ((...args: A) => T) | T, ...args: A) =>\n T;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| value | ((...args: A) => T) \\\\| T | |\n| args | A | |\n\n**Returns:**\n\nT\n\n```tsx\nconst fixedRandomValue = useConstant(() => Math.random);\nconst otherFixedRandomValue = useConstant(Math.random);\n\nconst getConfig = (env: string) => { ... }\nconst config = useConstant(getConfig, environment);\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-signal.ts)\n\n## useContext\n\nRetrieve Context value.\n\nUse `useContext()` to retrieve the value of context in a component. To retrieve a value a parent component needs to invoke `useContextProvider()` to assign a value.\n\n### Example\n\n```tsx\n// Declare the Context type.\ninterface TodosStore {\n items: string[];\n}\n// Create a Context ID (no data is saved here.)\n// You will use this ID to both create and retrieve the Context.\nexport const TodosContext = createContextId<TodosStore>(\"Todos\");\n\n// Example of providing context to child components.\nexport const App = component$(() => {\n useContextProvider(\n TodosContext,\n useStore<TodosStore>({\n items: [\"Learn Qwik\", \"Build Qwik app\", \"Profit\"],\n }),\n );\n\n return <Items />;\n});\n\n// Example of retrieving the context provided by a parent component.\nexport const Items = component$(() => {\n const todos = useContext(TodosContext);\n return (\n <ul>\n {todos.items.map((item) => (\n <li>{item}</li>\n ))}\n </ul>\n );\n});\n```\n\n```typescript\nuseContext: UseContext;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-context.ts)\n\n## useContextProvider\n\nAssign a value to a Context.\n\nUse `useContextProvider()` to assign a value to a context. The assignment happens in the component's function. Once assigned, use `useContext()` in any child component to retrieve the value.\n\nContext is a way to pass stores to the child components without prop-drilling. Note that scalar values are allowed, but for reactivity you need signals or stores.\n\n### Example\n\n```tsx\n// Declare the Context type.\ninterface TodosStore {\n items: string[];\n}\n// Create a Context ID (no data is saved here.)\n// You will use this ID to both create and retrieve the Context.\nexport const TodosContext = createContextId<TodosStore>(\"Todos\");\n\n// Example of providing context to child components.\nexport const App = component$(() => {\n useContextProvider(\n TodosContext,\n useStore<TodosStore>({\n items: [\"Learn Qwik\", \"Build Qwik app\", \"Profit\"],\n }),\n );\n\n return <Items />;\n});\n\n// Example of retrieving the context provided by a parent component.\nexport const Items = component$(() => {\n const todos = useContext(TodosContext);\n return (\n <ul>\n {todos.items.map((item) => (\n <li>{item}</li>\n ))}\n </ul>\n );\n});\n```\n\n```typescript\nuseContextProvider: <STATE>(context: ContextId<STATE>, newValue: STATE) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| context | [ContextId](#contextid)<STATE> | The context to assign a value to. |\n| newValue | STATE | |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-context.ts)\n\n## useId\n\n```typescript\nuseId: () => string;\n```\n\n**Returns:**\n\nstring\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-id.ts)\n\n## useOn\n\nRegister a listener on the current component's host element.\n\nUsed to programmatically add event listeners. Useful from custom `use*` methods, which do not have access to the JSX. Otherwise, it's adding a JSX listener in the `<div>` is a better idea.\n\nEvents are case sensitive.\n\n```typescript\nuseOn: <T extends KnownEventNames>(event: T | T[], eventQrl: EventQRL<T>, options?: UseOnOptions) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| event | T \\\\| T[] | |\n| eventQrl | EventQRL<T> | |\n| options | [UseOnOptions](#useonoptions) | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-on.ts)\n\n## useOnDocument\n\nRegister a listener on `document`.\n\nUsed to programmatically add event listeners. Useful from custom `use*` methods, which do not have access to the JSX.\n\nEvents are case sensitive.\n\n```typescript\nuseOnDocument: <T extends KnownEventNames>(event: T | T[], eventQrl: EventQRL<T>, options?: UseOnOptions) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| event | T \\\\| T[] | |\n| eventQrl | EventQRL<T> | |\n| options | [UseOnOptions](#useonoptions) | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-on.ts)\n\n## UseOnOptions\n\n```typescript\nexport type UseOnOptions = UseOnOptionsBase &\n (\n | {\n passive?: boolean;\n preventdefault?: never;\n }\n | {\n passive?: never;\n preventdefault?: boolean;\n }\n );\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-on.ts)\n\n## useOnWindow\n\nRegister a listener on `window`.\n\nUsed to programmatically add event listeners. Useful from custom `use*` methods, which do not have access to the JSX.\n\nEvents are case sensitive.\n\n```typescript\nuseOnWindow: <T extends KnownEventNames>(event: T | T[], eventQrl: EventQRL<T>, options?: UseOnOptions) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| event | T \\\\| T[] | |\n| eventQrl | EventQRL<T> | |\n| options | [UseOnOptions](#useonoptions) | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-on.ts)\n\n## useResource$\n\n> Warning: This API is now obsolete.\n>\n> Use `useComputed$` instead, which is more powerful and flexible. `useResource$` is still available for backward compatibility but it is recommended to migrate to `useComputed$` for new code and when updating existing code.\n\nThis method works like an async memoized function that runs whenever some tracked value changes and returns some data.\n\n`useResource` however returns immediate a `ResourceReturn` object that contains the data and a state that indicates if the data is available or not.\n\nThe status can be one of the following:\n\n- `pending` - the data is not yet available. - `resolved` - the data is available. - `rejected` - the data is not available due to an error or timeout.\n\nBe careful when using a `try/catch` statement in `useResource$`. If you catch the error and don't re-throw it (or a new Error), the resource status will never be `rejected`.\n\n```typescript\nuseResource$: <T>(\n qrl: import(\"./use-resource\").ResourceFn<T>,\n opts?: import(\"./use-resource\").ResourceOptions | undefined,\n) => import(\"./use-resource\").ResourceReturn<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | import(\"./use-resource\").[ResourceFn](#resourcefn)<T> | |\n| opts | import(\"./use-resource\").[ResourceOptions](#resourceoptions) \\\\| undefined | _(Optional)_ |\n\n**Returns:**\n\nimport(\"./use-resource\").[ResourceReturn](#resourcereturn)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-resource-dollar.ts)\n\n## useSerializer$\n\nCreates a signal which holds a custom serializable value. It requires that the value implements the `CustomSerializable` type, which means having a function under the `[SerializeSymbol]` property that returns a serializable value when called.\n\nThe `fn` you pass is called with the result of the serialization (in the browser, only when the value is needed), or `undefined` when not yet initialized. If you refer to other signals, `fn` will be called when those change just like computed signals, and then the argument will be the previous output, not the serialized result.\n\nThis is useful when using third party libraries that use custom objects that are not serializable.\n\nNote that the `fn` is called lazily, so it won't impact container resume.\n\n```typescript\nuseSerializer$: typeof createSerializer$;\n```\n\n```tsx\nclass MyCustomSerializable {\n constructor(public n: number) {}\n inc() {\n this.n++;\n }\n}\nconst Cmp = component$(() => {\n const custom = useSerializer$({\n deserialize: (data) => new MyCustomSerializable(data),\n serialize: (data) => data.n,\n initial: 2,\n });\n return <div onClick$={() => custom.value.inc()}>{custom.value.n}</div>;\n});\n```\n\nWhen using a Signal as the data to create the object, you need to pass the configuration as a function, and you can then also provide the `update` function to update the object when the signal changes.\n\nBy returning an object from `update`, you signal that the listeners have to be notified. You can mutate the current object but you should return it so that it will trigger listeners.\n\n```tsx\nconst Cmp = component$(() => {\n const n = useSignal(2);\n const custom = useSerializer$(() => ({\n deserialize: () => new MyCustomSerializable(n.value),\n update: (current) => {\n current.n = n.value;\n return current;\n },\n }));\n return <div onClick$={() => n.value++}>{custom.value.n}</div>;\n});\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-serializer.ts)\n\n## useServerData\n\n```typescript\nexport declare function useServerData<T>(key: string): T | undefined;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| key | string | |\n\n**Returns:**\n\nT \\| undefined\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-env-data.ts)\n\n## useSignal\n\nCreates an object with a single reactive `.value` property, that Qwik can track across serializations.\n\nUse it to create state for your application. The object has a getter and setter to track reads and writes of the `.value` property. When the value changes, any functions that read from it will re-run.\n\nPrefer `useSignal` over `useStore` when possible, as it is more efficient.\n\n### Example\n\n```tsx\nconst Signals = component$(() => {\n const counter = useSignal(1);\n const text = useSignal('changeme');\n const toggle = useSignal(false);\n\n // useSignal() can also accept a function to calculate the initial value\n const state = useSignal(() => {\n return expensiveInitialValue();\n });\n\n return (\n <div>\n <button onClick$={() => counter.value++}>Counter: {counter.value}</button>\n {\n // pass signal values as the value, the optimizer will make it pass the signal\n }\n <Child state={state.value} />\n {\n // signals can be bound to inputs. A property named `bind:x` implies that the property\nis a signal\n }\n <input type=\"text\" bind:value={text} />\n <input type=\"checkbox\" bind:checked={toggle} />\n </div>\n );\n});\n```\n\n```typescript\nuseSignal: UseSignal;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-signal.ts)\n\n## UseSignal\n\nCreates an object with a single reactive `.value` property, that Qwik can track across serializations.\n\nUse it to create state for your application. The object has a getter and setter to track reads and writes of the `.value` property. When the value changes, any functions that read from it will re-run.\n\nPrefer `useSignal` over `useStore` when possible, as it is more efficient.\n\n### Example\n\n```tsx\nconst Signals = component$(() => {\n const counter = useSignal(1);\n const text = useSignal('changeme');\n const toggle = useSignal(false);\n\n // useSignal() can also accept a function to calculate the initial value\n const state = useSignal(() => {\n return expensiveInitialValue();\n });\n\n return (\n <div>\n <button onClick$={() => counter.value++}>Counter: {counter.value}</button>\n {\n // pass signal values as the value, the optimizer will make it pass the signal\n }\n <Child state={state.value} />\n {\n // signals can be bound to inputs. A property named `bind:x` implies that the property\nis a signal\n }\n <input type=\"text\" bind:value={text} />\n <input type=\"checkbox\" bind:checked={toggle} />\n </div>\n );\n});\n```\n\n```typescript\nuseSignal: UseSignal;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-signal.ts)\n\n## useStore\n\nCreates a reactive object that Qwik can track across serialization.\n\nUse it to create state for your application. The returned object is a Proxy that tracks reads and writes. When any of the properties change, the functions that read those properties will re-run.\n\n`Store`s are deep by default, meaning that any objects assigned to properties will also become `Store`s. This includes arrays.\n\nPrefer `useSignal` over `useStore` when possible, as it is more efficient.\n\n### Example\n\nExample showing how `useStore` is used in Counter example to keep track of the count.\n\n```tsx\nconst Stores = component$(() => {\n const counter = useCounter(1);\n\n // Reactivity happens even for nested objects and arrays\n const userData = useStore({\n name: \"Manu\",\n address: {\n address: \"\",\n city: \"\",\n },\n orgs: [],\n });\n\n // useStore() can also accept a function to calculate the initial value\n const state = useStore(() => {\n return {\n value: expensiveInitialValue(),\n };\n });\n\n return (\n <div>\n <div>Counter: {counter.value}</div>\n <Child userData={userData} state={state} />\n </div>\n );\n});\n\nfunction useCounter(step: number) {\n // Multiple stores can be created in custom hooks for convenience and composability\n const counterStore = useStore({\n value: 0,\n });\n useVisibleTask$(() => {\n // Only runs in the client\n const timer = setInterval(() => {\n counterStore.value += step;\n }, 500);\n return () => {\n clearInterval(timer);\n };\n });\n return counterStore;\n}\n```\n\n```typescript\nuseStore: <STATE extends object>(\n initialState: STATE | (() => STATE),\n opts?: UseStoreOptions,\n) => STATE;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| initialState | STATE \\\\| (() => STATE) | |\n| opts | [UseStoreOptions](#usestoreoptions) | _(Optional)_ |\n\n**Returns:**\n\nSTATE\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-store.public.ts)\n\n## UseStoreOptions\n\n```typescript\nexport interface UseStoreOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| deep? | | boolean | _(Optional)_ If `true` then all nested objects and arrays will be tracked as well. Default is `true`. |\n| reactive? | | boolean | _(Optional)_ If `false` then the object will not be tracked for changes. Default is `true`. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-store.public.ts)\n\n## useStyles$\n\nA lazy-loadable reference to a component's styles.\n\nComponent styles allow Qwik to lazy load the style information for the component only when needed. (And avoid double loading it in case of SSR hydration.)\n\n```tsx\nimport styles from \"./code-block.css?inline\";\n\nexport const CmpStyles = component$(() => {\n useStyles$(styles);\n\n return <div>Some text</div>;\n});\n```\n\n```typescript\nuseStyles$: (qrl: string) => UseStyles;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | string | |\n\n**Returns:**\n\nUseStyles\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-styles.ts)\n\n## UseStylesScoped\n\n```typescript\nexport interface UseStylesScoped\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| scopeId | | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-styles.ts)\n\n## useStylesScoped$\n\nA lazy-loadable reference to a component's styles, that is scoped to the component.\n\nComponent styles allow Qwik to lazy load the style information for the component only when needed. (And avoid double loading it in case of SSR hydration.)\n\n```tsx\nimport scoped from \"./code-block.css?inline\";\n\nexport const CmpScopedStyles = component$(() => {\n useStylesScoped$(scoped);\n\n return <div>Some text</div>;\n});\n```\n\n```typescript\nuseStylesScoped$: (qrl: string) => UseStylesScoped;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | string | |\n\n**Returns:**\n\n[UseStylesScoped](#usestylesscoped)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-styles.ts)\n\n## useTask$\n\nReruns the `taskFn` when the observed inputs change.\n\nUse `useTask` to observe changes on a set of inputs, and then re-execute the `taskFn` when those inputs change.\n\nThe `taskFn` only executes if the observed inputs change. To observe the inputs, use the `obs` function to wrap property reads. This creates subscriptions that will trigger the `taskFn` to rerun.\n\nCleanup callbacks registered with `cleanup()` or returned from the task may be async. When a task reruns, Qwik waits for the previous cleanup to finish before starting the next invocation.\n\nDuring SSR, the cleanup function is called immediately after SSR completes. Therefore, it is not called on the client side after resuming, but only the second time the task runs on the client.\n\n```typescript\nuseTask$: (fn: TaskFn, opts?: TaskOptions) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| fn | [TaskFn](#taskfn) | |\n| opts | [TaskOptions](#taskoptions) | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-task-dollar.ts)\n\n## useVisibleTask$\n\n```tsx\nconst Timer = component$(() => {\n const store = useStore({\n count: 0,\n });\n\n useVisibleTask$(() => {\n // Only runs in the client\n const timer = setInterval(() => {\n store.count++;\n }, 500);\n return () => {\n clearInterval(timer);\n };\n });\n\n return <div>{store.count}</div>;\n});\n```\n\nVisible Tasks are a variant of Tasks that only run in the browser, and are registered but not executed during SSR. They are useful for running code that should only execute in the browser, such as code that interacts with the DOM or browser APIs.\n\nCleanup callbacks registered with `cleanup()` or returned from the task may be async. When a visible task reruns, Qwik waits for the previous cleanup to finish before starting the next invocation.\n\n```typescript\nuseVisibleTask$: (fn: TaskFn, opts?: OnVisibleTaskOptions) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| fn | [TaskFn](#taskfn) | |\n| opts | [OnVisibleTaskOptions](#onvisibletaskoptions) | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-visible-task-dollar.ts)\n\n## ValueOrPromise\n\nType representing a value which is either resolve or a promise.\n\n```typescript\nexport type ValueOrPromise<T> = T | Promise<T>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/shared/utils/types.ts)\n\n## version\n\nQWIK_VERSION\n\n```typescript\nversion: string;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/version.ts)\n\n## VisibleTaskStrategy\n\n```typescript\nexport type VisibleTaskStrategy =\n | \"intersection-observer\"\n | \"document-ready\"\n | \"document-idle\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-visible-task.ts)\n\n## withLocale\n\nOverride the `getLocale` with `lang` within the `fn` execution.\n\n`fn` may be async. The locale stays set until the returned promise settles, even when AsyncLocalStorage is not available.\n\n```typescript\nexport declare function withLocale<T>(locale: string, fn: () => T): T;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| locale | string | |\n| fn | () => T | |\n\n**Returns:**\n\nT\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/core/use/use-locale.ts)\n\n## write\n\n```typescript\nwrite(chunk: JSXOutput): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| chunk | [JSXOutput](#jsxoutput) | |\n\n**Returns:**\n\nvoid\n"},{"id":"/api/qwik-router/","title":"@qwik.dev/qwik-router","description":"Router API reference for routing, loaders, actions, middleware, and server utilities.","url":"https://next.qwik.dev/api/qwik-router/","content":"# [API](/api.md) › @qwik.dev/router\n\n## Action\n\n```typescript\nexport type Action<\n RETURN,\n INPUT = Record<string, unknown>,\n OPTIONAL extends boolean = true,\n> = {\n (): ActionStore<ExcludeControlFlow<RETURN>, INPUT, OPTIONAL>;\n};\n```\n\n**References:** [ActionStore](#actionstore), [ExcludeControlFlow](#excludecontrolflow)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ActionConstructor\n\n```typescript\nexport type ActionConstructor = {\n <\n OBJ extends Record<string, any> | void | null,\n VALIDATOR extends TypedDataValidator,\n REST extends [DataValidator, ...DataValidator[]],\n >(\n actionQrl: (\n data: GetValidatorOutputType<VALIDATOR>,\n event: RequestEventAction,\n ) => ValueOrPromise<OBJ>,\n options: ActionOptions & {\n readonly validation: [VALIDATOR, ...REST];\n },\n ): Action<\n StrictUnion<\n | OBJ\n | FailReturn<ValidatorErrorType<GetValidatorInputType<VALIDATOR>>>\n | FailReturn<FailOfRest<REST>>\n >,\n GetValidatorInputType<VALIDATOR>,\n false\n >;\n <\n OBJ extends Record<string, any> | void | null,\n VALIDATOR extends TypedDataValidator,\n >(\n actionQrl: (\n data: GetValidatorOutputType<VALIDATOR>,\n event: RequestEventAction,\n ) => ValueOrPromise<OBJ>,\n options: ActionOptions & {\n readonly validation: [VALIDATOR];\n },\n ): Action<\n StrictUnion<\n OBJ | FailReturn<ValidatorErrorType<GetValidatorInputType<VALIDATOR>>>\n >,\n GetValidatorInputType<VALIDATOR>,\n false\n >;\n <\n OBJ extends Record<string, any> | void | null,\n REST extends [DataValidator, ...DataValidator[]],\n >(\n actionQrl: (\n data: JSONObject,\n event: RequestEventAction,\n ) => ValueOrPromise<OBJ>,\n options: ActionOptions & {\n readonly validation: REST;\n },\n ): Action<StrictUnion<OBJ | FailReturn<FailOfRest<REST>>>>;\n <\n OBJ extends Record<string, any> | void | null,\n VALIDATOR extends TypedDataValidator,\n REST extends [DataValidator, ...DataValidator[]],\n >(\n actionQrl: (\n data: GetValidatorOutputType<VALIDATOR>,\n event: RequestEventAction,\n ) => ValueOrPromise<OBJ>,\n options: VALIDATOR,\n ...rest: REST\n ): Action<\n StrictUnion<\n | OBJ\n | FailReturn<ValidatorErrorType<GetValidatorInputType<VALIDATOR>>>\n | FailReturn<FailOfRest<REST>>\n >,\n GetValidatorInputType<VALIDATOR>,\n false\n >;\n <\n OBJ extends Record<string, any> | void | null,\n VALIDATOR extends TypedDataValidator,\n >(\n actionQrl: (\n data: GetValidatorOutputType<VALIDATOR>,\n event: RequestEventAction,\n ) => ValueOrPromise<OBJ>,\n options: VALIDATOR,\n ): Action<\n StrictUnion<\n OBJ | FailReturn<ValidatorErrorType<GetValidatorInputType<VALIDATOR>>>\n >,\n GetValidatorInputType<VALIDATOR>,\n false\n >;\n <\n OBJ extends Record<string, any> | void | null,\n REST extends [DataValidator, ...DataValidator[]],\n >(\n actionQrl: (\n form: JSONObject,\n event: RequestEventAction,\n ) => ValueOrPromise<OBJ>,\n ...rest: REST\n ): Action<StrictUnion<OBJ | FailReturn<FailOfRest<REST>>>>;\n <OBJ>(\n actionQrl: (\n form: JSONObject,\n event: RequestEventAction,\n ) => ValueOrPromise<OBJ>,\n options?: ActionOptions,\n ): Action<StrictUnion<OBJ>>;\n};\n```\n\n**References:** [TypedDataValidator](#typeddatavalidator), [DataValidator](#datavalidator), [GetValidatorOutputType](#getvalidatoroutputtype), [ActionOptions](#actionoptions), [Action](#action), [StrictUnion](#strictunion), [FailReturn](#failreturn), [ValidatorErrorType](#validatorerrortype), [GetValidatorInputType](#getvalidatorinputtype), [FailOfRest](#failofrest), [JSONObject](#jsonobject)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ActionOptions\n\n```typescript\nexport type ActionOptions = {\n readonly id?: string;\n readonly validation?: DataValidator[];\n readonly invalidate?: Loader<any>[];\n};\n```\n\n**References:** [DataValidator](#datavalidator), [Loader](#loader_2)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ActionReturn\n\n```typescript\nexport type ActionReturn<RETURN> = {\n readonly status?: number;\n readonly value: RETURN;\n};\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ActionStore\n\n```typescript\nexport type ActionStore<RETURN, INPUT, OPTIONAL extends boolean = true> = {\n readonly actionPath: string;\n readonly isRunning: boolean;\n readonly status?: number;\n readonly formData: FormData | undefined;\n readonly value: RETURN | undefined;\n readonly submit: QRL<\n OPTIONAL extends true\n ? (form?: INPUT | FormData | SubmitEvent) => Promise<ActionReturn<RETURN>>\n : (form: INPUT | FormData | SubmitEvent) => Promise<ActionReturn<RETURN>>\n >;\n readonly submitted: boolean;\n};\n```\n\n**References:** [ActionReturn](#actionreturn)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## CacheKeyFn\n\nCache key function. Used by `routeConfig.cacheKey` (SSR HTML cache) and by `routeLoader$`'s `cacheKey` option (per-loader JSON cache).\n\n- `true`: use the surface's default key.\n\n- SSR default: `${status}|${eTag}|${pathname}` when an eTag is set, otherwise `${status}|${pathname}`. - Loader default: `${pathname}|${filteredSearch}|${loaderId}|${eTag}` when an eTag is set, otherwise `${pathname}|${filteredSearch}|${loaderId}`. - Function: receives the request event and the normalized, unquoted eTag (or an empty string when none was provided). Return the cache key string, or `null` or `''` to skip caching for this request. Loader callbacks receive the loader-scoped request event, with `url`, `query`, and `request.url` filtered by the loader's `search` allowlist.\n\nNote: valid cacheKeys are non-empty strings.\n\n```typescript\nexport type CacheKeyFn =\n | true\n | ((requestEv: RequestEvent, eTag: string) => string | null);\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ContentHeading\n\n```typescript\nexport interface ContentHeading\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| id | `readonly` | string | |\n| level | `readonly` | number | |\n| text | `readonly` | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ContentMenu\n\n```typescript\nexport interface ContentMenu\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| href? | `readonly` | string | _(Optional)_ |\n| items? | `readonly` | [ContentMenu](#contentmenu)[] | _(Optional)_ |\n| text | `readonly` | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ContentModuleETag\n\nThe eTag export type for routeConfig.\n\n- `string` — static ETag value. - `(props: DocumentHeadProps) => string | null` — compute the ETag from route context (params, URL, loaded data via `resolveValue`, etc.). Return `null` to skip eTag for this request.\n\nQwik normalizes eTag values by stripping weak-form `W/` prefixes, quotes, and forbidden chars, then sends a strong `ETag` header. Values that normalize to an empty string are treated as absent.\n\nWhen set (and a value is produced), the server includes an `ETag` header and returns `304` if `If-None-Match` matches.\n\n```typescript\nexport type ContentModuleETag =\n | string\n | ((props: DocumentHeadProps) => string | null);\n```\n\n**References:** [DocumentHeadProps](#documentheadprops)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ContentModuleHead\n\n```typescript\nexport type ContentModuleHead = DocumentHead | ResolvedDocumentHead;\n```\n\n**References:** [DocumentHead](#documenthead), [ResolvedDocumentHead](#resolveddocumenthead)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## createRenderer\n\nCreates the `render()` function that is required by `createQwikRouter()`. It requires a function that returns the `jsx` and `options` for the renderer.\n\n```typescript\ncreateRenderer: (\n getOptions: (options: RendererOptions) => {\n jsx: JSXOutput;\n options: RendererOutputOptions;\n },\n) => Render;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| getOptions | (options: [RendererOptions](#rendereroptions)) => \\{ jsx: JSXOutput; options: [RendererOutputOptions](#rendereroutputoptions); } | |\n\n**Returns:**\n\nRender\n\n```tsx\nconst renderer = createRenderer((opts) => {\n if (opts.requestHeaders[\"x-hello\"] === \"world\") {\n return { jsx: <Hello />, options: opts };\n }\n return {\n jsx: <Root />,\n options: {\n ...opts,\n serverData: {\n ...opts.serverData,\n documentHead: {\n meta: [{ name: \"renderedAt\", content: new Date().toISOString() }],\n },\n },\n },\n };\n});\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/create-renderer.ts)\n\n## DataValidator\n\n```typescript\nexport type DataValidator<T extends Record<string, any> = {}> = {\n validate(ev: RequestEvent, data: unknown): Promise<ValidatorReturn<T>>;\n};\n```\n\n**References:** [ValidatorReturn](#validatorreturn)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## DocumentHead\n\n```typescript\nexport type DocumentHead =\n | DocumentHeadValue\n | ((props: DocumentHeadProps) => DocumentHeadValue);\n```\n\n**References:** [DocumentHeadValue](#documentheadvalue), [DocumentHeadProps](#documentheadprops)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## DocumentHeadProps\n\n```typescript\nexport interface DocumentHeadProps extends RouteLocation\n```\n\n**Extends:** [RouteLocation](#routelocation)\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| head | `readonly` | [ResolvedDocumentHead](#resolveddocumenthead) | |\n| resolveValue | `readonly` | ResolveSyncValue | |\n| status | `readonly` | number | The HTTP status code of the response (e.g. 200, 404). |\n| withLocale | `readonly` | <T>(fn: () => T) => T | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## DocumentHeadTags\n\nThis renders all the tags collected from `head`.\n\nYou can partially override the head, for example if you want to change the title:\n\n```tsx\nimport { DocumentHeadTags, useDocumentHead } from \"@qwik.dev/router\";\n\nexport default component$(() => {\n const head = useDocumentHead();\n return <DocumentHeadTags title={`${head.title} - My App`} />;\n});\n```\n\nYou don't have to use this component, you can also do it yourself for full control. Just copy the code from this component and modify it to your needs.\n\nNote that this component normally only runs once, during SSR. You can use Signals in your `src/root.tsx` to make runtime changes to `<head>` if needed.\n\n```typescript\nDocumentHeadTags: import(\"@qwik.dev/core\").Component<\n DocumentHeadValue<Record<string, unknown>>\n>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/document-head-tags-component.tsx)\n\n## DocumentHeadValue\n\n```typescript\nexport interface DocumentHeadValue<FrontMatter extends Record<string, any> = Record<string, unknown>>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| frontmatter? | `readonly` | Readonly<FrontMatter> | _(Optional)_ Arbitrary object containing custom data. When the document head is created from markdown files, the frontmatter attributes that are not recognized as a well-known meta names (such as title, description, author, etc...), are stored in this property. |\n| links? | `readonly` | readonly [DocumentLink](#documentlink)[] | _(Optional)_ Used to manually append `` elements to the ``. |\n| meta? | `readonly` | readonly [DocumentMeta](#documentmeta)[] | _(Optional)_ Used to manually set meta tags in the head. |\n| scripts? | `readonly` | readonly [DocumentScript](#documentscript)[] | _(Optional)_ Used to manually append `` elements to the ``. |\n| styles? | `readonly` | readonly [DocumentStyle](#documentstyle)[] | _(Optional)_ Used to manually append `` elements to the ``. |\n| title? | `readonly` | string | _(Optional)_ Sets `document.title`. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## DocumentLink\n\n```typescript\nexport type DocumentLink = QwikIntrinsicElements[\"link\"];\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## DocumentMeta\n\n```typescript\nexport type DocumentMeta = QwikIntrinsicElements[\"meta\"];\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## DocumentScript\n\n```typescript\nexport type DocumentScript = (\n | (Omit<QwikIntrinsicElements[\"script\"], \"dangerouslySetInnerHTML\"> & {\n props?: never;\n })\n | {\n key?: string;\n props: Readonly<QwikIntrinsicElements[\"script\"]>;\n }\n) &\n (\n | {\n script?: string;\n dangerouslySetInnerHTML?: never;\n }\n | {\n dangerouslySetInnerHTML?: string;\n script?: never;\n }\n );\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## DocumentStyle\n\n```typescript\nexport type DocumentStyle = Readonly<\n (\n | (Omit<QwikIntrinsicElements[\"style\"], \"dangerouslySetInnerHTML\"> & {\n props?: never;\n })\n | {\n key?: string;\n props: Readonly<QwikIntrinsicElements[\"style\"]>;\n }\n ) &\n (\n | {\n style?: string;\n dangerouslySetInnerHTML?: never;\n }\n | {\n dangerouslySetInnerHTML?: string;\n style?: never;\n }\n )\n>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## Editable\n\n```typescript\nexport type Editable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ExcludeControlFlow\n\nDrops control-flow signals (`ev.redirect()`, `ev.error()`, etc.) from a loader/action return type: those are thrown, not surfaced as data. `ev.fail()` is plain data and is kept.\n\n```typescript\nexport type ExcludeControlFlow<T> = Exclude<T, AbortMessage | ServerError>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## FailOfRest\n\n```typescript\nexport type FailOfRest<REST extends readonly DataValidator[]> =\n REST extends readonly DataValidator<infer ERROR>[] ? ERROR : never;\n```\n\n**References:** [DataValidator](#datavalidator)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## FailReturn\n\n```typescript\nexport type FailReturn<T> = T & Failed;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## Form\n\n```typescript\nForm: <O, I>(input: FormProps<O, I>, key: string | null) =>\n import(\"@qwik.dev/core\").JSXOutput;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| \\{ action, spaReset, reloadDocument, onSubmit$, ...rest } | (not declared) | |\n| input | [FormProps](#formprops)<O, I> | |\n| key | string \\\\| null | |\n\n**Returns:**\n\nimport(\"@qwik.dev/core\").JSXOutput\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/form-component.tsx)\n\n## FormProps\n\n```typescript\nexport interface FormProps<O, I> extends Omit<QwikJSX.IntrinsicElements['form'], 'action' | 'method'>\n```\n\n**Extends:** Omit&lt;QwikJSX.IntrinsicElements['form'], 'action' \\| 'method'&gt;\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| action? | | [ActionStore](#actionstore)<O, I, true \\\\| false> | _(Optional)_ Reference to the action returned by `action()`. |\n| key? | | string \\\\| number \\\\| null | _(Optional)_ |\n| onSubmitCompleted$? | | QRLEventHandlerMulti<CustomEvent<[FormSubmitCompletedDetail](#formsubmitsuccessdetail)<O>>, HTMLFormElement> \\\\| undefined | _(Optional)_ Event handler executed right after the action is executed successfully and returns some data. |\n| reloadDocument? | | boolean | _(Optional)_ When `true` the form submission will cause a full page reload, even if SPA mode is enabled and JS is available. |\n| spaReset? | | boolean | _(Optional)_ When `true` all the form inputs will be reset in SPA mode, just like happens in a full page form submission. Defaults to `false` |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/form-component.tsx)\n\n## FormSubmitSuccessDetail\n\n```typescript\nexport interface FormSubmitCompletedDetail<T>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| status | | number | |\n| value | | T | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/form-component.tsx)\n\n## getBasePathname\n\nThe base pathname the app is served under, such as `/` or `/docs/`.\n\n```typescript\ngetBasePathname: () => string;\n```\n\n**Returns:**\n\nstring\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/router-config.ts)\n\n## getRequestEvent\n\nReturns the current RequestEvent if possible. Only usable on the server, and only during request processing.\n\n```typescript\ngetRequestEvent: (thisArg?: unknown) => RequestEvent | undefined;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| thisArg | unknown | _(Optional)_ |\n\n**Returns:**\n\nRequestEvent \\| undefined\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/route-loaders.ts)\n\n## getRouterConfig\n\nThe app's route config: the route trie, server plugins and build options that the Qwik Router Vite plugin generated. Resolves once the config is loaded and its `server$` modules are registered. On the server, the router copy of a Qwik library kept external reads the config of the app serving the current request.\n\n```typescript\ngetRouterConfig: () => Promise<QwikRouterConfig>;\n```\n\n**Returns:**\n\nPromise&lt;[QwikRouterConfig](#qwikrouterconfig)&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/router-config.ts)\n\n## getRoutes\n\nThe route trie of the app, as generated by the Qwik Router Vite plugin.\n\n```typescript\ngetRoutes: () => Promise<RouteData>;\n```\n\n**Returns:**\n\nPromise&lt;[RouteData](#routedata)&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/router-config.ts)\n\n## getTrailingSlash\n\nWhether the app's URLs end with a trailing slash.\n\n```typescript\ngetTrailingSlash: () => boolean;\n```\n\n**Returns:**\n\nboolean\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/router-config.ts)\n\n## GetValidatorInputType\n\n```typescript\nexport type GetValidatorInputType<VALIDATOR extends TypedDataValidator> =\n VALIDATOR extends ValibotDataValidator<infer TYPE>\n ? v.InferInput<TYPE>\n : VALIDATOR extends ZodDataValidator<infer TYPE>\n ? z.input<TYPE>\n : never;\n```\n\n**References:** [TypedDataValidator](#typeddatavalidator)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## GetValidatorOutputType\n\n```typescript\nexport type GetValidatorOutputType<VALIDATOR extends TypedDataValidator> =\n VALIDATOR extends ValibotDataValidator<infer TYPE>\n ? v.InferOutput<TYPE>\n : VALIDATOR extends ZodDataValidator<infer TYPE>\n ? z.output<TYPE>\n : never;\n```\n\n**References:** [TypedDataValidator](#typeddatavalidator)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## GetValidatorType\n\n```typescript\nexport type GetValidatorType<VALIDATOR extends TypedDataValidator> =\n GetValidatorOutputType<VALIDATOR>;\n```\n\n**References:** [TypedDataValidator](#typeddatavalidator), [GetValidatorOutputType](#getvalidatoroutputtype)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## globalAction$\n\n```typescript\nglobalAction$: ActionConstructor;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/server-functions.ts)\n\n## HttpErrorProps\n\n```typescript\nexport type HttpStatus = {\n status: number;\n message: string;\n};\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## JSONObject\n\n```typescript\nexport type JSONObject = {\n [x: string]: JSONValue;\n};\n```\n\n**References:** [JSONValue](#jsonvalue)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## JSONValue\n\n```typescript\nexport type JSONValue =\n | string\n | number\n | boolean\n | {\n [x: string]: JSONValue;\n }\n | Array<JSONValue>;\n```\n\n**References:** [JSONValue](#jsonvalue)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## Link\n\n```typescript\nLink: import(\"@qwik.dev/core\").Component<LinkProps>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/link-component.tsx)\n\n## LinkProps\n\n```typescript\nexport interface LinkProps extends AnchorAttributes\n```\n\n**Extends:** AnchorAttributes\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| prefetch? | | boolean \\\\| 'js' | _(Optional)_ |\n| prefetchBundles? | | [PrefetchStrategy](#prefetchstrategy) | _(Optional)_ Controls when Qwik should prefetch the javascript bundles required to render this \\*\\*`Link`\\*\\* target during client-side navigation. Defaults to \\*\\*`\"visible\"`\\*\\*. Prefetching will not occur if the user has the \\*\\*data saver\\*\\* setting enabled. |\n| prefetchData? | | [PrefetchStrategy](#prefetchstrategy) | _(Optional)_ Controls when Qwik should prefetch and cache route data for this \\*\\*`Link`\\*\\* target, including invoking any \\*\\*`routeLoader$`\\*\\*, \\*\\*`onGet`\\*\\*, etc. Defaults to \\*\\*`\"intent\"`\\*\\*. When using the deprecated \\*\\*`prefetch=\"js\"`\\*\\* prop, route data prefetching defaults to \\*\\*`\"off\"`\\*\\*. Prefetching route data can improve client-side navigation performance for pages that wait on loaders, server handlers, databases, or API calls. Prefetching will not occur if the user has the \\*\\*data saver\\*\\* setting enabled. |\n| reload? | | boolean | _(Optional)_ |\n| replaceState? | | boolean | _(Optional)_ |\n| scroll? | | boolean | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/link-component.tsx)\n\n## Loader_2\n\n```typescript\nexport type Loader<RETURN> = {\n (): LoaderSignal<ExcludeControlFlow<RETURN>>;\n};\n```\n\n**References:** [LoaderSignal](#loadersignal), [ExcludeControlFlow](#excludecontrolflow)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## LoaderSignal\n\n```typescript\nexport type LoaderSignal<TYPE> = (TYPE extends () => ValueOrPromise<\n infer VALIDATOR\n>\n ? Signal<ValueOrPromise<VALIDATOR>>\n : Signal<TYPE>) &\n Pick<ComputedSignal<any>, \"promise\">;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## NavigationType_2\n\n```typescript\nexport type NavigationType = \"initial\" | \"form\" | \"link\" | \"popstate\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## omitProps\n\n> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\nCreates a new object from `obj` by omitting a set of `keys`.\n\n```typescript\nexport declare function omitProps<T, KEYS extends keyof T>(\n obj: T,\n keys: KEYS[],\n): Omit<T, KEYS>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| obj | T | |\n| keys | KEYS[] | |\n\n**Returns:**\n\nOmit&lt;T, KEYS&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/typed-routes.ts)\n\n## PageModule\n\n```typescript\nexport type PageModule = RouteModule & {\n readonly default: (props: Record<string, never>) => JSXOutput;\n readonly routeConfig?: RouteConfig;\n readonly head?: ContentModuleHead;\n readonly eTag?: ContentModuleETag;\n readonly cacheKey?: CacheKeyFn;\n readonly headings?: ContentHeading[];\n readonly onStaticGenerate?: StaticGenerateHandler;\n};\n```\n\n**References:** [RouteConfig](#routeconfig), [ContentModuleHead](#contentmodulehead), [ContentModuleETag](#contentmoduleetag), [CacheKeyFn](#cachekeyfn), [ContentHeading](#contentheading), [StaticGenerateHandler](#staticgeneratehandler)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## PathParams\n\n```typescript\nexport declare type PathParams = Record<string, string>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## PrefetchStrategy\n\nDefines when link prefetching should be triggered.\n\n```typescript\nexport type PrefetchStrategy =\n /**\n * Prefetch when the user commits to navigating.\n *\n * Triggered by `pointerdown` or the `Enter` key.\n */\n | \"commit\"\n /**\n * Prefetch when the user shows navigation intent.\n *\n * Triggered by `pointerenter`, hover, or focus.\n */\n | \"intent\"\n /** Prefetch when the link becomes visible in the viewport. */\n | \"visible\"\n /** Disable link prefetching. */\n | \"off\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/link-component.tsx)\n\n## PreventNavigateCallback\n\n```typescript\nexport type PreventNavigateCallback = (\n url?: number | URL,\n) => ValueOrPromise<boolean>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## Q_ROUTE\n\n```typescript\nQ_ROUTE = \"q:route\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/constants.ts)\n\n## QWIK_CITY_SCROLLER\n\n> Warning: This API is now obsolete.\n>\n> Use `QWIK_ROUTER_SCROLLER` instead (will be removed in V3)\n\n```typescript\nQWIK_CITY_SCROLLER = \"_qCityScroller\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QWIK_ROUTER_SCROLLER\n\n```typescript\nQWIK_ROUTER_SCROLLER = \"_qRouterScroller\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikCityMockProvider\n\n> Warning: This API is now obsolete.\n>\n> Use `useQwikMockRouter()` instead. Will be removed in V3\n\n```typescript\nQwikCityMockProvider: import(\"@qwik.dev/core\").Component<QwikRouterMockProps>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikCityPlan\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterConfig` instead. Will be removed in V3.\n\n```typescript\nexport type QwikCityPlan = QwikRouterConfig;\n```\n\n**References:** [QwikRouterConfig](#qwikrouterconfig)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## QwikCityProps\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterProps` instead. Will be removed in v3.\n\n```typescript\nexport type QwikCityProps = QwikRouterProps;\n```\n\n**References:** [QwikRouterProps](#qwikrouterprops)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikCityProvider\n\n> Warning: This API is now obsolete.\n>\n> Use `useQwikRouter()` instead. Will be removed in v3.\n\n```typescript\nQwikCityProvider: import(\"@qwik.dev/core\").Component<QwikRouterProps>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikRouterConfig\n\n```typescript\nexport interface QwikRouterConfig\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| basePathname? | `readonly` | string | _(Optional)_ |\n| cacheModules? | `readonly` | boolean | _(Optional)_ |\n| fallthrough? | `readonly` | boolean | _(Optional)_ When true, return null instead of rendering the 404 page, letting the adapter handle it |\n| importEagerModules? | `readonly` | () => Promise<unknown> | _(Optional)_ Imports the modules containing `server$` functions so their registration side effects run. Called by the request handler before serving; deliberately async so the config module itself evaluates without touching the runtime (see the import-cycle notes in `route-loaders.ts`). |\n| routes | `readonly` | [RouteData](#routedata) | |\n| serverPlugins? | `readonly` | RouteModule[] | _(Optional)_ |\n| serviceWorkerUrl? | `readonly` | string | _(Optional)_ URL of the app's service worker, when the routes define one. |\n| trailingSlash? | `readonly` | boolean | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## QwikRouterEnvData\n\n```typescript\nexport interface QwikRouterEnvData\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| ev | | RequestEvent | |\n| loadedRoute | | LoadedRoute | |\n| loaderValues | | Record<string, unknown> | |\n| params | | [PathParams](#pathparams) | |\n| response | | EndpointResponse | |\n| routeLoaderCtx | | RouteLoaderCtx | |\n| routeName | | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## QwikRouterMockActionProp\n\n```typescript\nexport interface QwikRouterMockActionProp<T = any>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| action | | [Action](#action)<T> | The action function to mock. |\n| handler | | QRL<(data: T) => ValueOrPromise<RouteActionResolver>> | The QRL function that will be called when the action is submitted. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikRouterMockLoaderProp\n\n```typescript\nexport interface QwikRouterMockLoaderProp<T = any>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| data | | T | The data to return when the loader is called. |\n| loader | | [Loader](#loader_2)<T> | The loader function to mock. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikRouterMockProps\n\n```typescript\nexport interface QwikRouterMockProps\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| actions? | | Array<[QwikRouterMockActionProp](#qwikroutermockactionprop)<any>> | _(Optional)_ Allow mocking actions defined with `routeAction$` function. ``` [ { action: useAddUser, handler: $(async (data) => { console.log('useAddUser action called with data:', data); }), }, ]; ``` |\n| goto? | | [RouteNavigate](#routenavigate) | _(Optional)_ Allow mocking the `goto` function returned by `useNavigate` hook. |\n| loaders? | | Array<[QwikRouterMockLoaderProp](#qwikroutermockloaderprop)<any>> | _(Optional)_ Allow mocking data for loaders defined with `routeLoader$` function. ``` [ { loader: useProductData, data: { product: { name: 'Test Product' } }, }, ]; ``` |\n| params? | | Record<string, string> | _(Optional)_ Allow mocking the route params returned by `useLocation` hook. |\n| url? | | string | _(Optional)_ Allow mocking the url returned by `useLocation` hook. Default: `http://localhost/` |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikRouterMockProvider\n\n```typescript\nQwikRouterMockProvider: import(\"@qwik.dev/core\").Component<QwikRouterMockProps>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikRouterProps\n\n```typescript\nexport interface QwikRouterProps\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| viewTransition? | | boolean | _(Optional)_ Enable the ViewTransition API on SPA navigation. Opt-in: set to `true` to enable. Default: `false` |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## QwikRouterProvider\n\nThis is a wrapper around the `useQwikRouter()` hook. We recommend using the hook instead of this component, unless you have a good reason to make your root component reactive.\n\n```typescript\nQwikRouterProvider: import(\"@qwik.dev/core\").Component<QwikRouterProps>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## RendererOptions\n\n```typescript\nexport type RendererOptions = Omit<RenderToStreamOptions, \"serverData\"> & {\n serverData: ServerData;\n};\n```\n\n**References:** [ServerData](#serverdata)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/create-renderer.ts)\n\n## RendererOutputOptions\n\n```typescript\nexport type RendererOutputOptions = Omit<\n RenderToStreamOptions,\n \"serverData\"\n> & {\n serverData: ServerData & {\n documentHead?: DocumentHeadValue;\n } & Record<string, unknown>;\n};\n```\n\n**References:** [ServerData](#serverdata), [DocumentHeadValue](#documentheadvalue)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/create-renderer.ts)\n\n## ResolvedDocumentHead\n\n```typescript\nexport type ResolvedDocumentHead<\n FrontMatter extends Record<string, any> = Record<string, unknown>,\n> = Required<DocumentHeadValue<FrontMatter>> & {\n readonly manifestHash: string;\n};\n```\n\n**References:** [DocumentHeadValue](#documentheadvalue)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## routeAction$\n\nDefine a route action that handles form submissions or programmatic invocations.\n\nActions run on the server when submitted from the client. The result is returned as an `ActionStore` with `.value` for success data and `.error` for errors (including validation errors from `zod$`/`valibot$` where `.fieldErrors` etc. are accessible directly on `.error`).\n\nBy default, after an action completes, ALL current route loaders are invalidated on the client and re-fetched as needed (so that the browser cache is correct). This can be controlled with:\n\n- `invalidate: [loader1, loader2]`: Only invalidate specific loaders. The client re-fetches them individually. Other loaders keep their current data. - `invalidate: []`: No loaders are invalidated. The action response only contains the action result. Use this when the action doesn't affect any loader data.\n\nThe `strictLoaders` Vite plugin option applies `invalidate: []` globally for all actions that don't specify an explicit `invalidate` option.\n\n```typescript\nrouteAction$: ActionConstructor;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/server-functions.ts)\n\n## routeActionQrl\n\nHoisted function declarations (not consts) on purpose, like `routeLoaderQrl`: the app's route modules call these factories during their own evaluation, which a bundle may run before this module, where a `const` binding would throw a TDZ ReferenceError.\n\n```typescript\nexport declare function routeActionQrl(\n actionQrl: QRL<(form: JSONObject, event: RequestEventAction) => unknown>,\n ...rest: (ActionOptions | DataValidator)[]\n): {\n (): Editable<ActionStore<unknown, unknown>>;\n __brand: \"server_action\";\n __validators: DataValidator[];\n __qrl: QRL<(form: JSONObject, event: RequestEventAction) => unknown>;\n __id: string;\n __invalidate: string[] | undefined;\n};\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| actionQrl | QRL<(form: [JSONObject](#jsonobject), event: RequestEventAction) => unknown> | |\n| rest | ([ActionOptions](#actionoptions) \\\\| [DataValidator](#datavalidator))[] | |\n\n**Returns:**\n\n\\{ (): [Editable](#editable)&lt;[ActionStore](#actionstore)&lt;unknown, unknown&gt;&gt;; \\_\\_brand: \"server_action\"; \\_\\_validators: [DataValidator](#datavalidator)[]; \\_\\_qrl: QRL&lt;(form: [JSONObject](#jsonobject), event: RequestEventAction) =&gt; unknown&gt;; \\_\\_id: string; \\_\\_invalidate: string[] \\| undefined; }\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/server-functions.ts)\n\n## RouteConfig\n\nUnified route configuration export. Groups head, eTag, and cacheKey with the same resolution rules as DocumentHead: can be a static object or a function receiving DocumentHeadProps.\n\nWhen a module exports `routeConfig`, the separate `head`, `eTag`, and `cacheKey` exports are ignored for that module.\n\n```typescript\nexport type RouteConfig =\n | RouteConfigValue\n | ((props: DocumentHeadProps) => RouteConfigValue);\n```\n\n**References:** [RouteConfigValue](#routeconfigvalue), [DocumentHeadProps](#documentheadprops)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## RouteConfigValue\n\nThe value shape returned by a routeConfig export (object form or function return).\n\n```typescript\nexport interface RouteConfigValue\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| cacheKey? | `readonly` | [CacheKeyFn](#cachekeyfn) | _(Optional)_ |\n| eTag? | `readonly` | [ContentModuleETag](#contentmoduleetag) | _(Optional)_ |\n| head? | `readonly` | [DocumentHeadValue](#documentheadvalue) | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## RouteData\n\nA nested route trie structure. The root represents `/` and each level represents a URL segment.\n\nKeys starting with a single `_` are metadata; all other keys are child route segments. A static segment that starts with `_` is stored with an extra `_` (`_drafts` → `__drafts`).\n\n- Use `_W` as the key for a single dynamic segment (param); `_P` on that node names the param. - Use `_A` as the key for a rest/catch-all segment; `_P` on that node names the param. - For infix params like `pre[slug]post`, use `_W` with `_0` (prefix) and `_9` (suffix). - Use `_M` for an array of group (pathless layout) nodes, sorted by group name.\n\nExact segments match case-insensitively. When several routes match, the most specific wins, compared segment by segment: an exact segment beats `_W` (with optional prefix/suffix), which beats `_A`. When no route matches, the closest `_E` (error.tsx) or `_4` (404.tsx) loader in the ancestor chain is used to render the error page.\n\n```typescript\nexport interface RouteData\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| \\_0? | | string | _(Optional)_ Prefix for infix params (e.g. \"pre\" for `pre[slug]post`) — only on `_W` nodes |\n| \\_4? | | ContentModuleLoader \\\\| ModuleLoader[] | _(Optional)_ Not-found (404) boundary: single loader (runtime prepends layouts) or override chain (`404@layout`/`!`). |\n| \\_9? | | string | _(Optional)_ Suffix for infix params (e.g. \"post\" for `pre[slug]post`) — only on `_W` nodes |\n| \\_B? | | string[] | _(Optional)_ The JS bundle names for this route (SSR only) |\n| \\_D? | | string[] | _(Optional)_ Page loader hashes; override pages include their selected layouts and plugins. |\n| \\_E? | | ContentModuleLoader \\\\| ModuleLoader[] | _(Optional)_ Error (error.tsx) boundary, same single-or-override-chain shape as `_4`. |\n| \\_G? | | string | _(Optional)_ Rewrite/goto target path. Matcher re-walks trie from root using this path's keys. |\n| \\_I? | | ContentModuleLoader \\\\| ModuleLoader[] | _(Optional)_ This node's index/page loader. Single = normal (runtime prepends gathered \\_L). Array = override (layout stop / named layout — IS the complete chain). |\n| \\_L? | | ContentModuleLoader | _(Optional)_ This node's layout loader (single). Runtime accumulates these during trie traversal. |\n| \\_M? | | [RouteData](#routedata)[] | _(Optional)_ Group (pathless layout) nodes merged into this level, sorted by group name |\n| \\_N? | | MenuModuleLoader | _(Optional)_ Menu loader for this subtree (from menu.md). Runtime uses nearest ancestor during traversal. |\n| \\_P? | | string | _(Optional)_ The parameter name when this node is reached via `_W` or `_A` from the parent |\n| \\_R? | | string[] | _(Optional)_ Inherited layout and server plugin routeLoader$ hashes. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## routeLoader$\n\nDefine a route loader that fetches data before the route renders.\n\nRoute loaders run on the server during SSR and return data as a `ComputedSignal`. On the client, loaders automatically re-fetch when the route changes (SPA navigation). Each loader gets its own JSON endpoint (`q-loader-{id}.{hash}.json`), so only the loaders present on the target route are fetched.\n\n\\*\\*Important:\\*\\* Route loader data uses Qwik's custom serialization format, not standard JSON. This means the data supports features like circular references, Dates, and other non-JSON types, but it cannot be consumed by external clients expecting plain JSON.\n\n\\#\\# Options\n\n- `search: string[]`: Allowlist of URL search params the loader depends on. Only listed params are sent in the request and changes to other params are ignored. During SSR and loader JSON requests, the loader's request event is filtered to those params too. `search: []` means no search params are sent and only route path changes trigger a re-fetch. - `eTag`: Enable ETag-based caching. Can be `true` (auto-hash), a string, or a function. - `cacheControl`: Cache-Control for loader JSON responses; the browser HTTP cache controls client-side freshness. `'immutable'` additionally lets SSG write the loader file.\n\nThe `strictLoaders` Vite plugin option applies `search: []` globally for all loaders that don't specify an explicit `search` option.\n\n```typescript\nrouteLoader$: LoaderConstructor;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/route-loaders.ts)\n\n## RouteLocation\n\n```typescript\nexport interface RouteLocation\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| isNavigating | `readonly` | boolean | |\n| params | `readonly` | Readonly<Record<string, string>> | |\n| prevUrl | `readonly` | URL \\\\| undefined | |\n| url | `readonly` | URL | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## RouteNavigate\n\n```typescript\nexport type RouteNavigate = QRL<\n (\n path?: string | number | URL,\n options?:\n | {\n type?: Exclude<NavigationType, \"initial\">;\n forceReload?: boolean;\n replaceState?: boolean;\n scroll?: boolean;\n }\n | boolean,\n ) => Promise<void>\n>;\n```\n\n**References:** [NavigationType](#navigationtype_2)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## RouterOutlet\n\n```typescript\nRouterOutlet: import(\"@qwik.dev/core\").Component<unknown>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/router-outlet-component.tsx)\n\n## server$\n\n```typescript\nserver$: <T extends ServerFunction>(\n qrl: T,\n options?: ServerConfig | undefined,\n) => ServerQRL<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | T | |\n| options | ServerConfig \\\\| undefined | _(Optional)_ |\n\n**Returns:**\n\n[ServerQRL](#serverqrl)&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/server-functions.ts)\n\n## ServerData\n\nThe server data that is provided by Qwik Router during SSR rendering. It can be retrieved with `useServerData(key)` in the server, but it is not available in the client.\n\n```typescript\nexport type ServerData = {\n url: string;\n requestHeaders: Record<string, string>;\n renderMode: \"static\" | \"server\";\n locale: string | undefined;\n nonce: string | undefined;\n containerAttributes: Record<string, string> & {\n [Q_ROUTE]: string;\n };\n qwikrouter: QwikRouterEnvData;\n};\n```\n\n**References:** [Q_ROUTE](#q_route), [QwikRouterEnvData](#qwikrouterenvdata)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ServerFunction\n\n```typescript\nexport type ServerFunction = {\n (this: RequestEventBase, ...args: any[]): any;\n options?: ServerConfig;\n};\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ServerQRL\n\nYou can pass an AbortSignal as the first argument of a `server$` function and it will use it to abort the fetch when fired.\n\n```typescript\nexport type ServerQRL<T extends ServerFunction> = QRL<\n | ((abort: AbortSignal, ...args: Parameters<T>) => ReturnType<T>)\n | ((...args: Parameters<T>) => ReturnType<T>)\n>;\n```\n\n**References:** [ServerFunction](#serverfunction)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ServiceWorkerRegister\n\nLoads the service workers that are defined in the routes. Any file named `service-worker.*` (all JS extensions are allowed) will be picked up, bundled into a separate file, and registered as a service worker.\n\nQwik 1.14.0 and above now use `<link rel=\"modulepreload\">` by default. If you didn't add custom service-worker logic, you should remove your service-worker.ts file(s) for the `ServiceWorkerRegister` Component to actually unregister the service-worker.js and delete its related cache. Make sure to keep the `ServiceWorkerRegister` Component in your app (without any service-worker.ts file) as long as you want to unregister the service-worker.js for your users.\n\n```typescript\nServiceWorkerRegister: (props: { nonce?: string }) => JSXOutput;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| props | \\{ nonce?: string; } | |\n\n**Returns:**\n\nJSXOutput\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/sw-component.tsx)\n\n## StaticGenerate\n\n```typescript\nexport interface StaticGenerate\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| params? | | [PathParams](#pathparams)[] | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## StaticGenerateHandler\n\n```typescript\nexport type StaticGenerateHandler = ({\n env,\n}: {\n env: EnvGetter;\n}) => Promise<StaticGenerate> | StaticGenerate;\n```\n\n**References:** [StaticGenerate](#staticgenerate)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## StrictUnion\n\n```typescript\nexport type StrictUnion<T> = Prettify<StrictUnionHelper<T, T>>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## TypedDataValidator\n\n```typescript\nexport type TypedDataValidator = ValibotDataValidator | ZodDataValidator;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## untypedAppUrl\n\n> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n```typescript\nuntypedAppUrl: (\n route: string,\n params?: Record<string, string>,\n paramsPrefix?: string,\n) => string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| route | string | |\n| params | Record<string, string> | _(Optional)_ |\n| paramsPrefix | string | _(Optional)_ |\n\n**Returns:**\n\nstring\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/typed-routes.ts)\n\n## useContent\n\n```typescript\nuseContent: () => import(\"./types\").ContentState;\n```\n\n**Returns:**\n\nimport(\"./types\").ContentState\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/use-functions.ts)\n\n## useDocumentHead\n\nReturns the document head for the current page. The generic type describes the front matter.\n\n```typescript\nuseDocumentHead: <\n FrontMatter extends Record<string, unknown> = Record<string, any>,\n>() => Required<ResolvedDocumentHead<FrontMatter>>;\n```\n\n**Returns:**\n\nRequired&lt;[ResolvedDocumentHead](#resolveddocumenthead)&lt;FrontMatter&gt;&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/use-functions.ts)\n\n## useHttpStatus\n\n```typescript\nuseHttpStatus: () => import(\"./types\").HttpStatus;\n```\n\n**Returns:**\n\nimport(\"./types\").[HttpStatus](#httperrorprops)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/use-functions.ts)\n\n## useLocation\n\n```typescript\nuseLocation: () => RouteLocation;\n```\n\n**Returns:**\n\n[RouteLocation](#routelocation)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/use-functions.ts)\n\n## useNavigate\n\n```typescript\nuseNavigate: () => RouteNavigate;\n```\n\n**Returns:**\n\n[RouteNavigate](#routenavigate)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/use-functions.ts)\n\n## usePreventNavigate$\n\nPrevent navigation attempts. This hook registers a callback that will be called before SPA or browser navigation.\n\nReturn `true` to prevent navigation.\n\n\\#### SPA Navigation\n\nFor Single-Page-App (SPA) navigation (via `<Link />`, `const nav = useNavigate()`, and browser backwards/forwards inside SPA history), the callback will be provided with the target, either a URL or a number. It will only be a number if `nav(number)` was called to navigate forwards or backwards in SPA history.\n\nIf you return a Promise, the navigation will be blocked until the promise resolves.\n\nThis can be used to show a nice dialog to the user, and wait for the user to confirm, or to record the url, prevent the navigation, and navigate there later via `nav(url)`.\n\n\\#### Browser Navigation\n\nHowever, when the user navigates away by clicking on a regular `<a />`, reloading, or moving backwards/forwards outside SPA history, this callback will not be awaited. This is because the browser does not provide a way to asynchronously prevent these navigations.\n\nIn this case, returning returning `true` will tell the browser to show a confirmation dialog, which cannot be customized. You are also not able to show your own `window.confirm()` dialog during the callback, the browser won't allow it. If you return a Promise, it will be considered as `true`.\n\nWhen the callback is called from the browser, no url will be provided. Use this to know whether you can show a dialog or just return `true` to prevent the navigation.\n\n```typescript\nusePreventNavigate$: (qrl: PreventNavigateCallback) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | [PreventNavigateCallback](#preventnavigatecallback) | |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/use-functions.ts)\n\n## useQwikRouter\n\nThis hook initializes Qwik Router, providing the necessary context for it to work.\n\nThis hook should be used once, at the root of your application.\n\n```typescript\nuseQwikRouter: (props?: QwikRouterProps) => void\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| props | [QwikRouterProps](#qwikrouterprops) | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/qwik-router-component.tsx)\n\n## valibot$\n\n> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n```typescript\nvalibot$: ValibotConstructor;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/server-functions.ts)\n\n## validator$\n\n```typescript\nvalidator$: ValidatorConstructor;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/server-functions.ts)\n\n## ValidatorErrorKeyDotNotation\n\n```typescript\nexport type ValidatorErrorKeyDotNotation<T, Prefix extends string = \"\"> =\n IsAny<T> extends true\n ? never\n : T extends object\n ? {\n [K in keyof T & string]: IsAny<T[K]> extends true\n ? never\n : T[K] extends (infer U)[]\n ? IsAny<U> extends true\n ? never\n : U extends object\n ?\n | `${Prefix}${K}[]`\n | ValidatorErrorKeyDotNotation<U, `${Prefix}${K}[].`>\n : `${Prefix}${K}[]`\n : T[K] extends object\n ? ValidatorErrorKeyDotNotation<T[K], `${Prefix}${K}.`>\n : `${Prefix}${K}`;\n }[keyof T & string]\n : never;\n```\n\n**References:** [ValidatorErrorKeyDotNotation](#validatorerrorkeydotnotation)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ValidatorErrorType\n\n```typescript\nexport type ValidatorErrorType<T, U = string> = {\n formErrors: U[];\n fieldErrors: Partial<{\n [K in ValidatorErrorKeyDotNotation<T>]: K extends `${infer _Prefix}[]${infer _Suffix}`\n ? U[]\n : U;\n }>;\n};\n```\n\n**References:** [ValidatorErrorKeyDotNotation](#validatorerrorkeydotnotation)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## ValidatorReturn\n\n```typescript\nexport type ValidatorReturn<T extends Record<string, any> = {}> =\n | ValidatorReturnSuccess\n | ValidatorReturnFail<T>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n\n## zod$\n\n```typescript\nzod$: ZodConstructor;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/server-functions.ts)\n\n## ZodConstructor\n\n```typescript\nexport type ZodConstructor = {\n <T extends z.ZodRawShape>(schema: T): ZodDataValidator<z.ZodObject<T>>;\n <T extends z.ZodRawShape>(\n schema: (zod: typeof z.z, ev: RequestEvent) => T,\n ): ZodDataValidator<z.ZodObject<T>>;\n <T extends z.ZodType>(schema: T): ZodDataValidator<T>;\n <T extends z.ZodType>(\n schema: (zod: typeof z.z, ev: RequestEvent) => T,\n ): ZodDataValidator<T>;\n};\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/runtime/src/types.ts)\n"},{"id":"/api/qwik-server/","title":"@qwik.dev/qwik-server","description":"Server rendering and serialization APIs for rendering Qwik applications outside the browser.","url":"https://next.qwik.dev/api/qwik-server/","content":"# [API](/api.md) › @qwik.dev/core/server\n\n## getQwikBackpatchExecutorScript\n\nProvides the `backpatch-executor.js` executor script as a string.\n\n```typescript\nexport declare function getQwikBackpatchExecutorScript(opts?: {\n debug?: boolean;\n}): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | \\{ debug?: boolean; } | _(Optional)_ |\n\n**Returns:**\n\nstring\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/scripts.ts)\n\n## getQwikLoaderScript\n\nProvides the `qwikloader.js` file as a string. Useful for tooling to inline the qwikloader script into HTML.\n\n```typescript\nexport declare function getQwikLoaderScript(opts?: { debug?: boolean }): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | \\{ debug?: boolean; } | _(Optional)_ |\n\n**Returns:**\n\nstring\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/scripts.ts)\n\n## getQwikPrefetchWorkerScript\n\nProvides the `qwik-prefetch-service-worker.js` file as a string. Useful for tooling to inline the qwik-prefetch-service-worker script into HTML.\n\n```typescript\nexport declare function getQwikPrefetchWorkerScript(opts?: {\n debug?: boolean;\n}): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | \\{ debug?: boolean; } | _(Optional)_ |\n\n**Returns:**\n\nstring\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/scripts.ts)\n\n## InOrderAuto\n\n```typescript\nexport interface InOrderAuto\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| maximumChunk? | | number | _(Optional)_ |\n| maximumInitialChunk? | | number | _(Optional)_ |\n| strategy | | 'auto' | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## InOrderDisabled\n\n```typescript\nexport interface InOrderDisabled\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| strategy | | 'disabled' | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## InOrderStreaming\n\n```typescript\nexport type InOrderStreaming = InOrderAuto | InOrderDisabled | InOrderDirect;\n```\n\n**References:** [InOrderAuto](#inorderauto), [InOrderDisabled](#inorderdisabled)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## OutOfOrderStreaming\n\n```typescript\nexport type OutOfOrderStreaming = boolean;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## PrefetchResource\n\n```typescript\nexport interface PrefetchResource\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| imports | | [PrefetchResource](#prefetchresource)[] | |\n| url | | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## PreloaderOptions\n\n```typescript\nexport interface PreloaderOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| maxIdlePreloads? | | number | _(Optional)_ Maximum number of simultaneous preload links that the preloader will maintain. If you set this higher, the browser will have all JS files in memory sooner, but it will contend with other resource downloads. Furthermore, if a bundle suddenly becomes more likely, it will have to wait longer to be preloaded. Bundles that reach 100% probability (static imports of other bundles) will always be preloaded immediately, no limit. Defaults to `25` |\n| ssrPreloads? | | number | _(Optional)_ Maximum number of preload links to add during SSR. These instruct the browser to preload likely bundles before the preloader script is active. This most likely includes the core and the preloader script itself. Setting this to 0 will disable all preload links. Preload links can delay LCP, which is a Core Web Vital, but they can improve TTI, which is not a Core Web Vital but more noticeable to the user. Defaults to `0`, so speculative preloading starts once the page is loaded. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## QwikLoaderOptions\n\n```typescript\nexport type QwikLoaderOptions =\n | \"module\"\n | \"inline\"\n | \"never\"\n | {\n include?: \"always\" | \"never\" | \"auto\";\n position?: \"top\" | \"bottom\";\n };\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## Render\n\n```typescript\nexport type Render = RenderToString | RenderToStream;\n```\n\n**References:** [RenderToString](#rendertostring-type-alias), [RenderToStream](#rendertostream-type-alias)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## RenderOptions\n\n```typescript\nexport interface RenderOptions extends SerializeDocumentOptions\n```\n\n**Extends:** [SerializeDocumentOptions](#serializedocumentoptions)\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| base? | | string \\\\| ((options: [RenderOptions](#renderoptions)) => string) | _(Optional)_ Specifies the root of the JS files of the client build. Setting a base, will cause the render of the `q:base` attribute in the `q:container` element. |\n| containerAttributes? | | Record<string, string> | _(Optional)_ |\n| containerTagName? | | string | _(Optional)_ When set, the app is serialized into a fragment. And the returned html is not a complete document. Defaults to `html` |\n| locale? | | string \\\\| ((options: [RenderOptions](#renderoptions)) => string) | _(Optional)_ Language to use when rendering the document. |\n| preloader? | | [PreloaderOptions](#preloaderoptions) \\\\| false | _(Optional)_ Specifies how preloading is handled. This ensures that code is instantly available when needed. |\n| qwikLoader? | | [QwikLoaderOptions](#qwikloaderoptions) | _(Optional)_ Specifies how the Qwik Loader is included in the document. This enables interactivity and lazy loading. `module`: Use a `` tag to load the Qwik Loader. Subsequent page loads will have the script cached and instantly running. `inline`: This embeds the Qwik Loader script directly in the document. This adds about 3kB before compression, which typically is reduced to about 1.6kB with gzip. `never`: Do not include the Qwik Loader script. This is mostly useful when embedding multiple containers on the same page. Defaults to `module`. Note that the Qwik Loader is absolutely required for Qwik to work. There must be an instance of it loaded for any interactivity to happen. |\n| serverData? | | Record<string, any> | _(Optional)_ Metadata that can be retrieved during SSR with `useServerData()`. |\n| snapshot? | | boolean | _(Optional)_ Defaults to `true` |\n| statePrewarm? | | number \\\\| false | _(Optional)_ Root-count threshold for eager yielded state prewarm during client resume. Defaults to `false`, keeping state fully lazy. Set to a number to enable eager prewarm when serialized state has at least that many roots. |\n| transformError? | | (error: unknown) => Error \\\\| undefined \\\\| null \\\\| void | _(Optional)_ Server-only. Projects a thrown error into the `Error` a `` fallback displays during SSR; `onError$` still receives the original. It never runs on the client, where a re-derived fallback shows the error as thrown. Return an `Error` to project it, or `undefined`/`null` to decline; any other return, or a throw, redacts to the generic error. It is called synchronously, so it cannot be `async`: a returned promise redacts every error. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## RenderResult\n\n```typescript\nexport interface RenderResult\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| isStatic | | boolean | |\n| manifest? | | ServerQwikManifest | _(Optional)_ |\n| snapshotResult? | | SnapshotResult \\\\| undefined | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## renderToStream\n\n```typescript\nexport type RenderToStream = (\n opts: RenderToStreamOptions,\n) => Promise<RenderToStreamResult>;\n```\n\n**References:** [RenderToStreamOptions](#rendertostreamoptions), [RenderToStreamResult](#rendertostreamresult)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/ssr-render.ts)\n\n## RenderToStream\n\n```typescript\nexport type RenderToStream = (\n opts: RenderToStreamOptions,\n) => Promise<RenderToStreamResult>;\n```\n\n**References:** [RenderToStreamOptions](#rendertostreamoptions), [RenderToStreamResult](#rendertostreamresult)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## RenderToStreamOptions\n\n```typescript\nexport interface RenderToStreamOptions extends RenderOptions\n```\n\n**Extends:** [RenderOptions](#renderoptions)\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| onBeforeFirstFlush? | | (info: \\{ hasCaughtError: boolean; }) => void | _(Optional)_ Called synchronously just before the first chunk is written — the last moment response headers can still change. `hasCaughtError` is true when a `` already swapped in its fallback during SSR. |\n| stream | | StreamWriter | |\n| streaming? | | [StreamingOptions](#streamingoptions) | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## RenderToStreamResult\n\n```typescript\nexport interface RenderToStreamResult extends RenderResult\n```\n\n**Extends:** [RenderResult](#renderresult)\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| flushes | | number | |\n| hasCaughtError? | | boolean | _(Optional)_ True when a `` caught during the render, no matter where in the stream. |\n| size | | number | |\n| timing | | \\{ firstFlush: number; render: number; snapshot: number; } | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## renderToString\n\n```typescript\nexport type RenderToString = (\n opts: RenderToStringOptions,\n) => Promise<RenderToStringResult>;\n```\n\n**References:** [RenderToStringOptions](#rendertostringoptions), [RenderToStringResult](#rendertostringresult)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/ssr-render.ts)\n\n## RenderToString\n\n```typescript\nexport type RenderToString = (\n opts: RenderToStringOptions,\n) => Promise<RenderToStringResult>;\n```\n\n**References:** [RenderToStringOptions](#rendertostringoptions), [RenderToStringResult](#rendertostringresult)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## RenderToStringOptions\n\n```typescript\nexport interface RenderToStringOptions extends RenderOptions\n```\n\n**Extends:** [RenderOptions](#renderoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## RenderToStringResult\n\n```typescript\nexport interface RenderToStringResult extends RenderResult\n```\n\n**Extends:** [RenderResult](#renderresult)\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| html | | string | |\n| timing | | \\{ firstFlush: number; render: number; snapshot: number; } | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## resolveManifest\n\nMerges a given manifest with the built manifest and provides mappings for symbols.\n\n```typescript\nexport declare function resolveManifest(\n manifest?: Partial<QwikManifest | ResolvedManifest> | undefined,\n): ResolvedManifest | undefined;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| manifest | Partial<QwikManifest \\\\| ResolvedManifest> \\\\| undefined | _(Optional)_ |\n\n**Returns:**\n\nResolvedManifest \\| undefined\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/ssr-render.ts)\n\n## SerializeDocumentOptions\n\n```typescript\nexport interface SerializeDocumentOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| debug? | | boolean | _(Optional)_ |\n| manifest? | | Partial<QwikManifest \\\\| ResolvedManifest> | _(Optional)_ |\n| symbolMapper? | | SymbolMapperFn | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## setServerPlatform\n\n```typescript\nexport declare function setServerPlatform(\n manifest?: Partial<QwikManifest | ResolvedManifest>,\n): Promise<void>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| manifest | Partial<QwikManifest \\\\| ResolvedManifest> | _(Optional)_ |\n\n**Returns:**\n\nPromise&lt;void&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/index.ts)\n\n## StreamingOptions\n\n```typescript\nexport interface StreamingOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| inOrder? | | [InOrderStreaming](#inorderstreaming) | _(Optional)_ |\n| outOfOrder? | | [OutOfOrderStreaming](#outoforderstreaming) | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## versions\n\n```typescript\nversions: {\n readonly qwik: string;\n readonly qwikDom: string;\n}\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/utils.ts)\n"},{"id":"/api/qwik-worker/","title":"@qwik.dev/core/worker","description":"Worker API reference for `worker$()` and `workerQrl()`, which run Qwik functions away from the main browser thread.","url":"https://next.qwik.dev/api/qwik-worker/","content":"# [API](/api.md) › @qwik.dev/core/worker\n\n## worker$\n\n```typescript\nworker$: <T extends WorkerFunction>(qrl: T) => QRL<T>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qrl | T | |\n\n**Returns:**\n\nQRL&lt;T&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/web-worker/worker-qrl.ts)\n\n## WorkerConstructorQRL\n\n```typescript\nexport interface WorkerConstructorQRL\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/web-worker/worker-qrl.ts)\n\n## WorkerFunction\n\n```typescript\nexport interface WorkerFunction\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/web-worker/worker-qrl.ts)\n\n## workerQrl\n\n```typescript\nworkerQrl: WorkerConstructorQRL;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/web-worker/worker-qrl.ts)\n"},{"id":"/api/qwik-optimizer/","title":"@qwik.dev/qwik-optimizer","description":"Optimizer API reference for the compiler and transform pipeline that powers lazy loading.","url":"https://next.qwik.dev/api/qwik-optimizer/","content":"# [API](/api.md) › @qwik.dev/core/optimizer\n\n## basename\n\n```typescript\nbasename(path: string, ext?: string): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| path | string | |\n| ext | string | _(Optional)_ |\n\n**Returns:**\n\nstring\n\n## blockSSR\n\n## BundleGraphAdder\n\nA function that returns a map of bundle names to their dependencies.\n\n```typescript\nexport type BundleGraphAdder = (manifest: QwikManifest) => Record<\n string,\n {\n imports?: string[];\n dynamicImports?: string[];\n }\n>;\n```\n\n**References:** [QwikManifest](#qwikmanifest)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/bundle-graph.ts)\n\n## catchBoundary\n\n## ComponentEntryStrategy\n\n```typescript\nexport interface ComponentEntryStrategy\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| manual? | | Record<string, string> | _(Optional)_ |\n| type | | 'component' | |\n\n## createOptimizer\n\n```typescript\ncreateOptimizer: (optimizerOptions?: OptimizerOptions) => Promise<Optimizer>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| optimizerOptions | [OptimizerOptions](#optimizeroptions) | _(Optional)_ |\n\n**Returns:**\n\nPromise&lt;[Optimizer](#optimizer)&gt;\n\n## DecoratorOptions\n\n```typescript\nexport interface DecoratorOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| emitDecoratorMetadata? | | boolean | _(Optional)_ Tsconfig's `emitDecoratorMetadata` |\n| legacy? | | boolean | _(Optional)_ Tsconfig's `experimentalDecorators` |\n\n## Diagnostic\n\n```typescript\nexport interface Diagnostic\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| category | | [DiagnosticCategory](#diagnosticcategory) | |\n| code | | string \\\\| null | |\n| file | | string | |\n| highlights | | [SourceLocation](#sourcelocation)[] \\\\| null | |\n| message | | string | |\n| scope | | string | |\n| suggestions | | string[] \\\\| null | |\n\n## DiagnosticCategory\n\n```typescript\nexport type DiagnosticCategory = \"error\" | \"warning\" | \"sourceError\";\n```\n\n## dirname\n\n```typescript\ndirname(path: string): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| path | string | |\n\n**Returns:**\n\nstring\n\n## each\n\n## EmitMode\n\n```typescript\nexport type EmitMode = \"dev\" | \"prod\" | \"lib\" | \"hmr\";\n```\n\n## EntryStrategy\n\n```typescript\nexport type EntryStrategy =\n | InlineEntryStrategy\n | HoistEntryStrategy\n | SingleEntryStrategy\n | HookEntryStrategy\n | SegmentEntryStrategy\n | ComponentEntryStrategy\n | SmartEntryStrategy;\n```\n\n**References:** [InlineEntryStrategy](#inlineentrystrategy), [HoistEntryStrategy](#hoistentrystrategy), [SingleEntryStrategy](#singleentrystrategy), [HookEntryStrategy](#hookentrystrategy), [SegmentEntryStrategy](#segmententrystrategy), [ComponentEntryStrategy](#componententrystrategy), [SmartEntryStrategy](#smartentrystrategy)\n\n## ExperimentalFeatures\n\nUse `__EXPERIMENTAL__.x` to check if feature `x` is enabled. It will be replaced with `true` or `false` via an exact string replacement.\n\nAdd experimental features to this enum definition.\n\n```typescript\nexport declare enum ExperimentalFeatures\n```\n\n| Member | Value | Description |\n| --- | --- | --- |\n| blockSSR | `\"blockSSR\"` | Enable the `blockSSR: false` route loader option |\n| catchBoundary | `\"catchBoundary\"` | Enable the Catch primitive |\n| each | `\"each\"` | Enable the Each keyed-list primitive |\n| insights | `\"insights\"` | Enable the ability to use the Qwik Insights vite plugin and `` component |\n| noSPA | `\"noSPA\"` | Disable SPA navigation handler in Qwik Router |\n| pendingBoundary | `\"pendingBoundary\"` | Enable the Pending fallback primitive |\n| show | `\"show\"` | Enable the Show conditional primitive |\n| valibot | `\"valibot\"` | Enable the Valibot form validation |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/plugin.ts)\n\n## extname\n\n```typescript\nextname(path: string): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| path | string | |\n\n**Returns:**\n\nstring\n\n## format\n\n```typescript\nformat(pathObject: {\n root: string;\n dir: string;\n base: string;\n ext: string;\n name: string;\n }): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| pathObject | \\{ root: string; dir: string; base: string; ext: string; name: string; } | |\n\n**Returns:**\n\nstring\n\n## GlobalInjections\n\n```typescript\nexport interface GlobalInjections\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| attributes? | | \\{ [key: string]: string; } | _(Optional)_ |\n| location | | 'head' \\\\| 'body' | |\n| tag | | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## HoistEntryStrategy\n\n```typescript\nexport interface HoistEntryStrategy\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| type | | 'hoist' | |\n\n## HookEntryStrategy\n\n> Warning: This API is now obsolete.\n>\n> Use SegmentStrategy instead\n\n```typescript\nexport interface HookEntryStrategy\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| manual? | | Record<string, string> | _(Optional)_ |\n| type | | 'hook' | |\n\n## InlineEntryStrategy\n\n```typescript\nexport interface InlineEntryStrategy\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| type | | 'inline' | |\n\n## insights\n\n## isAbsolute\n\n```typescript\nisAbsolute(path: string): boolean;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| path | string | |\n\n**Returns:**\n\nboolean\n\n## join\n\n```typescript\njoin(...paths: string[]): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| paths | string[] | |\n\n**Returns:**\n\nstring\n\n## MinifyMode\n\n```typescript\nexport type MinifyMode = \"simplify\" | \"none\";\n```\n\n## normalize\n\n```typescript\nnormalize(path: string): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| path | string | |\n\n**Returns:**\n\nstring\n\n## noSPA\n\n## Optimizer\n\n```typescript\nexport interface Optimizer\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| sys | | [OptimizerSystem](#optimizersystem) | Optimizer system use. This can be updated with a custom file system. |\n\n| Method | Description |\n| --- | --- |\n| [transformModules(opts)](#optimizer-transformmodules) | Transforms the input code string, does not access the file system. |\n\n## OptimizerOptions\n\n```typescript\nexport interface OptimizerOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| \\_optimizer? | | unknown | _(Optional)_ |\n| binding? | | any | _(Optional)_ |\n| inlineStylesUpToBytes? | | number | _(Optional)_ Inline the global styles if they're smaller than this |\n| sourcemap? | | boolean | _(Optional)_ Enable sourcemaps |\n| sys? | | [OptimizerSystem](#optimizersystem) | _(Optional)_ |\n| tsOptimizer? | | boolean | _(Optional)_ Use the TypeScript optimizer (`@qwik.dev/ts-optimizer`) instead of the Rust one. The `QWIK_OPTIMIZER` environment variable (`ts` or `rust`) overrides this, so a project can be built or tested on the other optimizer without changing its config. Default `false` |\n\n## OptimizerSystem\n\n```typescript\nexport interface OptimizerSystem\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| cwd | | () => string | |\n| dynamicImport | | (path: string) => Promise<any> | |\n| env | | [SystemEnvironment](#systemenvironment) | |\n| getInputFiles? | | (rootDir: string) => Promise<[TransformModuleInput](#transformmoduleinput)[]> | _(Optional)_ |\n| os | | string | |\n| path | | [Path](#path) | |\n| strictDynamicImport | | (path: string) => Promise<any> | |\n\n## parse\n\n```typescript\nparse(path: string): {\n root: string;\n dir: string;\n base: string;\n ext: string;\n name: string;\n };\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| path | string | |\n\n**Returns:**\n\n\\{ root: string; dir: string; base: string; ext: string; name: string; }\n\n## Path\n\n```typescript\nexport interface Path\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| delimiter | `readonly` | string | |\n| posix | `readonly` | [Path](#path) | |\n| sep | `readonly` | string | |\n| win32 | `readonly` | null | |\n\n| Method | Description |\n| --- | --- |\n| [basename(path, ext)](#path-basename) | |\n| [dirname(path)](#path-dirname) | |\n| [extname(path)](#path-extname) | |\n| [format(pathObject)](#path-format) | |\n| [isAbsolute(path)](#path-isabsolute) | |\n| [join(paths)](#path-join) | |\n| [normalize(path)](#path-normalize) | |\n| [parse(path)](#path-parse) | |\n| [relative(from, to)](#path-relative) | |\n| [resolve(paths)](#path-resolve) | |\n\n## pendingBoundary\n\n## QwikAsset\n\n```typescript\nexport interface QwikAsset\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| name | | string \\\\| undefined | Name of the asset |\n| size | | number | Size of the asset |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## QwikBuildMode\n\n```typescript\nexport type QwikBuildMode = \"production\" | \"development\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/plugin.ts)\n\n## QwikBuildTarget\n\n```typescript\nexport type QwikBuildTarget = \"client\" | \"ssr\" | \"lib\" | \"test\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/plugin.ts)\n\n## QwikBundle\n\n```typescript\nexport interface QwikBundle\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| dynamicImports? | | string[] | _(Optional)_ Dynamic imports |\n| imports? | | string[] | _(Optional)_ Direct imports |\n| interactivity? | | number | _(Optional)_ Interactivity score of the bundle |\n| origins? | | string[] | _(Optional)_ Source files of the bundle |\n| qrlImports? | | string[] | _(Optional)_ Dynamic imports of qrl segments, the subset of `dynamicImports` the preloader follows |\n| size | | number | Size of the bundle |\n| symbols? | | string[] | _(Optional)_ Symbols in the bundle |\n| total | | number | Total size of this bundle's static import graph |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## QwikBundleGraph\n\nBundle graph.\n\nFormat: [ 'bundle-a.js', 3, 5 // Depends on 'bundle-b.js' and 'bundle-c.js' 'bundle-b.js', 5, // Depends on 'bundle-c.js' 'bundle-c.js', ]\n\n```typescript\nexport type QwikBundleGraph = Array<string | number>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## QwikManifest\n\nThe metadata of the build. One of its uses is storing where QRL symbols are located.\n\n```typescript\nexport interface QwikManifest\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| assets? | | \\{ [fileName: string]: [QwikAsset](#qwikasset); } | _(Optional)_ All assets. The key is the fileName relative to the rootDir |\n| bundleGraph? | | [QwikBundleGraph](#qwikbundlegraph) | _(Optional)_ All bundles in a compact graph format with probabilities |\n| bundleGraphAsset? | | string | _(Optional)_ The bundle graph fileName |\n| bundles | | \\{ [fileName: string]: [QwikBundle](#qwikbundle); } | All code bundles, used to know the import graph. The key is the bundle fileName relative to \"build/\" |\n| core? | | string | _(Optional)_ The Qwik core bundle fileName |\n| injections? | | [GlobalInjections](#globalinjections)[] | _(Optional)_ CSS etc to inject in the document head |\n| manifestHash | | string | Content hash of the manifest, if this changes, the code changed |\n| mapping | | \\{ [symbolName: string]: string; } | Where QRLs are located. The key is the symbol name, the value is the bundle fileName |\n| options? | | \\{ target?: string; buildMode?: string; entryStrategy?: \\{ type: [EntryStrategy](#entrystrategy)['type']; }; } | _(Optional)_ The options used to build the manifest |\n| platform? | | \\{ [name: string]: string; } | _(Optional)_ The platform used to build the manifest |\n| preloader? | | string | _(Optional)_ The preloader bundle fileName |\n| qwikLoader? | | string | _(Optional)_ The Qwik loader bundle fileName |\n| symbols | | \\{ [symbolName: string]: [QwikSymbol](#qwiksymbol); } | QRL symbols |\n| version | | string | The version of the manifest |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## qwikRolldown\n\n```typescript\nexport declare function qwikRolldown(\n qwikRolldownOpts?: QwikRolldownPluginOptions,\n): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qwikRolldownOpts | [QwikRolldownPluginOptions](#qwikrolldownpluginoptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/rolldown.ts)\n\n## QwikRolldownPluginOptions\n\n```typescript\nexport interface QwikRolldownPluginOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| buildMode? | | [QwikBuildMode](#qwikbuildmode) | _(Optional)_ Build `production` or `development`. Default `development` |\n| csr? | | boolean | _(Optional)_ |\n| debug? | | boolean | _(Optional)_ Prints verbose Qwik plugin debug logs. Default `false` |\n| entryStrategy? | | [EntryStrategy](#entrystrategy) | _(Optional)_ The Qwik entry strategy to use while building for production. During development the type is always `segment`. Default `{ type: \"smart\" }`) |\n| experimental? | | (keyof typeof [ExperimentalFeatures](#experimentalfeatures))[] | _(Optional)_ Experimental features. These can come and go in patch releases, and their API is not guaranteed to be stable between releases. |\n| lint? | | boolean | _(Optional)_ Run eslint on the source files for the ssr build or dev server. This can slow down startup on large projects. Defaults to `true` |\n| manifestInput? | | [QwikManifest](#qwikmanifest) | _(Optional)_ The SSR build requires the manifest generated during the client build. The `manifestInput` option can be used to manually provide a manifest. Default `undefined` |\n| manifestOutput? | | (manifest: [QwikManifest](#qwikmanifest)) => Promise<void> \\\\| void | _(Optional)_ The client build will create a manifest and this hook is called with the generated build data. Default `undefined` |\n| optimizerOptions? | | [OptimizerOptions](#optimizeroptions) | _(Optional)_ |\n| rootDir? | | string | _(Optional)_ The root of the application, which is commonly the same directory as `package.json` and `rollup.config.js`. Default `process.cwd()` |\n| srcDir? | | string | _(Optional)_ The source directory to find all the Qwik components. Since Qwik does not have a single input, the `srcDir` is used to recursively find Qwik files. Default `src` |\n| srcInputs? | | [TransformModuleInput](#transformmoduleinput)[] \\\\| null | _(Optional)_ Alternative to `srcDir`, where `srcInputs` is able to provide the files manually. This option is useful for an environment without a file system, such as a webworker. Default: `null` |\n| target? | | [QwikBuildTarget](#qwikbuildtarget) | _(Optional)_ Target `client` or `ssr`. Default `client` |\n| transformedModuleOutput? | | ((transformedModules: [TransformModule](#transformmodule)[]) => Promise<void> \\\\| void) \\\\| null | _(Optional)_ Hook that's called after the build and provides all of the transformed modules that were used before bundling. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/rolldown.ts)\n\n## qwikRollup\n\n> Warning: This API is now obsolete.\n>\n> Use `qwikRolldown`.\n\nRenamed to `qwikRolldown`.\n\n```typescript\nqwikRollup: typeof qwikRolldown;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/rolldown.ts)\n\n## QwikRollupPluginOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRolldownPluginOptions`.\n\nRenamed to `QwikRolldownPluginOptions`.\n\n```typescript\nexport type QwikRollupPluginOptions = QwikRolldownPluginOptions;\n```\n\n**References:** [QwikRolldownPluginOptions](#qwikrolldownpluginoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/rolldown.ts)\n\n## QwikSymbol\n\n```typescript\nexport interface QwikSymbol\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| canonicalFilename | | string | |\n| captureNames? | | string[] | _(Optional)_ The transformed names of scoped variables, if any |\n| captures | | boolean | Whether the symbol captures a variable |\n| ctxKind | | 'function' \\\\| 'eventHandler' | |\n| ctxName | | string | |\n| displayName | | string | |\n| hash | | string | |\n| loc | | [number, number] | |\n| origin | | string | |\n| paramNames? | | string[] | _(Optional)_ The parameter names if it's a function with parameters |\n| parent | | string \\\\| null | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## qwikVite\n\nThe types for Vite/Rolldown don't allow us to be too specific about the return type. The correct return type is `[QwikVitePlugin, VitePlugin<never>]`, and if you search the plugin by name you'll get the `QwikVitePlugin`.\n\n```typescript\nexport declare function qwikVite(qwikViteOpts?: QwikVitePluginOptions): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| qwikViteOpts | [QwikVitePluginOptions](#qwikvitepluginoptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/vite.ts)\n\n## QwikVitePlugin\n\nThis is the type of the \"pre\" Qwik Vite plugin. `qwikVite` actually returns a tuple of two plugins, but after Vite flattens them, you can find the plugin by name.\n\n```typescript\nexport type QwikVitePlugin = P<QwikVitePluginApi> & {\n name: \"vite-plugin-qwik\";\n};\n```\n\n**References:** [QwikVitePluginApi](#qwikvitepluginapi)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/vite.ts)\n\n## QwikVitePluginApi\n\n```typescript\nexport interface QwikVitePluginApi\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| getClientOutDir | | () => string \\\\| null | |\n| getClientPublicOutDir | | () => string \\\\| null | |\n| getManifest | | () => [QwikManifest](#qwikmanifest) \\\\| null | |\n| getOptimizer | | () => [Optimizer](#optimizer) \\\\| null | |\n| getOptions | | () => NormalizedQwikPluginOptions | |\n| getRootDir | | () => string \\\\| null | |\n| onSegment | | (callback: SegmentCallback) => void | Register a callback that fires for each segment emitted during transform. |\n| registerBundleGraphAdder | | (adder: [BundleGraphAdder](#bundlegraphadder)) => void | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/vite.ts)\n\n## QwikVitePluginOptions\n\n```typescript\nexport type QwikVitePluginOptions =\n | QwikVitePluginCSROptions\n | QwikVitePluginSSROptions;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/plugins/vite.ts)\n\n## relative\n\n```typescript\nrelative(from: string, to: string): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| from | string | |\n| to | string | |\n\n**Returns:**\n\nstring\n\n## resolve\n\n```typescript\nresolve(...paths: string[]): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| paths | string[] | |\n\n**Returns:**\n\nstring\n\n## ResolvedManifest\n\n```typescript\nexport interface ResolvedManifest\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| bundleGraph? | | [QwikBundleGraph](#qwikbundlegraph) | _(Optional)_ |\n| injections? | | [GlobalInjections](#globalinjections)[] | _(Optional)_ |\n| manifest | | [ServerQwikManifest](#serverqwikmanifest) | |\n| mapper | | [SymbolMapper](#symbolmapper) | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## SegmentAnalysis\n\n```typescript\nexport interface SegmentAnalysis\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| canonicalFilename | | string | |\n| captureNames? | | string[] | _(Optional)_ The transformed names of scoped variables, if any |\n| captures | | boolean | |\n| ctxKind | | 'eventHandler' \\\\| 'function' | |\n| ctxName | | string | |\n| displayName | | string | |\n| entry | | string \\\\| null | |\n| extension | | string | |\n| hash | | string | |\n| loc | | [number, number] | |\n| name | | string | |\n| origin | | string | |\n| paramNames? | | string[] | _(Optional)_ The parameter names if it's a function with parameters |\n| parent | | string \\\\| null | |\n\n## SegmentEntryStrategy\n\n```typescript\nexport interface SegmentEntryStrategy\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| manual? | | Record<string, string> | _(Optional)_ |\n| type | | 'segment' | |\n\n## ServerQwikManifest\n\nThe manifest values that are needed for SSR.\n\n```typescript\nexport type ServerQwikManifest = Pick<\n QwikManifest,\n | \"manifestHash\"\n | \"injections\"\n | \"bundleGraph\"\n | \"bundleGraphAsset\"\n | \"mapping\"\n | \"preloader\"\n | \"core\"\n | \"qwikLoader\"\n>;\n```\n\n**References:** [QwikManifest](#qwikmanifest)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## show\n\n## SingleEntryStrategy\n\n```typescript\nexport interface SingleEntryStrategy\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| manual? | | Record<string, string> | _(Optional)_ |\n| type | | 'single' | |\n\n## SmartEntryStrategy\n\n```typescript\nexport interface SmartEntryStrategy\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| manual? | | Record<string, string> | _(Optional)_ |\n| type | | 'smart' | |\n\n## SourceLocation\n\n```typescript\nexport interface SourceLocation\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| endCol | | number | |\n| endLine | | number | |\n| hi | | number | |\n| lo | | number | |\n| startCol | | number | |\n| startLine | | number | |\n\n## SymbolMapper\n\n```typescript\nexport type SymbolMapper = Record<\n string,\n readonly [symbol: string, chunk: string]\n>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## SymbolMapperFn\n\n```typescript\nexport type SymbolMapperFn = (\n symbolName: string,\n mapper: SymbolMapper | undefined,\n parent?: string,\n) => readonly [symbol: string, chunk: string] | undefined;\n```\n\n**References:** [SymbolMapper](#symbolmapper)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-vite/src/types.ts)\n\n## SystemEnvironment\n\n```typescript\nexport type SystemEnvironment =\n | \"node\"\n | \"deno\"\n | \"bun\"\n | \"webworker\"\n | \"browsermain\"\n | \"unknown\";\n```\n\n## TransformModule\n\n```typescript\nexport interface TransformModule\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| code | | string | |\n| imports? | | string[] | _(Optional)_ |\n| isEntry | | boolean | |\n| map | | string \\\\| null | |\n| origPath | | string \\\\| null | |\n| path | | string | |\n| segment | | [SegmentAnalysis](#segmentanalysis) \\\\| null | |\n\n## TransformModuleInput\n\n```typescript\nexport interface TransformModuleInput\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| code | | string | |\n| devPath? | | string | _(Optional)_ |\n| path | | string | |\n\n## transformModules\n\nTransforms the input code string, does not access the file system.\n\n```typescript\ntransformModules(opts: TransformModulesOptions): Promise<TransformOutput>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [TransformModulesOptions](#transformmodulesoptions) | |\n\n**Returns:**\n\nPromise&lt;[TransformOutput](#transformoutput)&gt;\n\n## TransformModulesOptions\n\n```typescript\nexport interface TransformModulesOptions extends TransformOptions\n```\n\n**Extends:** [TransformOptions](#transformoptions)\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| input | | [TransformModuleInput](#transformmoduleinput)[] | |\n\n## TransformOptions\n\n```typescript\nexport interface TransformOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| decorator? | | [DecoratorOptions](#decoratoroptions) | _(Optional)_ Decorator lowering, mirroring tsconfig. Only the TypeScript optimizer applies it. |\n| entryStrategy? | | [EntryStrategy](#entrystrategy) | _(Optional)_ |\n| explicitExtensions? | | boolean | _(Optional)_ |\n| isServer? | | boolean | _(Optional)_ |\n| minify? | | [MinifyMode](#minifymode) | _(Optional)_ |\n| mode? | | [EmitMode](#emitmode) | _(Optional)_ |\n| preserveFilenames? | | boolean | _(Optional)_ |\n| regCtxName? | | string[] | _(Optional)_ |\n| rootDir? | | string | _(Optional)_ |\n| scope? | | string | _(Optional)_ |\n| sourceMaps? | | boolean | _(Optional)_ |\n| srcDir | | string | |\n| stripCtxName? | | string[] | _(Optional)_ |\n| stripEventHandlers? | | boolean | _(Optional)_ |\n| stripExports? | | string[] | _(Optional)_ |\n| transpileJsx? | | boolean | _(Optional)_ |\n| transpileTs? | | boolean | _(Optional)_ |\n\n## TransformOutput\n\n```typescript\nexport interface TransformOutput\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| diagnostics | | [Diagnostic](#diagnostic)[] | |\n| isJsx | | boolean | |\n| isTypeScript | | boolean | |\n| modules | | [TransformModule](#transformmodule)[] | |\n\n## valibot\n"},{"id":"/api/qwik-testing/","title":"@qwik.dev/qwik-testing","description":"Testing helpers and utilities for unit, DOM, and integration-style Qwik tests.","url":"https://next.qwik.dev/api/qwik-testing/","content":"# [API](/api.md) › @qwik.dev/core/testing\n\n## child\n\n```typescript\nchild: HTMLElement;\n```\n\n## createDocument\n\nCreate emulated `Document` for server environment. Does not implement the full browser `document` and `window` API. This api may be removed in the future.\n\n```typescript\nexport declare function createDocument(opts?: MockDocumentOptions): Document;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | MockDocumentOptions | _(Optional)_ |\n\n**Returns:**\n\nDocument\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/document.ts)\n\n## createDOM\n\nCreatePlatform and CreateDocument\n\n```typescript\ncreateDOM: (input?: { html?: string }) =>\n Promise<{\n render: (\n jsxElement: JSXOutput,\n ) => Promise<import(\"@qwik.dev/core\").RenderResult>;\n screen: HTMLElement;\n userEvent: (\n queryOrElement: string | Element | keyof HTMLElementTagNameMap | null,\n eventNameCamel: string | keyof WindowEventMap,\n eventPayload?: any,\n ) => Promise<Event | null>;\n }>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| \\{ html } | (not declared) | _(Optional)_ |\n| input | \\{ html?: string; } | _(Optional)_ |\n\n**Returns:**\n\nPromise&lt;\\{ render: (jsxElement: JSXOutput) =&gt; Promise&lt;import(\"@qwik.dev/core\").RenderResult&gt;; screen: HTMLElement; userEvent: (queryOrElement: string \\| Element \\| keyof HTMLElementTagNameMap \\| null, eventNameCamel: string \\| keyof WindowEventMap, eventPayload?: any) =&gt; Promise&lt;Event \\| null&gt;; }&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/library.ts)\n\n## document\n\n```typescript\ndocument: MockDocument;\n```\n\n## domRender\n\n```typescript\nexport declare function domRender(\n jsx: JSXOutput,\n opts?: {\n debug?: boolean;\n },\n): Promise<{\n document: Document;\n container: import(\"@qwik.dev/core\").ClientContainer;\n vNode: _VNode | null;\n getStyles: () => Record<string, string | string[]>;\n}>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| jsx | JSXOutput | |\n| opts | \\{ debug?: boolean; } | _(Optional)_ |\n\n**Returns:**\n\nPromise&lt;\\{ document: Document; container: import(\"@qwik.dev/core\").ClientContainer; vNode: \\_VNode \\| null; getStyles: () =&gt; Record&lt;string, string \\| string[]&gt;; }&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/rendering.unit-util.tsx)\n\n## ElementFixture\n\nCreates a simple DOM structure for testing components.\n\nBy default `EntityFixture` creates:\n\n```html\n<host q:view=\"./component_fixture.noop\">\n <child></child>\n</host>\n```\n\n```typescript\nexport declare class ElementFixture\n```\n\n| Constructor | Modifiers | Description |\n| --- | --- | --- |\n| (constructor)(options) | | Constructs a new instance of the `ElementFixture` class |\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| [child](#elementfixture-child) | | HTMLElement | |\n| [document](#elementfixture-document) | | MockDocument | |\n| [host](#elementfixture-host) | | HTMLElement | |\n| [parent](#elementfixture-parent) | | HTMLElement | |\n| [superParent](#elementfixture-superparent) | | HTMLElement | |\n| [window](#elementfixture-window) | | MockWindow | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/element-fixture.ts)\n\n## emulateExecutionOfQwikFuncs\n\n```typescript\nexport declare function emulateExecutionOfQwikFuncs(document: Document): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| document | Document | |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/rendering.unit-util.tsx)\n\n## expectDOM\n\n```typescript\nexport declare function expectDOM(\n actual: Element,\n expected: string,\n): Promise<void>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| actual | Element | |\n| expected | string | |\n\n**Returns:**\n\nPromise&lt;void&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/expect-dom.tsx)\n\n## getTestPlatform\n\n```typescript\nexport declare function getTestPlatform(): TestPlatform;\n```\n\n**Returns:**\n\nTestPlatform\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/platform.ts)\n\n## host\n\n```typescript\nhost: HTMLElement;\n```\n\n## InOrderAuto\n\n```typescript\nexport interface InOrderAuto\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| maximumChunk? | | number | _(Optional)_ |\n| maximumInitialChunk? | | number | _(Optional)_ |\n| strategy | | 'auto' | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## InOrderDirect\n\n```typescript\nexport interface InOrderDirect\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| strategy | | 'direct' | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## InOrderDisabled\n\n```typescript\nexport interface InOrderDisabled\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| strategy | | 'disabled' | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## InOrderStreaming\n\n```typescript\nexport type InOrderStreaming = InOrderAuto | InOrderDisabled | InOrderDirect;\n```\n\n**References:** [InOrderAuto](#inorderauto), [InOrderDisabled](#inorderdisabled), [InOrderDirect](#inorderdirect)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## OutOfOrderStreaming\n\n```typescript\nexport type OutOfOrderStreaming = boolean;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## parent\n\n```typescript\nparent: HTMLElement;\n```\n\n## ssrRenderToDom\n\n```typescript\nexport declare function ssrRenderToDom(\n jsx: JSXOutput,\n opts?: {\n debug?: boolean;\n raw?: boolean;\n qwikLoader?: boolean;\n containerTagName?: string;\n statePrewarm?: number | false;\n stream?: StreamWriter;\n streaming?: StreamingOptions;\n resume?: boolean;\n onBeforeResume?: (document: Document) => void;\n transformError?: (error: unknown) => Error | undefined | null | void;\n },\n): Promise<{\n container: _DomContainer;\n document: Document;\n vNode: _VNode | null;\n getStyles: () => Record<string, string | string[]>;\n}>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| jsx | JSXOutput | |\n| opts | \\{ debug?: boolean; raw?: boolean; qwikLoader?: boolean; containerTagName?: string; statePrewarm?: number \\\\| false; stream?: StreamWriter; streaming?: [StreamingOptions](#streamingoptions); resume?: boolean; onBeforeResume?: (document: Document) => void; transformError?: (error: unknown) => Error \\\\| undefined \\\\| null \\\\| void; } | _(Optional)_ |\n\n**Returns:**\n\nPromise&lt;\\{ container: \\_DomContainer; document: Document; vNode: \\_VNode \\| null; getStyles: () =&gt; Record&lt;string, string \\| string[]&gt;; }&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/rendering.unit-util.tsx)\n\n## StreamingOptions\n\n```typescript\nexport interface StreamingOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| inOrder? | | [InOrderStreaming](#inorderstreaming) | _(Optional)_ |\n| outOfOrder? | | [OutOfOrderStreaming](#outoforderstreaming) | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/server/types.ts)\n\n## superParent\n\n```typescript\nsuperParent: HTMLElement;\n```\n\n## trigger\n\nTrigger an event in unit tests on an element. Needs to be kept in sync with the Qwik Loader event dispatching.\n\nEvents can be either case sensitive element-scoped events or scoped kebab-case.\n\nFuture deprecation candidate.\n\n```typescript\nexport declare function trigger(\n root: Element,\n queryOrElement: string | Element | keyof HTMLElementTagNameMap | null,\n eventName: string,\n eventPayload?: any,\n options?: {\n waitForIdle?: boolean;\n },\n): Promise<Event | null>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| root | Element | |\n| queryOrElement | string \\\\| Element \\\\| keyof HTMLElementTagNameMap \\\\| null | |\n| eventName | string | |\n| eventPayload | any | _(Optional)_ |\n| options | \\{ waitForIdle?: boolean; } | _(Optional)_ |\n\n**Returns:**\n\nPromise&lt;Event \\| null&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/element-fixture.ts)\n\n## vnode_fromJSX\n\n```typescript\nexport declare function vnode_fromJSX(jsx: JSXOutput): {\n vParent: _ElementVNode | _VirtualVNode;\n vNode: _VNode | null;\n document: _QDocument;\n container: ClientContainer;\n};\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| jsx | JSXOutput | |\n\n**Returns:**\n\n\\{ vParent: \\_ElementVNode \\| \\_VirtualVNode; vNode: \\_VNode \\| null; document: \\_QDocument; container: ClientContainer; }\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/vdom-diff.unit-util.ts)\n\n## waitForDrain\n\nWait for the scheduler to drain.\n\nThis is useful when testing async code.\n\n```typescript\nexport declare function waitForDrain(container: Container): Promise<void>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| container | Container | The application container. |\n\n**Returns:**\n\nPromise&lt;void&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/util.ts)\n\n## walkJSX\n\n```typescript\nexport declare function walkJSX(\n jsx: JSXOutput,\n apply: {\n enter: (jsx: JSXNodeInternal) => void;\n leave: (jsx: JSXNodeInternal) => void;\n text: (text: _Stringifiable) => void;\n },\n): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| jsx | JSXOutput | |\n| apply | \\{ enter: (jsx: JSXNodeInternal) => void; leave: (jsx: JSXNodeInternal) => void; text: (text: \\_Stringifiable) => void; } | |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/testing/vdom-diff.unit-util.ts)\n\n## window\n\n```typescript\nwindow: MockWindow;\n```\n"},{"id":"/api/qwik-insights/","title":"@qwik.dev/qwik-insights","description":"Insights package API reference for performance tracing and analytics integration.","url":"https://next.qwik.dev/api/qwik-insights/","content":"# [API](/api.md) › @qwik.dev/core/insights\n\n## Insights\n\n> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n```typescript\nInsights: import(\"@qwik.dev/core\").Component<unknown>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/insights/insights.ts)\n\n## InsightsError\n\n```typescript\nexport interface InsightsError\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| column | | number | |\n| error | | string | |\n| line | | number | |\n| manifestHash | | string | Manifest Hash of the container. |\n| message | | string | |\n| source | | string | |\n| stack | | string | |\n| timestamp | | number | |\n| url | | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/insights/insights.ts)\n\n## InsightsPayload\n\n```typescript\nexport interface InsightsPayload\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| manifestHash | | string | Manifest Hash of the container. |\n| previousSymbol? | | string \\\\| null | _(Optional)_ Previous symbol received on the client. Client periodically sends symbol log to the server. Being able to connect the order of symbols is useful for server clustering. Sending previous symbol name allows the server to stitch the symbol list together. |\n| publicApiKey | | string | API key of the application which we are trying to profile. This key can be used for sharding the data. |\n| qVersion | | string | Qwik version |\n| symbols | | [InsightSymbol](#insightsymbol)[] | List of symbols which have been received since last update. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/insights/insights.ts)\n\n## InsightSymbol\n\n```typescript\nexport interface InsightSymbol\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| delay | | number | Time delta since last symbol. Can be used to stich symbol requests together |\n| interaction | | boolean | Was this symbol as a result of user interaction. User interactions represent roots for clouters. |\n| latency | | number | Number of ms between the time the symbol was requested and it was loaded. |\n| route | | string | Current route so we can have a better understanding of which symbols are needed for each route. |\n| symbol | | string | Symbol name |\n| timeline | | number | Number of ms between the q:route attribute change and the qsymbol event |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/insights/insights.ts)\n"},{"id":"/api/qwik-router-ssg/","title":"@qwik.dev/qwik-router-ssg","description":"API reference for @qwik.dev/qwik-router-ssg.","url":"https://next.qwik.dev/api/qwik-router-ssg/","content":"# [API](/api.md) › @qwik.dev/router/ssg\n\n## generate\n\nUse this function when SSG should be generated from another module, such as a Vite plugin. This function's should be passed the paths of the entry module and Qwik Router Plan.\n\n```typescript\nexport declare function generate(opts: SsgGenerateOptions): Promise<SsgResult>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [SsgGenerateOptions](#ssginternaloptions) | |\n\n**Returns:**\n\nPromise&lt;[SsgResult](#staticgenerateresult)&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/ssg/index.ts)\n\n## runSsg\n\nRun SSG as a standalone process. Writes `_static-paths.json` to `outDir` and exits with code 0 on success, 1 on error.\n\nIntended to be called from a generated `run-ssg.js` wrapper that provides render/config.\n\n```typescript\nexport declare function runSsg(opts: SsgGenerateOptions): Promise<never>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [SsgGenerateOptions](#ssginternaloptions) | |\n\n**Returns:**\n\nPromise&lt;never&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/ssg/index.ts)\n\n## SsgInternalOptions\n\nInternal SSG options that include the render function and router config.\n\n```typescript\nexport interface SsgGenerateOptions extends SsgOptions\n```\n\n**Extends:** [SsgOptions](#ssgoptions)\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| qwikRouterConfig | | QwikRouterConfig | The Qwik Router Config object (default export from `@qwik-router-config`). |\n| render | | Render | SSR render function (default export from `entry.ssr`); worker-only — the main entry omits it. |\n| workerFilePath? | | string \\\\| URL | _(Optional)_ Path or URL to the worker entry file (`run-ssg-worker.js`); workers are spawned from it. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/ssg/types.ts)\n\n## SsgOptions\n\n```typescript\nexport interface SsgOptions extends SsgRenderOptions\n```\n\n**Extends:** [SsgRenderOptions](#ssgrenderoptions)\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| basePathname? | | string | _(Optional)_ Defaults to `/` |\n| rootDir? | | string | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/ssg/types.ts)\n\n## SsgRenderOptions\n\n```typescript\nexport interface SsgRenderOptions extends RenderOptions\n```\n\n**Extends:** RenderOptions\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| emitData? | | boolean | _(Optional)_ Set to `false` if the generated per-loader data files should not be written to disk. Defaults to `true`. |\n| emitHtml? | | boolean | _(Optional)_ Set to `false` if the generated static HTML files should not be written to disk. Setting to `false` is useful if the SSG should only write the per-loader data files to disk. Defaults to `true`. |\n| exclude? | | string[] | _(Optional)_ Defines file system routes relative to the source `routes` directory that should not be static generated. Accepts wildcard behavior. This should not include the \"base\" pathname. `exclude` always takes priority over `include`. |\n| include? | | string[] | _(Optional)_ Defines file system routes relative to the source `routes` directory that should be static generated. Accepts wildcard behavior. This should not include the \"base\" pathname. If not provided, all routes will be static generated. `exclude` always takes priority over `include`. |\n| log? | | 'debug' \\\\| 'quiet' | _(Optional)_ Log level. `'quiet'` suppresses per-page output, `'debug'` enables verbose logging. |\n| maxTasksPerWorker? | | number | _(Optional)_ Maximum number of tasks to be running at one time per worker. Defaults to `20`. |\n| maxWorkers? | | number | _(Optional)_ Maximum number of workers to use while generating the static pages. Defaults to the number of CPUs available. |\n| origin | | string | The URL `origin`, which is a combination of the scheme (protocol) and hostname (domain). For example, `https://qwik.dev` has the protocol `https://` and domain `qwik.dev`. However, the `origin` does not include a `pathname`. The `origin` is used to provide a full URL during Static Site Generation (SSG), and to simulate a complete URL rather than just the `pathname`. For example, in order to render a correct canonical tag URL or URLs within the `sitemap.xml`, the `origin` must be provided too. If the site also starts with a pathname other than `/`, please use the `basePathname` option in the Qwik Router config options. |\n| outDir | | string | File system directory where the static files should be written. |\n| sitemapOutFile? | | string \\\\| null | _(Optional)_ File system path to write the `sitemap.xml` to. Defaults to `sitemap.xml` and written to the root of the `outDir`. Setting to `null` will prevent the sitemap from being created. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/ssg/types.ts)\n\n## startWorker\n\nBootstrap a worker thread for SSG rendering. Called from the generated `run-ssg.js` when it detects it's running as a worker thread.\n\n```typescript\nexport declare function startWorker(\n opts: Pick<SsgGenerateOptions, \"render\" | \"qwikRouterConfig\">,\n): Promise<void>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | Pick<[SsgGenerateOptions](#ssginternaloptions), 'render' \\\\| 'qwikRouterConfig'> | Must include `render` and `qwikRouterConfig` (imported by the worker entry). The remaining serializable options come from `workerData`. |\n\n**Returns:**\n\nPromise&lt;void&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/ssg/index.ts)\n\n## StaticGenerateResult\n\n```typescript\nexport interface SsgResult\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| duration | | number | |\n| errors | | number | |\n| rendered | | number | |\n| staticPaths | | string[] | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/ssg/types.ts)\n"},{"id":"/api/qwik-router-vite-azure-swa/","title":"@qwik.dev/qwik-router-vite-azure-swa","description":"API reference for @qwik.dev/qwik-router-vite-azure-swa.","url":"https://next.qwik.dev/api/qwik-router-vite-azure-swa/","content":"# [API](/api.md) › @qwik.dev/router/vite/azure-swa\n\n## azureSwaAdapter\n\n```typescript\nexport declare function azureSwaAdapter(opts?: AzureSwaAdapterOptions): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [AzureSwaAdapterOptions](#azureswaadapteroptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/azure-swa/vite/index.ts)\n\n## AzureSwaAdapterOptions\n\n```typescript\nexport interface AzureSwaAdapterOptions extends ServerAdapterOptions\n```\n\n**Extends:** ServerAdapterOptions\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/azure-swa/vite/index.ts)\n"},{"id":"/api/qwik-router-vite-bun-server/","title":"@qwik.dev/qwik-router-vite-bun-server","description":"API reference for @qwik.dev/qwik-router-vite-bun-server.","url":"https://next.qwik.dev/api/qwik-router-vite-bun-server/","content":"# [API](/api.md) › @qwik.dev/router/vite/bun-server\n\n## bunServerAdapter\n\n> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n```typescript\nexport declare function bunServerAdapter(opts?: bunServerAdapterOptions): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [bunServerAdapterOptions](#bunserveradapteroptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/bun-server/vite/index.ts)\n\n## bunServerAdapterOptions\n\n> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n```typescript\nexport interface bunServerAdapterOptions extends ServerAdapterOptions\n```\n\n**Extends:** ServerAdapterOptions\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| name? | | string | **_(BETA)_** _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/bun-server/vite/index.ts)\n"},{"id":"/api/qwik-router-vite-cloud-run/","title":"@qwik.dev/qwik-router-vite-cloud-run","description":"API reference for @qwik.dev/qwik-router-vite-cloud-run.","url":"https://next.qwik.dev/api/qwik-router-vite-cloud-run/","content":"# [API](/api.md) › @qwik.dev/router/vite/cloud-run\n\n## cloudRunAdapter\n\n```typescript\nexport declare function cloudRunAdapter(opts?: CloudRunAdapterOptions): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [CloudRunAdapterOptions](#cloudrunadapteroptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/cloud-run/vite/index.ts)\n\n## CloudRunAdapterOptions\n\n```typescript\nexport interface CloudRunAdapterOptions extends ServerAdapterOptions\n```\n\n**Extends:** ServerAdapterOptions\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/cloud-run/vite/index.ts)\n"},{"id":"/api/qwik-router-vite-cloudflare-pages/","title":"@qwik.dev/qwik-router-vite-cloudflare-pages","description":"API reference for @qwik.dev/qwik-router-vite-cloudflare-pages.","url":"https://next.qwik.dev/api/qwik-router-vite-cloudflare-pages/","content":"# [API](/api.md) › @qwik.dev/router/vite/cloudflare-pages\n\n## cloudflarePagesAdapter\n\n```typescript\nexport declare function cloudflarePagesAdapter(\n opts?: CloudflarePagesAdapterOptions,\n): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [CloudflarePagesAdapterOptions](#cloudflarepagesadapteroptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/cloudflare-pages/vite/index.ts)\n\n## CloudflarePagesAdapterOptions\n\n```typescript\nexport interface CloudflarePagesAdapterOptions extends ServerAdapterOptions\n```\n\n**Extends:** ServerAdapterOptions\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| functionRoutes? | | boolean | _(Optional)_ Determines if the build should generate the function invocation routes `_routes.json` file. https://developers.cloudflare.com/pages/platform/functions/routing/\\#functions-invocation-routes Defaults to `true`. |\n| staticPaths? | | string[] | _(Optional)_ Manually add pathnames that should be treated as static paths and not SSR. For example, when these pathnames are requested, their response should come from a static file, rather than a server-side rendered response. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/cloudflare-pages/vite/index.ts)\n"},{"id":"/api/qwik-router-vite-netlify-edge/","title":"@qwik.dev/qwik-router-vite-netlify-edge","description":"API reference for @qwik.dev/qwik-router-vite-netlify-edge.","url":"https://next.qwik.dev/api/qwik-router-vite-netlify-edge/","content":"# [API](/api.md) › @qwik.dev/router/vite/netlify-edge\n\n## netlifyEdgeAdapter\n\n```typescript\nexport declare function netlifyEdgeAdapter(\n opts?: NetlifyEdgeAdapterOptions,\n): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [NetlifyEdgeAdapterOptions](#netlifyedgeadapteroptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/netlify-edge/vite/index.ts)\n\n## NetlifyEdgeAdapterOptions\n\n```typescript\nexport interface NetlifyEdgeAdapterOptions extends ServerAdapterOptions\n```\n\n**Extends:** ServerAdapterOptions\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| excludedPath? | | string \\\\| string[] | _(Optional)_ Manually add path pattern that should be excluded from the edge function routes that are created by the 'manifest.json' file. If not specified, the following paths are excluded by default: - /build/\\* - /favicon.ico - /robots.txt - /mainifest.json - /\\~partytown/\\* - /service-worker.js - /sitemap.xml https://docs.netlify.com/edge-functions/declarations/\\#declare-edge-functions-in-netlify-toml |\n| functionRoutes? | | boolean | _(Optional)_ Determines if the build should generate the edge functions declarations `manifest.json` file. https://docs.netlify.com/edge-functions/declarations/ Defaults to `true`. |\n| staticPaths? | | string[] | _(Optional)_ Manually add pathnames that should be treated as static paths and not SSR. For example, when these pathnames are requested, their response should come from a static file, rather than a server-side rendered response. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/netlify-edge/vite/index.ts)\n"},{"id":"/api/qwik-router-vite-node-server/","title":"@qwik.dev/qwik-router-vite-node-server","description":"API reference for @qwik.dev/qwik-router-vite-node-server.","url":"https://next.qwik.dev/api/qwik-router-vite-node-server/","content":"# [API](/api.md) › @qwik.dev/router/vite/node-server\n\n## nodeServerAdapter\n\n> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n```typescript\nexport declare function nodeServerAdapter(opts?: NodeServerAdapterOptions): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [NodeServerAdapterOptions](#nodeserveradapteroptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/node-server/vite/index.ts)\n\n## NodeServerAdapterOptions\n\n> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n\n```typescript\nexport interface NodeServerAdapterOptions extends ServerAdapterOptions\n```\n\n**Extends:** ServerAdapterOptions\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| name? | | string | **_(BETA)_** _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/node-server/vite/index.ts)\n"},{"id":"/api/qwik-router-vite-ssg/","title":"@qwik.dev/qwik-router-vite-ssg","description":"API reference for @qwik.dev/qwik-router-vite-ssg.","url":"https://next.qwik.dev/api/qwik-router-vite-ssg/","content":"# [API](/api.md) › @qwik.dev/router/vite/ssg\n\n## ssgAdapter\n\n```typescript\nexport declare function ssgAdapter(opts: SsgAdapterOptions): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [SsgAdapterOptions](#ssgadapteroptions) | |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/ssg/vite/index.ts)\n\n## SsgAdapterOptions\n\n```typescript\nexport interface SsgAdapterOptions extends Omit<SsgRenderOptions, 'outDir'>\n```\n\n**Extends:** Omit&lt;SsgRenderOptions, 'outDir'&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/ssg/vite/index.ts)\n\n## staticAdapter\n\n> Warning: This API is now obsolete.\n>\n> Use `ssgAdapter` instead.\n\n```typescript\nstaticAdapter: typeof ssgAdapter;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/ssg/vite/index.ts)\n"},{"id":"/api/qwik-router-vite-vercel/","title":"@qwik.dev/qwik-router-vite-vercel","description":"API reference for @qwik.dev/qwik-router-vite-vercel.","url":"https://next.qwik.dev/api/qwik-router-vite-vercel/","content":"# [API](/api.md) › @qwik.dev/router/vite/vercel\n\n## vercelEdgeAdapter\n\n```typescript\nexport declare function vercelEdgeAdapter(opts?: VercelEdgeAdapterOptions): any;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [VercelEdgeAdapterOptions](#verceledgeadapteroptions) | _(Optional)_ |\n\n**Returns:**\n\nany\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/vercel-edge/vite/index.ts)\n\n## VercelEdgeAdapterOptions\n\n```typescript\nexport interface VercelEdgeAdapterOptions extends ServerAdapterOptions\n```\n\n**Extends:** ServerAdapterOptions\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| outputConfig? | | boolean | _(Optional)_ Determines if the build should auto-generate the `.vercel/output/config.json` config. Defaults to `true`. |\n| staticPaths? | | string[] | _(Optional)_ Manually add pathnames that should be treated as static paths and not SSR. For example, when these pathnames are requested, their response should come from a static file, rather than a server-side rendered response. |\n| target? | | 'webworker' \\\\| 'node' | _(Optional)_ Define the `target` property in the `ssr` object in the `vite.config.ts` file. Defaults to `webworker`. |\n| vcConfigEntryPoint? | | string | _(Optional)_ The `entrypoint` property in the `.vc-config.json` file. Indicates the initial file where code will be executed for the Edge Function. Defaults to `entry.vercel-edge.js`. |\n| vcConfigEnvVarsInUse? | | string[] | _(Optional)_ The `envVarsInUse` property in the `.vc-config.json` file. List of environment variable names that will be available for the Edge Function to utilize. Defaults to `undefined`. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/adapters/vercel-edge/vite/index.ts)\n"},{"id":"/api/qwik-router-middleware-aws-lambda/","title":"@qwik.dev/qwik-router-middleware-aws-lambda","description":"API reference for @qwik.dev/qwik-router-middleware-aws-lambda.","url":"https://next.qwik.dev/api/qwik-router-middleware-aws-lambda/","content":"# [API](/api.md) › @qwik.dev/router/middleware/aws-lambda\n\n## createQwikCity\n\n> Warning: This API is now obsolete.\n>\n> Use `createQwikRouter` instead. Will be removed in V3\n\n```typescript\ncreateQwikCity: typeof createQwikRouter;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/aws-lambda/index.ts)\n\n## createQwikRouter\n\n```typescript\nexport declare function createQwikRouter(\n opts: AwsOpt,\n): QwikRouterAwsLambdaMiddleware;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | AwsOpt | |\n\n**Returns:**\n\n[QwikRouterAwsLambdaMiddleware](#qwikrouterawslambdamiddleware)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/aws-lambda/index.ts)\n\n## PlatformAwsLambda\n\n```typescript\nexport interface PlatformAwsLambda extends Object\n```\n\n**Extends:** Object\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/aws-lambda/index.ts)\n\n## QwikCityAwsLambdaOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterAwsLambdaOptions` instead. Will be removed in V3\n\n```typescript\nexport type QwikCityAwsLambdaOptions = QwikRouterAwsLambdaOptions;\n```\n\n**References:** [QwikRouterAwsLambdaOptions](#qwikrouterawslambdaoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/aws-lambda/index.ts)\n\n## QwikRouterAwsLambdaMiddleware\n\n```typescript\nexport interface QwikRouterAwsLambdaMiddleware\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| fixPath | | (pathT: string) => string | |\n| handle | | (req: any, res: any) => void | |\n| notFound | | (req: IncomingMessage \\\\| Http2ServerRequest, res: ServerResponse, next: (e?: any) => void) => Promise<void> | |\n| router | | (req: IncomingMessage \\\\| Http2ServerRequest, res: ServerResponse, next: NodeRequestNextFunction) => Promise<void> | |\n| staticFile | | (req: IncomingMessage \\\\| Http2ServerRequest, res: ServerResponse, next: (e?: any) => void) => Promise<void> | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/aws-lambda/index.ts)\n\n## QwikRouterAwsLambdaOptions\n\n```typescript\nexport interface QwikRouterAwsLambdaOptions extends ServerRenderOptions\n```\n\n**Extends:** ServerRenderOptions\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/aws-lambda/index.ts)\n"},{"id":"/api/qwik-router-middleware-azure-swa/","title":"@qwik.dev/qwik-router-middleware-azure-swa","description":"API reference for @qwik.dev/qwik-router-middleware-azure-swa.","url":"https://next.qwik.dev/api/qwik-router-middleware-azure-swa/","content":"# [API](/api.md) › @qwik.dev/router/middleware/azure-swa\n\n## createQwikCity\n\n> Warning: This API is now obsolete.\n>\n> Use `createQwikRouter` instead. Will be removed in V3\n\n```typescript\ncreateQwikCity: typeof createQwikRouter;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/azure-swa/index.ts)\n\n## createQwikRouter\n\n```typescript\nexport declare function createQwikRouter(\n opts: QwikRouterAzureOptions,\n): AzureFunction;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [QwikRouterAzureOptions](#qwikrouterazureoptions) | |\n\n**Returns:**\n\nAzureFunction\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/azure-swa/index.ts)\n\n## PlatformAzure\n\n```typescript\nexport interface PlatformAzure extends Partial<Context>\n```\n\n**Extends:** Partial&lt;Context&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/azure-swa/index.ts)\n\n## QwikCityAzureOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterAzureOptions` instead. Will be removed in V3\n\n```typescript\nexport type QwikCityAzureOptions = QwikRouterAzureOptions;\n```\n\n**References:** [QwikRouterAzureOptions](#qwikrouterazureoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/azure-swa/index.ts)\n\n## QwikRouterAzureOptions\n\n```typescript\nexport interface QwikRouterAzureOptions extends ServerRenderOptions\n```\n\n**Extends:** ServerRenderOptions\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/azure-swa/index.ts)\n"},{"id":"/api/qwik-router-middleware-cloudflare-pages/","title":"@qwik.dev/qwik-router-middleware-cloudflare-pages","description":"API reference for @qwik.dev/qwik-router-middleware-cloudflare-pages.","url":"https://next.qwik.dev/api/qwik-router-middleware-cloudflare-pages/","content":"# [API](/api.md) › @qwik.dev/router/middleware/cloudflare-pages\n\n## createQwikCity\n\n> Warning: This API is now obsolete.\n>\n> Use `createQwikRouter` instead. Will be removed in V3\n\n```typescript\ncreateQwikCity: typeof createQwikRouter;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/cloudflare-pages/index.ts)\n\n## createQwikRouter\n\n```typescript\nexport declare function createQwikRouter(\n opts: QwikRouterCloudflarePagesOptions,\n): (\n request: PlatformCloudflarePages[\"request\"],\n env: PlatformCloudflarePages[\"env\"] & {\n ASSETS: {\n fetch: (req: Request) => Response;\n };\n },\n ctx: PlatformCloudflarePages[\"ctx\"],\n) => Promise<Response>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [QwikRouterCloudflarePagesOptions](#qwikroutercloudflarepagesoptions) | |\n\n**Returns:**\n\n(request: [PlatformCloudflarePages](#platformcloudflarepages)[\"request\"], env: [PlatformCloudflarePages](#platformcloudflarepages)[\"env\"] &amp; \\{ ASSETS: \\{ fetch: (req: Request) =&gt; Response; }; }, ctx: [PlatformCloudflarePages](#platformcloudflarepages)[\"ctx\"]) =&gt; Promise&lt;Response&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/cloudflare-pages/index.ts)\n\n## PlatformCloudflarePages\n\n```typescript\nexport interface PlatformCloudflarePages\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| ctx | | \\{ waitUntil: (promise: Promise<any>) => void; } | |\n| env? | | Record<string, any> | _(Optional)_ |\n| request | | Request | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/cloudflare-pages/index.ts)\n\n## QwikCityCloudflarePagesOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterCloudflarePagesOptions` instead. Will be removed in V3\n\n```typescript\nexport type QwikCityCloudflarePagesOptions = QwikRouterCloudflarePagesOptions;\n```\n\n**References:** [QwikRouterCloudflarePagesOptions](#qwikroutercloudflarepagesoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/cloudflare-pages/index.ts)\n\n## QwikRouterCloudflarePagesOptions\n\n```typescript\nexport interface QwikRouterCloudflarePagesOptions extends ServerRenderOptions\n```\n\n**Extends:** ServerRenderOptions\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/cloudflare-pages/index.ts)\n"},{"id":"/api/qwik-router-middleware-firebase/","title":"@qwik.dev/qwik-router-middleware-firebase","description":"API reference for @qwik.dev/qwik-router-middleware-firebase.","url":"https://next.qwik.dev/api/qwik-router-middleware-firebase/","content":"# [API](/api.md) › @qwik.dev/router/middleware/firebase\n\n## createQwikCity\n\n> Warning: This API is now obsolete.\n>\n> Use `createQwikRouter` instead. Will be removed in V3\n\n```typescript\ncreateQwikCity: typeof createQwikRouter;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/firebase/index.ts)\n\n## createQwikRouter\n\n```typescript\nexport declare function createQwikRouter(\n opts: QwikRouterFirebaseOptions,\n): (req: any, res: any) => Promise<void>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [QwikRouterFirebaseOptions](#qwikrouterfirebaseoptions) | |\n\n**Returns:**\n\n(req: any, res: any) =&gt; Promise&lt;void&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/firebase/index.ts)\n\n## PlatformFirebase\n\n```typescript\nexport interface PlatformFirebase extends Object\n```\n\n**Extends:** Object\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/firebase/index.ts)\n\n## QwikCityFirebaseOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterFirebaseOptions` instead. Will be removed in V3\n\n```typescript\nexport type QwikCityFirebaseOptions = QwikRouterFirebaseOptions;\n```\n\n**References:** [QwikRouterFirebaseOptions](#qwikrouterfirebaseoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/firebase/index.ts)\n\n## QwikRouterFirebaseOptions\n\n```typescript\nexport interface QwikRouterFirebaseOptions extends ServerRenderOptions\n```\n\n**Extends:** ServerRenderOptions\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/firebase/index.ts)\n"},{"id":"/api/qwik-router-middleware-netlify-edge/","title":"@qwik.dev/qwik-router-middleware-netlify-edge","description":"API reference for @qwik.dev/qwik-router-middleware-netlify-edge.","url":"https://next.qwik.dev/api/qwik-router-middleware-netlify-edge/","content":"# [API](/api.md) › @qwik.dev/router/middleware/netlify-edge\n\n## createQwikCity\n\n> Warning: This API is now obsolete.\n>\n> Use `createQwikRouter` instead. Will be removed in V3\n\n```typescript\ncreateQwikCity: typeof createQwikRouter;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/netlify-edge/index.ts)\n\n## createQwikRouter\n\n```typescript\nexport declare function createQwikRouter(\n opts: QwikRouterNetlifyOptions,\n): (request: Request, context: Context) => Promise<Response>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [QwikRouterNetlifyOptions](#qwikrouternetlifyoptions) | |\n\n**Returns:**\n\n(request: Request, context: Context) =&gt; Promise&lt;Response&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/netlify-edge/index.ts)\n\n## PlatformNetlify\n\n```typescript\nexport interface PlatformNetlify extends Partial<Omit<Context, 'next' | 'cookies'>>\n```\n\n**Extends:** Partial&lt;Omit&lt;Context, 'next' \\| 'cookies'&gt;&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/netlify-edge/index.ts)\n\n## QwikCityNetlifyOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterNetlifyOptions` instead. Will be removed in V3\n\n```typescript\nexport type QwikCityNetlifyOptions = QwikRouterNetlifyOptions;\n```\n\n**References:** [QwikRouterNetlifyOptions](#qwikrouternetlifyoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/netlify-edge/index.ts)\n\n## QwikRouterNetlifyOptions\n\n```typescript\nexport interface QwikRouterNetlifyOptions extends ServerRenderOptions\n```\n\n**Extends:** ServerRenderOptions\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/netlify-edge/index.ts)\n"},{"id":"/api/qwik-router-middleware-node/","title":"@qwik.dev/qwik-router-middleware-node","description":"API reference for @qwik.dev/qwik-router-middleware-node.","url":"https://next.qwik.dev/api/qwik-router-middleware-node/","content":"# [API](/api.md) › @qwik.dev/router/middleware/node\n\n## createQwikCity\n\n> Warning: This API is now obsolete.\n>\n> Use `createQwikRouter` instead. Will be removed in V3\n\n```typescript\ncreateQwikCity: typeof createQwikRouter;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/node/index.ts)\n\n## createQwikRouter\n\n```typescript\nexport declare function createQwikRouter(\n opts: QwikRouterNodeRequestOptions | QwikCityNodeRequestOptions,\n): QwikRouterNodeMiddleware;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [QwikRouterNodeRequestOptions](#qwikrouternoderequestoptions) \\\\| [QwikCityNodeRequestOptions](#qwikcitynoderequestoptions) | |\n\n**Returns:**\n\n[QwikRouterNodeMiddleware](#qwikrouternodemiddleware)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/node/index.ts)\n\n## NodeRequestNextFunction\n\n```typescript\nexport interface NodeRequestNextFunction\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/node/index.ts)\n\n## PlatformNode\n\n```typescript\nexport interface PlatformNode\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| incomingMessage? | | IncomingMessage \\\\| Http2ServerRequest | _(Optional)_ |\n| node? | | string | _(Optional)_ |\n| ssr? | | true | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/node/index.ts)\n\n## QwikCityNodeRequestOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterNodeRequestOptions` instead. Will be removed in V3\n\n```typescript\nexport type QwikCityNodeRequestOptions = QwikRouterNodeRequestOptions;\n```\n\n**References:** [QwikRouterNodeRequestOptions](#qwikrouternoderequestoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/node/index.ts)\n\n## QwikRouterNodeMiddleware\n\n```typescript\nexport interface QwikRouterNodeMiddleware\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| notFound | | (req: IncomingMessage \\\\| Http2ServerRequest, res: ServerResponse, next: (e: any) => void) => Promise<void> | |\n| router | | (req: IncomingMessage \\\\| Http2ServerRequest, res: ServerResponse, next: [NodeRequestNextFunction](#noderequestnextfunction), limits?: [QwikRouterNodeRequestLimits](#qwikrouternoderequestlimits)) => Promise<void> | |\n| staticFile | | (req: IncomingMessage \\\\| Http2ServerRequest, res: ServerResponse, next: (e?: any) => void) => Promise<void> | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/node/index.ts)\n\n## QwikRouterNodeRequestLimits\n\n```typescript\nexport interface QwikRouterNodeRequestLimits\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| bodyLimit? | | number | _(Optional)_ Maximum request body size in bytes imposed by the host. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/node/index.ts)\n\n## QwikRouterNodeRequestOptions\n\n```typescript\nexport interface QwikRouterNodeRequestOptions extends ServerRenderOptions\n```\n\n**Extends:** ServerRenderOptions\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| getClientConn? | | (req: IncomingMessage \\\\| Http2ServerRequest) => ClientConn | _(Optional)_ Provide a function that returns a `ClientConn` for the given request. |\n| getOrigin? | | (req: IncomingMessage \\\\| Http2ServerRequest) => string \\\\| null | _(Optional)_ Provide a function that computes the origin of the server, used to resolve relative URLs and validate the request origin against CSRF attacks. When not specified, it defaults to the `ORIGIN` environment variable (if set). If `ORIGIN` is not set, it's derived from the incoming request, which is not recommended for production use. You can specify the `PROTOCOL_HEADER`, `HOST_HEADER` to `X-Forwarded-Proto` and `X-Forwarded-Host` respectively to override the default behavior. |\n| origin? | | string | _(Optional)_ |\n| requestBodyLimit? | | number | _(Optional)_ Maximum request body size in bytes. Defaults to 10 MiB. |\n| static? | | \\{ root?: string; cacheControl?: string; } | _(Optional)_ Options for serving static files |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/node/index.ts)\n"},{"id":"/api/qwik-router-middleware-request-handler/","title":"@qwik.dev/qwik-router-middleware-request-handler","description":"API reference for @qwik.dev/qwik-router-middleware-request-handler.","url":"https://next.qwik.dev/api/qwik-router-middleware-request-handler/","content":"# [API](/api.md) › @qwik.dev/router/middleware/request-handler\n\n## __controlFlow\n\nType-only brand so `Exclude<>` can drop control-flow signals from resolved loader/action data.\n\n```typescript\nreadonly __controlFlow: true;\n```\n\n## AbortMessage\n\n```typescript\nexport declare class AbortMessage\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| [\\_\\_controlFlow](#abortmessage-__controlflow) | `readonly` | true | Type-only brand so `Exclude<>` can drop control-flow signals from resolved loader/action data. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/redirect-handler.ts)\n\n## append\n\nAppends a `Response` cookie header using the `Set-Cookie` header.\n\nThe difference between `set()` and `append()` is that if the specified header already exists, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values.\n\n```typescript\nappend(name: string, value: string | number | Record<string, any>, options?: CookieOptions): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| name | string | |\n| value | string \\\\| number \\\\| Record<string, any> | |\n| options | [CookieOptions](#cookieoptions) | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n## CacheControl\n\n```typescript\nexport type CacheControl =\n | CacheControlOptions\n | number\n | \"day\"\n | \"week\"\n | \"month\"\n | \"year\"\n | \"no-cache\"\n | \"immutable\"\n | \"private\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## clearLoaderCache\n\nClear the in-memory loader cache. Call after deployments or data changes.\n\nWhen `cacheKey` is provided, only that single entry is removed; otherwise the entire cache is cleared.\n\n```typescript\nexport declare function clearLoaderCache(cacheKey?: string): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| cacheKey | string | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/etag.ts)\n\n## clearSsrCache\n\nClear the in-memory SSR cache. Call after deployments or data changes.\n\nWhen `cacheKey` is provided, only that single entry is removed; otherwise the entire cache is cleared.\n\n```typescript\nexport declare function clearSsrCache(cacheKey?: string): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| cacheKey | string | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/etag.ts)\n\n## ClientConn\n\n```typescript\nexport interface ClientConn\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| country? | | string | _(Optional)_ |\n| ip? | | string | _(Optional)_ |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## Cookie\n\n```typescript\nexport interface Cookie\n```\n\n| Method | Description |\n| --- | --- |\n| [append(name, value, options)](#cookie-append) | Appends a `Response` cookie header using the `Set-Cookie` header. The difference between `set()` and `append()` is that if the specified header already exists, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. |\n| [delete(name, options)](#cookie-delete) | Deletes cookie value by name using the `Response` cookie header. |\n| [get(name)](#cookie-get) | Gets a `Request` cookie header value by name. |\n| [getAll()](#cookie-getall) | Gets all `Request` cookie headers. |\n| [has(name)](#cookie-has) | Checks if the `Request` cookie header name exists. |\n| [headers()](#cookie-headers) | Returns an array of all the set `Response` `Set-Cookie` header values. |\n| [set(name, value, options)](#cookie-set) | Sets a `Response` cookie header using the `Set-Cookie` header. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## CookieOptions\n\nhttps://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie\n\n```typescript\nexport interface CookieOptions\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| domain? | | string | _(Optional)_ Defines the host to which the cookie will be sent. If omitted, this attribute defaults to the host of the current document URL, not including subdomains. |\n| expires? | | Date \\\\| string | _(Optional)_ Indicates the maximum lifetime of the cookie as an HTTP-date timestamp. If both `expires` and `maxAge` are set, `maxAge` has precedence. |\n| httpOnly? | | boolean | _(Optional)_ Forbids JavaScript from accessing the cookie, for example, through the `document.cookie` property. |\n| maxAge? | | number \\\\| [number, 'seconds' \\\\| 'minutes' \\\\| 'hours' \\\\| 'days' \\\\| 'weeks'] | _(Optional)_ Indicates the number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both `expires` and `maxAge` are set, `maxAge` has precedence. You can also use the array syntax to set the max-age using minutes, hours, days or weeks. For example, `{ maxAge: [3, \"days\"] }` would set the cookie to expire in 3 days. |\n| path? | | string | _(Optional)_ Indicates the path that must exist in the requested URL for the browser to send the Cookie header. |\n| sameSite? | | 'strict' \\\\| 'lax' \\\\| 'none' \\\\| 'Strict' \\\\| 'Lax' \\\\| 'None' \\\\| boolean | _(Optional)_ Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF). |\n| secure? | | boolean | _(Optional)_ Indicates that the cookie is sent to the server only when a request is made with the `https:` scheme (except on localhost) |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## CookieValue\n\n```typescript\nexport interface CookieValue\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| json | | <T = unknown>() => T | |\n| number | | () => number | |\n| value | | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## data\n\n```typescript\ndata: T;\n```\n\n## DeferReturn\n\n```typescript\nexport type DeferReturn<T> = () => Promise<T>;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## delete\n\nDeletes cookie value by name using the `Response` cookie header.\n\n```typescript\ndelete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'sameSite'>): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| name | string | |\n| options | Pick<[CookieOptions](#cookieoptions), 'path' \\\\| 'domain' \\\\| 'sameSite'> | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n## EnvGetter\n\n```typescript\nexport interface EnvGetter\n```\n\n| Method | Description |\n| --- | --- |\n| get(key) | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## get\n\nGets a `Request` cookie header value by name.\n\n```typescript\nget(name: string): CookieValue | null;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| name | string | |\n\n**Returns:**\n\n[CookieValue](#cookievalue) \\| null\n\n## getAll\n\nGets all `Request` cookie headers.\n\n```typescript\ngetAll(): Record<string, CookieValue>;\n```\n\n**Returns:**\n\nRecord&lt;string, [CookieValue](#cookievalue)&gt;\n\n## getErrorHtml\n\n```typescript\nexport declare function getErrorHtml(status: number, e: any): string;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| status | number | |\n| e | any | |\n\n**Returns:**\n\nstring\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/error-handler.ts)\n\n## has\n\nChecks if the `Request` cookie header name exists.\n\n```typescript\nhas(name: string): boolean;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| name | string | |\n\n**Returns:**\n\nboolean\n\n## headers\n\nReturns an array of all the set `Response` `Set-Cookie` header values.\n\n```typescript\nheaders(): string[];\n```\n\n**Returns:**\n\nstring[]\n\n## InternalRequest\n\nInternal JSON request kind handled by Qwik Router, or `false` for normal page requests.\n\n```typescript\nexport type InternalRequest = false | \"loader\" | \"action\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## mergeHeadersCookies\n\n```typescript\nmergeHeadersCookies: (headers: Headers, cookies: CookieInterface) => Headers;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| headers | Headers | |\n| cookies | [CookieInterface](#cookie) | |\n\n**Returns:**\n\nHeaders\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/cookie.ts)\n\n## pathname\n\n```typescript\nreadonly pathname: string;\n```\n\n## RedirectMessage\n\n```typescript\nexport declare class RedirectMessage extends AbortMessage\n```\n\n**Extends:** [AbortMessage](#abortmessage)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/redirect-handler.ts)\n\n## RequestEvent\n\n```typescript\nexport interface RequestEvent<PLATFORM = QwikRouterPlatform> extends RequestEventCommon<PLATFORM>\n```\n\n**Extends:** [RequestEventCommon](#requesteventcommon)&lt;PLATFORM&gt;\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| exited | `readonly` | boolean | True if the middleware chain has finished executing. |\n| getWritableStream | `readonly` | () => WritableStream<Uint8Array> | Low-level access to write to the HTTP response stream. Once `getWritableStream()` is called, the status and headers can no longer be modified and will be sent over the network. |\n| headersSent | `readonly` | boolean | True if headers have been sent, preventing any more headers from being set. |\n| next | `readonly` | () => Promise<void> | Invoke the next middleware function in the chain. NOTE: Ensure that the call to `next()` is `await`ed. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## RequestEventAction\n\n```typescript\nexport interface RequestEventAction<PLATFORM = QwikRouterPlatform> extends RequestEventCommon<PLATFORM>\n```\n\n**Extends:** [RequestEventCommon](#requesteventcommon)&lt;PLATFORM&gt;\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| fail | | <T extends Record<string, any>>(status: number, returnData: T) => FailReturn<T> | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## RequestEventBase\n\n```typescript\nexport interface RequestEventBase<PLATFORM = QwikRouterPlatform>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| basePathname | `readonly` | string | The base pathname of the request, which can be configured at build time. Defaults to `/`. |\n| cacheControl | `readonly` | (cacheControl: [CacheControl](#cachecontrol), target?: CacheControlTarget) => void | Convenience method to set the Cache-Control header. Depending on your CDN, you may want to add another cacheControl with the second argument set to `CDN-Cache-Control` or any other value (we provide the most common values for auto-complete, but you can use any string you want). See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control and https://qwik.dev/docs/caching/\\#CDN-Cache-Controls for more information. |\n| clientConn | `readonly` | [ClientConn](#clientconn) | Provides information about the client connection, such as the IP address and the country the request originated from. |\n| cookie | `readonly` | [Cookie](#cookie) | HTTP request and response cookie. Use the `get()` method to retrieve a request cookie value. Use the `set()` method to set a response cookie value. https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies |\n| env | `readonly` | [EnvGetter](#envgetter) | Platform provided environment variables. |\n| headers | `readonly` | Headers | HTTP response headers. Notice it will be empty until you first add a header. If you want to read the request headers, use `request.headers` instead. https://developer.mozilla.org/en-US/docs/Glossary/Response\\_header |\n| internalRequest | `readonly` | [InternalRequest](#internalrequest) | Identifies Qwik Router internal JSON requests, such as route loader fetches and fetch-based action submissions. Returns `false` for normal page requests. Check this before applying broad rewrite rules so internal JSON requests keep their routing behavior. |\n| method | `readonly` | string | HTTP request method. https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods |\n| originalUrl | `readonly` | URL | The original HTTP request URL. This property was introduced to support the rewrite feature. If rewrite is called, the url property will be changed to the rewritten url. while originalUrl will stay the same(e.g the url inserted to the address bar). If rewrite is never called as part of the request, the url property and the originalUrl are equal. |\n| params | `readonly` | Readonly<Record<string, string>> | URL path params which have been parsed from the current url pathname segments. Use `query` to instead retrieve the query string search params. |\n| parseBody | `readonly` | () => Promise<unknown> | This method will check the request headers for a `Content-Type` header and parse the body accordingly. It supports `application/json`, `application/x-www-form-urlencoded`, and `multipart/form-data` content types. If the `Content-Type` header is not set, it will return `null`. |\n| pathname | `readonly` | string | URL pathname. Does not include the protocol, domain, query string (search params) or hash. https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname |\n| platform | `readonly` | PLATFORM | Platform specific data and functions |\n| query | `readonly` | URLSearchParams | URL Query Strings (URL Search Params). Use `params` to instead retrieve the route params found in the url pathname. https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams |\n| request | `readonly` | Request | HTTP request information. |\n| sharedMap | `readonly` | Map<string, any> | Shared Map across all the request handlers. Every HTTP request will get a new instance of the shared map. The shared map is useful for sharing data between request handlers. |\n| signal | `readonly` | AbortSignal | Request's AbortSignal (same as `request.signal`). This signal indicates that the request has been aborted. |\n| url | `readonly` | URL | HTTP request URL. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## RequestEventCommon\n\n```typescript\nexport interface RequestEventCommon<PLATFORM = QwikRouterPlatform> extends RequestEventBase<PLATFORM>\n```\n\n**Extends:** [RequestEventBase](#requesteventbase)&lt;PLATFORM&gt;\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| error | `readonly` | <T = any>(statusCode: ErrorCodes, message: T) => [ServerError](#servererror)<T> | When called, the response will immediately end with the given status code. This could be useful to end a response with `404`, and use the 404 handler in the routes directory. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status for which status code should be used. |\n| exit | `readonly` | () => [AbortMessage](#abortmessage) | |\n| html | `readonly` | (statusCode: StatusCodes, html: string) => [AbortMessage](#abortmessage) | Convenience method to send an HTML body response. The response will be automatically set the `Content-Type` header to`text/html; charset=utf-8`. An `html()` response can only be called once. |\n| json | `readonly` | (statusCode: StatusCodes, data: any) => [AbortMessage](#abortmessage) | Convenience method to JSON stringify the data and send it in the response. The response will be automatically set the `Content-Type` header to `application/json; charset=utf-8`. A `json()` response can only be called once. |\n| locale | `readonly` | (local?: string) => string | Which locale the content is in. The locale value can be retrieved from selected methods using `getLocale()`: |\n| redirect | `readonly` | (statusCode: RedirectCode, url: string) => [RedirectMessage](#redirectmessage) | URL to redirect to. When called, the response will immediately end with the correct redirect status and headers. https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections |\n| rewrite | `readonly` | (pathname: string) => [RewriteMessage](#rewritemessage) | When called, qwik-router will execute the path's matching route flow. The url in the browser will remain unchanged. |\n| send | `readonly` | SendMethod | Send a body response. The `Content-Type` response header is not automatically set when using `send()` and must be set manually. A `send()` response can only be called once. |\n| status | `readonly` | (statusCode?: StatusCodes) => number | HTTP response status code. Sets the status code when called with an argument. Always returns the status code, so calling `status()` without an argument will can be used to return the current status code. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status |\n| text | `readonly` | (statusCode: StatusCodes, text: string) => [AbortMessage](#abortmessage) | Convenience method to send an text body response. The response will be automatically set the `Content-Type` header to`text/plain; charset=utf-8`. An `text()` response can only be called once. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## RequestEventLoader\n\n```typescript\nexport interface RequestEventLoader<PLATFORM = QwikRouterPlatform> extends RequestEventAction<PLATFORM>\n```\n\n**Extends:** [RequestEventAction](#requesteventaction)&lt;PLATFORM&gt;\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| defer | | <T>(returnData: Promise<T> \\\\| (() => Promise<T>)) => [DeferReturn](#deferreturn)<T> | |\n| resolveValue | | [ResolveValue](#resolvevalue) | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## requestHandler\n\n```typescript\nexport type RequestHandler<PLATFORM = QwikRouterPlatform> = (\n ev: RequestEvent<PLATFORM>,\n) =>\n | Promise<void | AbortMessage | ServerError>\n | void\n | AbortMessage\n | ServerError;\n```\n\n**References:** [RequestEvent](#requestevent), [AbortMessage](#abortmessage), [ServerError](#servererror)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/request-handler.ts)\n\n## RequestHandler\n\n```typescript\nexport type RequestHandler<PLATFORM = QwikRouterPlatform> = (\n ev: RequestEvent<PLATFORM>,\n) =>\n | Promise<void | AbortMessage | ServerError>\n | void\n | AbortMessage\n | ServerError;\n```\n\n**References:** [RequestEvent](#requestevent), [AbortMessage](#abortmessage), [ServerError](#servererror)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## ResolveSyncValue\n\n```typescript\nexport interface ResolveSyncValue\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## ResolveValue\n\n```typescript\nexport interface ResolveValue\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## RewriteMessage\n\n```typescript\nexport declare class RewriteMessage extends AbortMessage\n```\n\n**Extends:** [AbortMessage](#abortmessage)\n\n| Constructor | Modifiers | Description |\n| --- | --- | --- |\n| (constructor)(pathname) | | Constructs a new instance of the `RewriteMessage` class |\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| [pathname](#rewritemessage-pathname) | `readonly` | string | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/rewrite-handler.ts)\n\n## ServerError\n\n```typescript\nexport declare class ServerError<T = any> extends Error\n```\n\n**Extends:** Error\n\n| Constructor | Modifiers | Description |\n| --- | --- | --- |\n| (constructor)(status, data) | | Constructs a new instance of the `ServerError` class |\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| [data](#servererror-data) | | T | |\n| [status](#servererror-status) | | number | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/server-error.ts)\n\n## ServerRenderOptions\n\n```typescript\nexport interface ServerRenderOptions extends RenderOptions\n```\n\n**Extends:** RenderOptions\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| checkOrigin? | | boolean \\\\| 'lax-proto' | _(Optional)_ Protection against cross-site request forgery (CSRF) attacks. When `true`, for every incoming POST, PUT, PATCH, or DELETE form submissions, the request origin is checked to match the server's origin. `lax-proto` is for SSL-terminating proxies Be careful when disabling this option as it may lead to CSRF attacks. Defaults to `true`. |\n| render | | Render | |\n| trustForwardedHeaders? | | boolean | _(Optional)_ Use the `X-Forwarded-Host` and `X-Forwarded-Proto` request headers to compute the URL exposed by `useLocation()` during SSR. Only enable this when the server is behind a proxy that overwrites these headers, otherwise clients can spoof the URL. Defaults to `false`. |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## ServerRequestEvent\n\nRequest event created by the server.\n\n```typescript\nexport interface ServerRequestEvent<T = unknown>\n```\n\n| Property | Modifiers | Type | Description |\n| --- | --- | --- | --- |\n| env | | [EnvGetter](#envgetter) | |\n| getClientConn | | () => [ClientConn](#clientconn) | |\n| getWritableStream | | [ServerResponseHandler](#serverresponsehandler)<T> | |\n| locale | | string \\\\| undefined | |\n| mode | | [ServerRequestMode](#serverrequestmode) | |\n| platform | | QwikRouterPlatform | |\n| request | | Request | |\n| url | | URL | |\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## ServerRequestMode\n\n```typescript\nexport type ServerRequestMode = \"static\" | \"server\";\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## ServerResponseHandler\n\n```typescript\nexport type ServerResponseHandler<T = any> = (\n status: number,\n headers: Headers,\n cookies: Cookie,\n resolve: (response: T) => void,\n requestEv: RequestEvent,\n) => WritableStream<Uint8Array>;\n```\n\n**References:** [Cookie](#cookie), [RequestEvent](#requestevent)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/request-handler/types.ts)\n\n## set\n\nSets a `Response` cookie header using the `Set-Cookie` header.\n\n```typescript\nset(name: string, value: string | number | Record<string, any>, options?: CookieOptions): void;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| name | string | |\n| value | string \\\\| number \\\\| Record<string, any> | |\n| options | [CookieOptions](#cookieoptions) | _(Optional)_ |\n\n**Returns:**\n\nvoid\n\n## status\n\n```typescript\nstatus: number;\n```\n"},{"id":"/api/qwik-router-middleware-vercel-edge/","title":"@qwik.dev/qwik-router-middleware-vercel-edge","description":"API reference for @qwik.dev/qwik-router-middleware-vercel-edge.","url":"https://next.qwik.dev/api/qwik-router-middleware-vercel-edge/","content":"# [API](/api.md) › @qwik.dev/router/middleware/vercel-edge\n\n## createQwikCity\n\n> Warning: This API is now obsolete.\n>\n> Use `createQwikRouter` instead. Will be removed in V3\n\n```typescript\ncreateQwikCity: typeof createQwikRouter;\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/vercel-edge/index.ts)\n\n## createQwikRouter\n\n```typescript\nexport declare function createQwikRouter(\n opts: QwikRouterVercelEdgeOptions,\n): (request: Request) => Promise<Response>;\n```\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| opts | [QwikRouterVercelEdgeOptions](#qwikrouterverceledgeoptions) | |\n\n**Returns:**\n\n(request: Request) =&gt; Promise&lt;Response&gt;\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/vercel-edge/index.ts)\n\n## PlatformVercel\n\n```typescript\nexport interface PlatformVercel\n```\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/vercel-edge/index.ts)\n\n## QwikCityVercelEdgeOptions\n\n> Warning: This API is now obsolete.\n>\n> Use `QwikRouterVercelEdgeOptions` instead. Will be removed in V3\n\n```typescript\nexport type QwikCityVercelEdgeOptions = QwikRouterVercelEdgeOptions;\n```\n\n**References:** [QwikRouterVercelEdgeOptions](#qwikrouterverceledgeoptions)\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/vercel-edge/index.ts)\n\n## QwikRouterVercelEdgeOptions\n\n```typescript\nexport interface QwikRouterVercelEdgeOptions extends ServerRenderOptions\n```\n\n**Extends:** ServerRenderOptions\n\n[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/src/middleware/vercel-edge/index.ts)\n"},{"id":"/docs/advanced/backpatching/","title":"Backpatching | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/backpatching/","content":"# Backpatching\n\nSimilar to the [Qwikloader](/docs/advanced/qwikloader.md) that executes a small script, backpatching updates nodes already streamed on the server without waking up the Qwik runtime.\n\nMost useful when building component libraries or apps with interdependent elements that render in varying orders.\n\n### What it is\n\nBackpatching solves a fundamental difference between client and server rendering:\n\n**Client rendering**: Components can render in any order, then establish relationships between each other afterward.\n\n**SSR streaming**: Once HTML is sent to the browser, it's immutable—you can only stream more content forward.\n\nThis creates problems for component libraries where elements need to reference each other (like form inputs linking to their labels via `aria-labelledby`). If the input streams before its label, it can't know the label's ID to set the relationship.\n\nBackpatching automatically fixes these relationships by updating attributes after the entire page has streamed, giving you the same flexibility as client-side rendering.\n\nThis is not Out-of-Order Streaming. It only corrects already-sent attributes without delaying the stream.\n\n### Example\n\n```tsx\nconst fieldContextId = createContextId<{ isDescription: Signal<boolean> }>('field-context');\n\nexport const Field = component$(() => {\n const isDescription = useSignal(false);\n\n const context = {\n isDescription,\n }\n\n useContextProvider(fieldContextId, context);\n\n return (\n <>\n <Label />\n <Input />\n {/* If the description component is not passed, it is a broken aria reference without backpatching, as the input would try to describe an element that does not exist */}\n <Description />\n </>\n )\n})\n\nexport const Label = component$(() => {\n return <label>Label</label>;\n});\n\nexport const Input = component$(() => {\n const context = useContext(fieldContextId);\n\n return <input aria-describedby={context.isDescription.value ? \"description\" : undefined} />;\n});\n\nexport const Description = component$(() => {\n const context = useContext(fieldContextId);\n\n useTask$(() => {\n context.isDescription = true;\n })\n\n return <div id=\"description\">Description</div>;\n});\n```\n\n- Without backpatching, `<Input />` would never know about `<Description />`, leading to incorrect accessibility relationships.\n\n- With backpatching, the aria-describedby attribute on `<Input>` will be automatically corrected even if `<Description>` runs after the input was streamed.\n\n### Limitations\n\n- **Attributes only**: Backpatching is currently limited to updating attributes. It does not change element children/text/structure.\n\n### How it works (high level)\n\nHere's how backpatching works under the hood:\n\n1. **During Server-side streaming**: When a component tries to update an attribute on an element that's already been sent to the browser, Qwik detects this and remembers the intended change.\n\n2. **Element Tracking**: Qwik assigns each element a unique index based on its position in the DOM tree, so it can reliably find the same element in the browser.\n\n3. **Script Generation**: Instead of blocking the stream, Qwik generates a tiny JavaScript snippet that will run later to apply the fix.\n\n4. **Browser Execution**: On page load, this script uses efficient DOM traversal to find and update the target elements with their correct attribute values.\n\n5. **Zero Runtime Impact**: This all happens without waking up the Qwik framework, keeping your app fast and lightweight.\n"},{"id":"/docs/advanced/containers/","title":"Containers | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/containers/","content":"# Containers\n\nEvery Qwik application is contained inside a element, usually the `<html>` element. This element becomes the container for the application. The container is the root element for the application and all components, state and events are contained within.\n\n```html\n<html\n q:container=\"paused\"\n q:version=\"1.9.0\"\n q:render=\"ssr\"\n q:base=\"/build/\"\n q:manifest-hash=\"ggb7b3\"\n q:instance=\"b0yf84vwuup\"\n>\n ...\n</html>\n```\n\n## Container Attributes\n\nSince containers are implicitly rendered by the Qwik runtime, it's not possible to define custom HTML attributes using JSX, however, the SSR render APIs, like `renderToString` and `renderToStream`, provide the `containerAttributes` option to define custom attributes:\n\n```tsx\nrenderToStream(<Root />, {\n containerAttributes: {\n lang: 'en',\n },\n});\n```\n\nThe code above will render the following HTML:\n\n```html\n<html lang=\"en\" q:container=\"paused\" q:version=\"1.9.0\" q:base=\"/build/\">\n ...\n</html>\n```\n\nIn the example above, the `lang` attribute is added to the `<html>` container element.\n\nThis attribute will not be reactive, if the app needs to change this value dynamically, it will need to do through manual DOM manipulation.\n\nAlong with the custom attributes, Qwik will automatically render the `q:container`, `q:version`, `q:render` and `q:base` attributes.\n\n- `q:container` - The container state. This attribute is used by the Qwik runtime to determine if the container is in a paused state or not. The value of this attribute is either `paused` or `resumed`.\n\n- `q:version` - The version of the Qwik runtime.\n\n- `q:render` - Indicated how the container was rendered. The value of this attribute is either `ssr`, `ssr-dev`, `dom` or `dom-dev`.\n\n## Properties\n\nSince the runtime ensures isolation across containers, several containers can coexist within the same document, a container can even contain another nested container, this property allows containers to break up an application into smaller parts.\n\n- **resumed**: Each container can be resumed independently from all other components on the page. Independent resumability further reduces the amount of state which resume deserializes.\n- **updated**: Each container can be updated/replaced at any point using `innerHTML`. This allows a portion of the page to update without forcing a full re-fetch of a complete HTML document without downloading or executing JavaScript.\n- **compiled**: Each container can be compiled and deployed separately from other containers. Separate compilation is especially useful for large-scale applications and large-scale teams working on the applications.\n- **versioned**: Each container can run a different version of the Qwik framework. Allowing for the composability of the website from many small containers.\n\nContainers can be nested in a tree and can communicate and share data. The inter-component communication requires that the components have well-defined boundaries, which we call container protocols.\n\n```html\n<html q:container=\"paused\" q:version=\"1.9.0\" q:base=\"/build/\">\n <head>\n <title>My Qwik Application</title>\n </head>\n <body>\n <header q:container=\"resumed\" q:version=\"1.8.0\" q:base=\"https://server.a/build\">\n <div>\n <h1>This is a header form a container</h1>\n </div>\n </header>\n\n <footer q:container=\"paused\" q:version=\"0.13.0\" q:base=\"https://footer.server.b/\">\n <div>\n <h1>This is a footer</h1>\n </div>\n </footer>\n </body>\n</html>\n```\n\n## Containers vs. Components\n\nContainers sound very similar to components; what are the differences? You can think of a container as a more restricted component. However, components can do a few things which containers can't.\n\n- Containers can only have read-only properties passed into them. This restriction is because container inputs may need to be serialized for SSR requests.\n- Containers don't understand [content projection](/docs/core/slots.md).\n- Containers can't modify the state which has been passed into them.\n\nComponents have restrictions:\n\n- Components must be compiled together and, as a result, share the same bundle artifacts and same Qwik version.\n- On pause, all of the components in the container are serialized together (and then they are resumed together).\n\n## What do containers solve?\n\nContainers allow multiple independent Qwik applications to run on the page and behave as a single application to the user. There are two most common use cases:\n\n1. Routing\n2. Micro-frontend architecture\n\n### Routing\n\nA typical site is composed of two logical parts:\n\n1. The navigation that tends to stay constant across many pages.\n2. The outlet, which is the part of the page that changes based on which route the user navigated to.\n\nWe can model the two parts as two navigation and outlet containers. When the user first navigates to a route, the server responds with HTML, that contains containers for both the navigation and the outlet. Once the user navigates to the second route, there are three ways to solve the navigation:\n\n1. The simplistic approach is to make a full round trip and download an entirely new page. The main downside is that the application loses all of its states on the client.\n2. The classical approach is to treat any further navigation in JavaScript. We replace the current outlet component with the new outlet component and let the new component render. The disadvantage is that we need to download and execute the JavaScript.\n3. The Qwik approach treats the navigation and the outlet as two different containers. The first navigation downloads HTML representing the full page (with both containers). The subsequent navigation fetches the HTML only for the outlet container. This approach is the best of both worlds. The navigation is fast (no JavaScript download or execution), and the application keeps its state in the parent container.\n\n### Micro-frontend\n\nWhen an application gets very large, it becomes impractical to think of it as a single application. A better mental model is that many applications work together to give the user the impression of a single application.\n\nFor large apps, the teams also become large. Large teams usually have different goals and, as a result, different release schedules.\n\nContainers allow a large team to break up the application into many smaller parts and treat each part as a unit with a separate deployment, testing, and version upgrade schedule.\n\nTeams break up the application into containers and clearly define protocols between the containers. As long as the protocols are satisfied, each team can deploy the two containers independently.\n"},{"id":"/docs/advanced/custom-build-dir/","title":"Custom Build Output Directory | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/custom-build-dir/","content":"# Custom Build Output Directory\n\nBy default, the build output directory for Qwik is the `dist` folder in the root folder of the project.\n\nIn certain cases, we may need to make the build output directory different from the default package.\n\n## Wrong Way\n\nUsually with Vite.js we do it like this:\n\n```ts title=\"vite.config.ts\"\nimport { defineConfig } from 'vite';\nimport { qwikVite } from '@qwik.dev/core/optimizer';\nimport { qwikRouter } from '@qwik.dev/router/vite';\nimport { resolve } from 'node:path';\n/* VITE_IMPORTS */\n\nexport default defineConfig(() => {\n const pagesDir = resolve('pages');\n\n return {\n /* VITE_CONFIG */\n build: {\n outDir: '../resources/', // This will be overrided to `dist` by qwikVite() setting\n },\n plugins: [\n qwikRouter({\n pagesDir,\n layouts: {\n default: resolve('src', 'layouts', 'default', 'default.tsx'),\n },\n }),\n qwikVite(/* VITE_QWIK */),\n /* VITE_PLUGINS */\n ],\n };\n});\n```\n\nHowever, it will be overridden by the settings of QwikVite() so nothing happens and the build output directory is still in the `dist` folder\n\n## The Right Way\n\nSo instead of changing the settings in Vite.js directly, we just need to change the settings in QwikVite() like this:\n\n```ts title=\"vite.config.ts\"\nimport { defineConfig } from 'vite';\nimport { qwikVite } from '@qwik.dev/core/optimizer';\nimport { qwikRouter } from '@qwik.dev/router/vite';\nimport tsconfigPaths from 'vite-tsconfig-paths';\n\nexport default defineConfig(() => {\n return {\n ssr: { target: 'webworker', noExternal: true },\n plugins: [\n qwikRouter(),\n qwikVite({\n client: {\n outDir: 'resources/', // This is the right setting\n },\n }),\n tsconfigPaths({ root: '.' }),\n ],\n };\n});\n```\n\nSo that the output build directory becomes `resources`, please rename this folder name as needed.\n"},{"id":"/docs/advanced/eslint/","title":"/docs/advanced/eslint/","description":"","url":"https://next.qwik.dev/docs/advanced/eslint/","content":"[//]: <> (--------------------------------------)\n[//]: <> (......THIS FILE IS AUTOGENERATED......)\n[//]: <> (--------------------------------------)\n[//]: <> ( to update run: pnpm eslint.update )\n[//]: <> ( after changing the rule metadata on )\n[//]: <> ( packages/eslint-plugin-qwik/index.ts )\n[//]: <> ( and update the frontmatter if needed )\n[//]: <> (--------------------------------------)\n\n# ESLint-Rules\n\nQwik comes with its own set of ESLint rules to help developers write better code.\n\n <span class=\"icon icon-inactive\"></span>\n <b>Warn</b> in 'recommended' ruleset\n\n <span class=\"icon\"></span>\n <b>Error</b> in 'recommended' ruleset\n\n <span class=\"icon icon-inactive\"></span>\n <b>Warn</b> in 'strict' ruleset\n\n <span class=\"icon\"></span>\n <b>Error</b> in 'strict' ruleset\n\n## Possible Problems\n\nThese rules are available.\n\n <a href=\"#use-method-usage\" class=\"p-4 flex panel\">\n\n <code>use-method-usage</code>\n <span class=\"rule-description\">Detect invalid use of use hooks.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#valid-lexical-scope\" class=\"p-4 flex panel\">\n\n <code>valid-lexical-scope</code>\n <span class=\"rule-description\">Used the tsc typechecker to detect the capture of unserializable data in dollar ($) scopes.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#loader-location\" class=\"p-4 flex panel\">\n\n <code>loader-location</code>\n <span class=\"rule-description\">Detect declaration location of loader$.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': true,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#no-react-props\" class=\"p-4 flex panel\">\n\n <code>no-react-props</code>\n <span class=\"rule-description\">Disallow usage of React-specific `className`/`htmlFor` props.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#prefer-classlist\" class=\"p-4 flex panel\">\n\n <code>prefer-classlist</code>\n <span class=\"rule-description\">Enforce using the classlist prop over importing a classnames helper. The classlist prop accepts an object `{ [class: string]: boolean }` just like classnames.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': true,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#jsx-no-script-url\" class=\"p-4 flex panel\">\n\n <code>jsx-no-script-url</code>\n <span class=\"rule-description\">Disallow javascript: URLs.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': true,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#jsx-key\" class=\"p-4 flex panel\">\n\n <code>jsx-key</code>\n <span class=\"rule-description\">Disallow missing `key` props in iterators/collection literals</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': true,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#unused-server\" class=\"p-4 flex panel\">\n\n <code>unused-server</code>\n <span class=\"rule-description\">Detect unused server$() functions.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#jsx-img\" class=\"p-4 flex panel\">\n\n <code>jsx-img</code>\n <span class=\"rule-description\">For performance reasons, always provide width and height attributes for &lt;img&gt; elements, it will help to prevent layout shifts.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': true,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#jsx-a\" class=\"p-4 flex panel\">\n\n <code>jsx-a</code>\n <span class=\"rule-description\">For a perfect SEO score, always provide href attribute for &lt;a&gt; elements.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': true,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#no-use-visible-task\" class=\"p-4 flex panel\">\n\n <code>no-use-visible-task</code>\n <span class=\"rule-description\">Detect useVisibleTask$() functions.</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': true,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': true,\n }}\n >\n </span>\n\n </a>\n\n <a href=\"#serializer-signal-usage\" class=\"p-4 flex panel\">\n\n <code>serializer-signal-usage</code>\n <span class=\"rule-description\">Ensure signals used in update() are also used in deserialize()</span>\n\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n <span\n class={{\n 'icon': false,\n 'icon icon-inactive': false,\n }}\n >\n </span>\n\n </a>\n\n## Details\n\n### use-method-usage\n\n <span>Detect invalid use of use hooks.</span>\n\n#### useWrongFunction\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {2} /component$/#a\nexport const Counter = component$(() => {\n const count = useSignal(0);\n});\n```\n\n<span class=\"badge good\">✓</span>\n```tsx {2} /component$/#a\nexport const useCounter = () => {\n const count = useSignal(0);\n return count;\n};\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {2} /component$/#a\nexport const Counter = (() => {\n const count = useSignal(0);\n});\n```\n`use*` methods can only be used in `component$` functions or inside `use*` hooks (e.g. `useCounter`).\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/useMethodUsage.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### valid-lexical-scope\n\n <span>Used the tsc typechecker to detect the capture of unserializable data in dollar ($) scopes.</span>\n\n#### referencesOutside\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {1,4} /print/#a /$((msg: string)/#b)\nimport { component$, useTask$, $ } from '@qwik.dev/core';\n\nexport const HelloWorld = component$(() => {\n const print = $((msg: string) => {\n console.log(msg);\n });\n\n useTask$(() => {\n print(\"Hello World\");\n });\n\n return <h1>Hello</h1>;\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {1,4} /print/#a /(msg: string)/#b)\nimport { component$, useTask$ } from '@qwik.dev/core';\n\nexport const HelloWorld = component$(() => {\n const print = (msg: string) => {\n console.log(msg);\n };\n\n useTask$(() => {\n print(\"Hello World\");\n });\n\n return <h1>Hello</h1>;\n});\n```\nSince Expressions are not serializable, they must be wrapped with `$( ... )` so that the optimizer can split the code into small chunks.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/validLexicalScope.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### invalidJsxDollar\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {1} /click/#a\nimport { component$, $ } from '@qwik.dev/core';\n\nexport const HelloWorld = component$(() => {\n const click = $(() => console.log());\n return (\n <button onClick$={click}>log it</button>\n );\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {1} /click/#a\nimport { component$ } from '@qwik.dev/core';\n\nexport const HelloWorld = component$(() => {\n const click = () => console.log();\n return (\n <button onClick$={click}>log it</button>\n );\n});\n```\nEvent handler must be wrapped with `${ ... }`.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/validLexicalScope.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### mutableIdentifier\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {4} /person/#a\nimport { component$ } from '@qwik.dev/core';\n\nexport const HelloWorld = component$(() => {\n const person = { name: 'Bob' };\n\n return (\n <button onClick$={() => {\n person.name = 'Alice';\n }}>\n {person.name}\n </button>\n );\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {4} /personName/#a\nimport { component$ } from '@qwik.dev/core';\n\nexport const HelloWorld = component$(() => {\n let personName = 'Bob';\n\n return (\n <button onClick$={() => {\n personName = 'Alice';\n }}>\n {personName}\n </button>\n );\n});\n```\nSimple values are not allowed to be mutated. Use an Object instead and edit one of its property.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/validLexicalScope.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### loader-location\n\n <span>Detect declaration location of loader$.</span>\n\n#### invalidLoaderLocation\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {3} /routeLoader$/#a title=\"src/routes/product/[productId]/index.tsx\"\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductDetails = routeLoader$(async (requestEvent) => {\n const res = await fetch(`https://.../products/${requestEvent.params.productId}`);\n const product = await res.json();\n return product as Product;\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {3} /routeLoader$/#a title=\"src/components/product/product.tsx\"\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductDetails = routeLoader$(async (requestEvent) => {\n const res = await fetch(`https://.../products/${requestEvent.params.productId}`);\n const product = await res.json();\n return product as Product;\n});\n```\nThis is not a valid location for a route loader. It only can be used inside the `src/routes` folder, in a `layout.tsx` or `index.tsx` file.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/loaderLocation.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### missingExport\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {3} /export/#a\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductDetails = routeLoader$(async (requestEvent) => {\n const res = await fetch(`https://.../products/${requestEvent.params.productId}`);\n const product = await res.json();\n return product as Product;\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {3}\nimport { routeLoader$ } from '@qwik.dev/router';\n\nconst useProductDetails = routeLoader$(async (requestEvent) => {\n const res = await fetch(`https://.../products/${requestEvent.params.productId}`);\n const product = await res.json();\n return product as Product;\n});\n```\nThe route loader function must be exported.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/loaderLocation.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### wrongName\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {3} /use/#a\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductDetails = routeLoader$(async (requestEvent) => {\n const res = await fetch(`https://.../products/${requestEvent.params.productId}`);\n const product = await res.json();\n return product as Product;\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {3} /get/#a\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const getProductDetails = routeLoader$(async (requestEvent) => {\n const res = await fetch(`https://.../products/${requestEvent.params.productId}`);\n const product = await res.json();\n return product as Product;\n});\n```\nThe route loader function name must start with `use`.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/loaderLocation.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### recommendedValue\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {3} /=>/#a\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductDetails = routeLoader$(async (requestEvent) => {\n const res = await fetch(`https://.../products/${requestEvent.params.productId}`);\n const product = await res.json();\n return product as Product;\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {9} /fetcher/#a\nimport { routeLoader$ } from '@qwik.dev/router';\n\nasync function fetcher() {\n const res = await fetch(`https://.../products/${requestEvent.params.productId}`);\n const product = await res.json();\n return product as Product;\n}\n\nexport const useProductDetails = routeLoader$(fetcher);\n```\nIt is recommended to inline the arrow function. This will help the optimizer make sure that no server code is leaked to the client build.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/loaderLocation.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### no-react-props\n\n <span>Disallow usage of React-specific `className`/`htmlFor` props.</span>\n\n#### prefer\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx /class/#a /for/#b\n<MyReactComponent class=\"foo\" for=\"#password\" />;\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx /className/#a /htmlFor/#b\n<MyReactComponent className=\"foo\" htmlFor=\"#password\" />;\n```\nPrefer `class` and `for` props over `className` and `htmlFor`.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/noReactProps.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### prefer-classlist\n\n <span>Enforce using the classlist prop over importing a classnames helper. The classlist prop accepts an object `{ [class: string]: boolean }` just like classnames.</span>\n\n#### preferClasslist\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {7-10,15,16} /class/#a\nimport { component$ } from '@qwik.dev/core';\nimport styles from './MyComponent.module.css';\n\nexport default component$((props) => {\n // Array syntax example\n return <div class={[\n styles.container,\n 'p-8',\n props.isHighAttention ? 'text-green-500' : 'text-slate-500',\n { active: true}\n ]}>Hello world</div>;\n\n // Object syntax example\n return <div class={{\n 'text-green-500': props.isHighAttention,\n 'p-4': true\n }}>Hello world</div>;\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {2,7-13} /classnames/#a\nimport { component$ } from '@qwik.dev/core';\nimport classnames from 'classnames';\nimport styles from './MyComponent.module.css';\n\nexport default component$((props) => {\n return <div class={classnames(\n styles.container,\n 'p-8',\n {\n 'text-green-500' : props.isHighAttention,\n 'text-slate-500' : !props.isHighAttention,\n },\n { active: true}\n )}>Hello world</div>;\n});\n```\nThe class prop should be used instead of any 3rd party lib to efficiently set classes based on an object.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/preferClasslist.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### jsx-no-script-url\n\n <span>Disallow javascript: URLs.</span>\n\n#### noJSURL\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx\n<button onClick$={() => alert('open the door please')}>ring</button>\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx /javascript:/#a\n<button onClick$=\"javascript:alert('open the door please')\">ring</button>\n```\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxNoScriptUrl.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### jsx-key\n\n <span>Disallow missing `key` props in iterators/collection literals</span>\n\n#### missingIterKey\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {13} /key=/#a\nimport { component$ } from '@qwik.dev/core';\n\nexport const Person = component$(() => {\n const person = {\n firstName: 'John',\n lastName: 'Doe',\n age: 32,\n }\n\n return (\n <ul>\n {Object.keys(person).map((color) => (\n <li key={`person-${key}`}>{person[key]}</li>\n ))}\n </ul>\n );\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {13}\nimport { component$ } from '@qwik.dev/core';\n\nexport const Person = component$(() => {\n const person = {\n firstName: 'John',\n lastName: 'Doe',\n age: 32,\n }\n\n return (\n <ul>\n {Object.keys(person).map((color) => (\n <li>{person[key]}</li>\n ))}\n </ul>\n );\n});\n```\nMissing `key` prop for element in iterator.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxKey.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### missingIterKeyUsePrag\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {14} /Fragment/#a\nimport { component$ } from '@qwik.dev/core';\nimport Card from './Card';\nimport Summary from './Summary';\n\nexport const Person = component$(() => {\n const person = {\n firstName: 'John',\n lastName: 'Doe',\n age: 32,\n }\n\n return (\n {Object.keys(person).map((color) => (\n <Fragment key={`person-${key}`}>\n <Card value={person[key]} />\n <Summary value={person[key]} />\n </Fragment>\n ))}\n );\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {14}\nimport { component$ } from '@qwik.dev/core';\nimport Card from './Card';\nimport Summary from './Summary';\n\nexport const Person = component$(() => {\n const person = {\n firstName: 'John',\n lastName: 'Doe',\n age: 32,\n }\n\n return (\n {Object.keys(person).map((color) => (\n < key={`person-${key}`}>\n <Card value={person[key]} />\n <Summary value={person[key]} />\n </>\n ))}\n );\n});\n```\nMissing `key` prop for element in iterator. The key prop allows for improved rendering performance. Shorthand fragment syntax does not support providing keys. Use `` instead\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxKey.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### missingArrayKey\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {9} /key=/#a\nimport { component$ } from '@qwik.dev/core';\n\nexport const ColorList = component$(() => {\n const colors = ['red', 'green', 'blue'];\n\n return (\n <ul>\n {colors.map((color) => (\n <li key={`color-${color}`}>{color}</li>\n ))}\n </ul>\n );\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {9}\nimport { component$ } from '@qwik.dev/core';\n\nexport const ColorList = component$(() => {\n const colors = ['red', 'green', 'blue'];\n\n return (\n <ul>\n {colors.map((color) => (\n <li>{color}</li>\n ))}\n </ul>\n );\n});\n```\nMissing `key` prop for element in array. The key prop allows for improved rendering performance.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxKey.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### missingArrayKeyUsePrag\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {8,11} /Fragment/#a\nimport { component$, Fragment } from '@qwik.dev/core';\n\nexport const ColorList = component$(() => {\n const colors = ['red', 'green', 'blue'];\n\n return (\n {colors.map((color) => (\n <Fragment key={`color-${color}`}>\n <h2>{color}</h2>\n <p>The color \"${color}\" is a great color.</p>\n </Fragment>\n ))}\n );\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {8,11}\nimport { component$ } from '@qwik.dev/core';\n\nexport const ColorList = component$(() => {\n const colors = ['red', 'green', 'blue'];\n\n return (\n {colors.map((color) => (\n < key={`color-${color}`}>\n <h2>{color}</h2>\n <p>The color \"${color}\" is a great color.</p>\n </>\n ))}\n );\n});\n```\nMissing `key` prop for element in array. The key prop allows for improved rendering performance. Shorthand fragment syntax does not support providing keys. Use `` instead\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxKey.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### nonUniqueKeys\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {9} /key=/#a\nimport { component$ } from '@qwik.dev/core';\n\nexport const ColorList = component$(() => {\n const colors = ['red', 'green', 'blue'];\n\n return (\n <ul>\n {colors.map((color) => (\n <li key={`color-${color}`}>{color}</li>\n ))}\n </ul>\n );\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {9} /key=/#a /not-a-good-idea/#b\nimport { component$ } from '@qwik.dev/core';\n\nexport const ColorList = component$(() => {\n const colors = ['red', 'green', 'blue'];\n\n return (\n <ul>\n {colors.map((color) => (\n <li key=\"not-a-good-idea\">{color}</li>\n ))}\n </ul>\n );\n});\n```\nThe `key` prop must be unique.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxKey.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### unused-server\n\n <span>Detect unused server$() functions.</span>\n\n#### unusedServer\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx {4,12} /serverGreeter/#a\nimport { component$ } from '@qwik.dev/core';\nimport { server$ } from '@qwik.dev/router';\n\nconst serverGreeter = server$((firstName: string, lastName: string) => {\n const greeting = `Hello ${firstName} ${lastName}`;\n return greeting;\n});\n\nexport default component$(() => (\n <button\n onClick$={async () => {\n const greeting = await serverGreeter('John', 'Doe');\n alert(greeting);\n }}\n >\n greet\n </button>\n));\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx {4,12} /serverGreeter/#a\nimport { component$ } from '@qwik.dev/core';\nimport { server$ } from '@qwik.dev/router';\n\nconst serverGreeter = server$((firstName: string, lastName: string) => {\n const greeting = `Hello ${firstName} ${lastName}`;\n return greeting;\n});\n\nexport default component$(() => (\n <button\n onClick$={async () => {\n const greeting = 'not using the server$ function';\n alert(greeting);\n }}\n >\n greet\n </button>\n));\n```\nA `server$` function is declared, but never used.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/unusedServer.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### jsx-img\n\n <span>For performance reasons, always provide width and height attributes for &lt;img&gt; elements, it will help to prevent layout shifts.</span>\n\n#### noLocalSrc\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx\nimport Image from '~/media/image.png';\n<Image />\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx\n\n```\nServing images from public are not optimized, nor cached. Import images using ESM instead.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxImg.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n#### noWidthHeight\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx /width/#a /height/#b\n\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx\n\n```\nFor performance reasons, always provide width and height attributes for `` elements, it will help to prevent layout shifts.\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxImg.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### jsx-a\n\n <span>For a perfect SEO score, always provide href attribute for &lt;a&gt; elements.</span>\n\n#### noHref\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/jsxA.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### no-use-visible-task\n\n <span>Detect useVisibleTask$() functions.</span>\n\n#### noUseVisibleTask\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/noUseVisibleTask.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### serializer-signal-usage\n\n <span>Ensure signals used in update() are also used in deserialize()</span>\n\n#### serializerSignalMismatch\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx /countSignal/#a\nimport { useSignal, useSerializer$ } from '@qwik.dev/core';\nimport MyClass from './my-class';\n\nexport default component$(() => {\n const countSignal = useSignal(0);\n\n useSerializer$(() => ({\n deserialize: () => new MyClass(countSignal.value),\n update: (myClass) => {\n myClass.count = countSignal.value;\n return myClass;\n }\n }));\n\n return <div>{myClass.count}</div>;\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx /countSignal/#a\nimport { useSignal, useSerializer$ } from '@qwik.dev/core';\nimport MyClass from './my-class';\n\nexport default component$(() => {\n const countSignal = useSignal(0);\n\n useSerializer$(() => ({\n deserialize: (count) => new MyClass(count),\n\t\tinitial: 2,\n update: (myClass) => {\n myClass.count = countSignal.value;\n return myClass;\n }\n }));\n\n return <div>{myClass.count}</div>;\n});\n```\nThe countSignal is used in update() but not in deserialize()\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/serializerSignalUsage.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n\n### serializer-signal-usage\n\n <span>Ensure signals used in update() are also used in deserialize()</span>\n\n#### serializerSignalMismatch\n\nExamples of correct code for this rule:\n\n<span class=\"badge good\">✓</span>\n```tsx /countSignal/#a\nimport { useSignal, useSerializer$ } from '@qwik.dev/core';\nimport MyClass from './my-class';\n\nexport default component$(() => {\n const countSignal = useSignal(0);\n\n useSerializer$(() => ({\n deserialize: () => new MyClass(countSignal.value),\n update: (myClass) => {\n myClass.count = countSignal.value;\n return myClass;\n }\n }));\n\n return <div>{myClass.count}</div>;\n});\n```\n\nExamples of incorrect code for this rule:\n\n<span class=\"badge bad\">✕</span>\n```tsx /countSignal/#a\nimport { useSignal, useSerializer$ } from '@qwik.dev/core';\nimport MyClass from './my-class';\n\nexport default component$(() => {\n const countSignal = useSignal(0);\n\n useSerializer$(() => ({\n deserialize: (count) => new MyClass(count),\n\t\tinitial: 2,\n update: (myClass) => {\n myClass.count = countSignal.value;\n return myClass;\n }\n }));\n\n return <div>{myClass.count}</div>;\n});\n```\nThe countSignal is used in update() but not in deserialize()\n\n<div class=\"edit-examples-wrapper\"><a href=\"https://github.com/QwikDev/qwik/edit/main/packages/eslint-plugin-qwik/src/serializerSignalUsage.ts\" target=\"_blank\" class=\"edit-btn\">Edit examples</a></div>\n"},{"id":"/docs/advanced/library/","title":"Component library | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/library/","content":"# Library\n\nQwik uses the [library mode of Vite](https://vitejs.dev/guide/build.html#library-mode) to create component libraries.\n\nIn order to create a component library for Qwik, you need to make sure of specific rules, this is because the Qwik Optimizer needs to recognize your library as a Qwik library.\n\nThe easiest way to create a new component library is to use the build-in `library` starter:\n\n```shell\npnpm create qwik library my-library\n```\n\nThis will create a new folder called `my-library` with the following structure:\n\n```bash {2,11,14}\n|-- README.md\n|-- package.json\n|-- src\n|   |-- components\n|   |   |-- counter\n|   |   |   `-- counter.tsx\n|   |   `-- logo\n|   |   `-- logo.tsx\n|   |-- entry.ssr.tsx\n|   |-- index.ts\n|   `-- root.tsx\n|-- tsconfig.json\n`-- vite.config.ts\n```\n\nThe most important files of a library are a properly configured `package.json` and `vite.config.ts`.\n\n## package.json\n\n```json\n{\n \"name\": \"my-qwik-library-name\",\n \"version\": \"0.0.1\",\n \"description\": \"Create a reusable Qwik component library\",\n \"main\": \"./lib/index.qwik.mjs\",\n \"qwik\": \"./lib/index.qwik.mjs\",\n \"types\": \"./lib-types/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": \"./lib/index.qwik.mjs\",\n \"require\": \"./lib/index.qwik.cjs\",\n \"types\": \"./lib-types/index.d.ts\"\n }\n },\n \"files\": [\n \"lib\",\n \"lib-types\"\n ],\n \"peerDependencies\": {\n \"@qwik.dev/core\": \"^2.0.0\",\n \"@qwik.dev/router\": \"^2.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"@qwik.dev/router\": { \"optional\": true }\n },\n \"type\": \"module\",\n}\n```\n\nNotice the `qwik` field, this is the entry point for the Qwik Optimizer, it will use this file to generate the `index.qwik.mjs` file.\n\nList `@qwik.dev/core`, and `@qwik.dev/router` if you use it, in `peerDependencies`, starting at the version you build with: the build imports runtime helpers that older versions lack. The starter's `vite.config.ts` keeps peer dependencies out of the build, so the app provides a single copy of Qwik. A production server may load your library from `node_modules` as it is, and it shares Qwik's runtime state with the app.\n\nThe file must be called with the `.qwik.mjs` extension, otherwise the Qwik Optimizer will not recognize it.\n\n## vite.config.ts\n\n```ts {8-12}\nimport { defineConfig } from 'vite';\nimport { qwikVite } from '@qwik.dev/core/optimizer';\n\nexport default defineConfig(() => {\n return {\n build: {\n target: 'es2020',\n lib: {\n entry: './src/index.ts',\n formats: ['es', 'cjs'],\n fileName: (format) => `index.qwik.${format === 'es' ? 'mjs' : 'cjs'}`,\n },\n },\n plugins: [qwikVite()],\n };\n});\n```\n\nCompared to a normal Vite configuration, libraries will use [the `lib` mode of Vite](https://vitejs.dev/guide/build.html#library-mode), which requires you to properly configure `build.lib`.\n\n## `src/index.ts`\n\nThis is the entry point of your library, it will export all the components, and functions that you want to expose to the world.\n\n```ts\n// As an example, we will export the Logo and Counter components\nexport { Logo } from './components/logo/logo';\nexport { Counter } from './components/counter/counter';\n```\n\n## Libraries are also Apps\n\nThe library starter is also a standalone Qwik app (without routing, nor Qwik Router), this is the reason why you will find the `entry.ssr.tsx` and `root.tsx` files.\n\nDo not worry about them, they won't be part of the final library, but they are useful during development and testing, so you can test your components in a real Qwik app.\n\n## Build and publish\n\nIn order to publish your library, you have to first build it in `lib` mode and then publish to npm.\n\n```shell\npnpm run build\n```\n\nThis will create a `lib` folder with the following structure. Then you can publish it to npm.\n\n```shell\nnpm publish\n```\n\nBefore first publishing, you might want to update the `package.json` fields, like `name`, `version`, `description`, etc. For any other subsequent publish, you will need to update the `version` field.\n"},{"id":"/docs/advanced/modules-prefetching/","title":"Prefetching | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/modules-prefetching/","content":"# Prefetching Modules\n\nQwik prefetches modules ahead of time. This page describes the **low-level** features of Qwik's prefetching.\n\nPrefetching modules allows applications to start downloading necessary code in the background before users actually need it. The ideal solution is to prefetch only the smallest amount of relevant code that is highly likely to be executed from a user's interaction, while also avoiding any JavaScript that _will not_ be used.\n\nQwik applications excel at downloading and executing a minimal amount of JavaScript, optimizing resource use and performance. By understanding how individual components are used or not used, Qwik can effectively decide which bundles should be prefetched. This targeted approach ensures that only necessary code is loaded.\n\nRemember, the key difference between [resumability and hydration](/docs/concepts/resumable.md), is that resumability enables Qwik applications to avoid executing JavaScript just to restore the event listeners, component tree, and application state. By fundamentally breaking apart a component's event listeners, render function, and state, the amount of code to prefetch is significantly smaller compared to traditional approaches.\n\n## Collecting Used Symbols\n\nWhen Qwik renders an app, it's able to collect which \"symbols\" were used during the render. A symbol includes various parts of a component, which are extracted by the [optimizer](/docs/advanced/optimizer.md) to break apart the application. Individual event listeners, component state, and the component renderer itself are examples of different symbols that could be extracted.\n\nFor example, consider a product page that is mostly static except for one \"Add to cart\" button. When the button is clicked, the user should immediately get feedback to show the product added to the cart. In this example, the Qwik optimizer would be able to understand that the only symbol a user could interact with is the \"Add to cart\" button click event listener.\n\nFor our \"Add to cart\" example, the optimizer collects the symbols only for the click event listener and the renderer for the add to cart widget. There is no need to download, hydrate, and re-render any other parts of the application that aren't relevant. This demonstrates Qwik's capability to determine which interactions are possible and to prefetch only the necessary code for the event listener. In contrast, traditional approaches require the entire application or route, including framework code, to be prefetched just to add the click event listener.\n\n## Preloader\n\nThe preloader is the part of Qwik that decides which JavaScript, if any, Qwik should prefetch in the background. By default, Qwik will prefetch any event handlers on the page, as well as their dependencies.\n\nThis is done probabilistically based on various metrics, including the real-use metrics collected from [Insights](/docs/labs/insights.md)\n\nTo give an example, suppose we have two event handlers, one an `onClick` handler and the other a `beforePrint` handler. The click handler is much more likely to be used than the print handler, so Qwik will prefetch the click handler with a higher probability. Furthermore if both handlers are importing the Qwik core bundle, that core bundle is more important than either of the event handlers, and will be prefetched first.\n\nDuring execution, new segments of code are imported and they each impact the probability of the segments to be loaded.\n\nOnly `$()` segments are part of this graph. A regular dynamic `import()` in your code or in a library is never preloaded by Qwik; you (or the library) are responsible for its timing, for example with `<link rel=\"modulepreload\">` or by calling `import()` early. Once the imported code runs, its own `$()` segments join the preloading as usual.\n\n### Implementation\n\nThe prefetching is done by adding `<link rel=\"modulepreload\">` elements to the document. SSR will determine the most likely bundles and add some `<link>` elements to the HTML.\n\nThen, a script is addded that loads the preloader as well as the module graph, and it is passed all the bundles discovered during the SSR render.\n\nThe preloader will then add the remaining `<link>` elements to the document head, keeping only a few active at a time so that high priority bundles can be added at any time.\n\nMost browsers support `rel=\"modulepreload\"`, but for older browsers, Qwik will fall back to `rel=\"preload\"` attribute.\n\n## Frequently Asked Prefetching Questions\n\n**QUESTION**: _Is lazy loading on user events slow because the user must wait for the code to download?_\n\nYes, that would create a noticeable delay, especially on slow networks. This is why code prefetching is an important part of Qwik applications.\n\nPrefetching code ensures that all of the necessary code for running the application is fetched immediately on navigating to the page. This way, when the user performs an action, the code for that action comes from the prefetch cache rather than the network. The result is that the code execution is instant.\n\n**QUESTION**: _Doesn't code prefetch result in the same behavior as existing frameworks that download and execute all of the code eagerly?_\n\nNo, for several reasons:\n\n- Existing frameworks must download and execute all of the code ([hydration](/docs/concepts/resumable.md)) before the application can be interactive. Typically the download of the code is a smaller time cost than the execution of the code.\n- Qwik code prefetch only downloads but does not execute the code. Therefore even if Qwik prefetches the same amount of code as the existing frameworks, the result is significant time cost savings.\n- Qwik only prefetches the code which is needed for the current page. Qwik avoids downloading code associated with components that are static. In scenarios where more code needs prefetching, Qwik still only reaches the volume that existing frameworks consider their best case. In most cases, Qwik prefetches a small fraction of code compared to the existing frameworks.\n- Prefetching of code can happen on other threads than the main thread. Many browsers can even pre-parse the AST of the code off the main thread.\n- If the user interaction happens before the prefetch is completed, the browser will automatically prioritize the interaction chunk before the remaining prefetch chunks.\n- Qwik can break up the application into many small chunks, and these chunks can be downloaded in the order of probability that the user will interact with them. Existing frameworks have trouble breaking up applications into small chunks, and there is no easy way to prioritize the chunk download order because hydration requires a single \"main\" entry point to the application.\n\n**QUESTION**: _Who is responsible for knowing what code to prefetch?_\n\nQwik automatically generates the prefetch instructions as part of the SSR rendering. By executing the application, Qwik has runtime knowledge of which components are visible, which events the users can trigger and what code will need to be downloaded. The result is that the prefetch is an ideal set of files for this page. No action on the developers' part is required.\n"},{"id":"/docs/advanced/optimizer/","title":"Optimizer Rules | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/optimizer/","content":"# Optimizer\n\nQwik's philosophy is to delay loading code for as long as possible. To do that, Qwik relies on an Optimizer to re-arrange the code for lazy loading. The Optimizer is a code level transformation that runs as part of the rollup.\n\nThe Optimizer is written in Rust (and available as WASM) for instant performance.\n\nThe Optimizer looks for `$` and applies a transformation that extracts the expression following the `$` and turns it into a lazy-loadable and importable symbol.\n\nLet's start by looking at a simple `Counter` example:\n\n```tsx\nexport const Counter = component$(() => {\n const count = useSignal(0);\n\n return <button onClick$={() => count.value++}>{count.value}</button>;\n});\n```\n\nThe above code represents what a developer would write to describe the component. Below are the transformations that the Optimizer applies to the code to make the code lazy-loadable.\n\n```tsx\nconst Counter = component(qrl('./chunk-a.js', 'Counter_onMount'));\n```\n\n```tsx title=\"chunk-a.js\"\nexport const Counter_onMount = () => {\n const count = useSignal(0);\n return <button onClick$={qrl('./chunk-b.js', 'Counter_onClick', [count])}>{count.value}</button>;\n};\n```\n\n```tsx title=\"chunk-b.js\"\nconst Counter_onClick = () => {\n const [count] = useLexicalScope();\n return count.value++;\n};\n```\n\nNotice that every occurrence of `$` results in a new lazy loadable symbol.\n\n## Serialization\n\nSee [serialization](/docs/concepts/resumable.md#serialization) for a discussion of what is serializable.\n\n## Suppressing optimizer diagnostics\n\nSome optimizer diagnostics can be suppressed for a single line with [`@qwik-disable-next-line`](/docs/advanced/optimizer-hints.md).\n\nUse it when a warning is intentional and you want to silence only that specific occurrence.\n"},{"id":"/docs/advanced/qwikloader/","title":"Qwikloader | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/qwikloader/","content":"# Qwikloader\n\nQwik is designed for fine-grained lazy loading of your application. To achieve lazy-loading, Qwik requires a tiny piece of JavaScript to load at the beginning that knows how to download the rest of the application on an as-needed basis. We refer to that JavaScript as Qwikloader.\n\nQwikloader is:\n\n- Small: about 1 kb minified.\n- Fast: it executes in less than 5ms even on mobile devices. (Initial cost, not per event cost.)\n\nHow it is delivered:\n\n- Because of its size, we recommend delivering Qwikloader in an inlined `<script>` tag. This way, the browser does not have to pay the cost of creating another connection to the server.\n\nQwikloader's Purpose:\n\n- Register global browser events.\n- If an event occurs, search the DOM for the corresponding event attribute pointing to the QRL that should be lazy-loaded.\n- Lazy-load the event handler and execute it.\n\n## How does it work\n\nBelow you can find simple HTML with Qwikloader and a button with associated behavior.\n\n```html\n<html>\n <body q:base=\"/build/\">\n <button q-e:click=\"./myHandler.js#clickHandler\">push me</button>\n <script>\n /* Qwikloader */\n </script>\n </body>\n</html>\n```\n\n1. The browser downloads the HTML and executes the inlined Qwikloader script. The Qwikloader sets up global listeners for all browser events.\n2. The user clicks on the `<button>`. The browser generates a `click` event that bubbles up the DOM until the Qwikloader's global listener intercepts it.\n3. The Qwikloader retraces the event path and searches for `q-e:click` attribute on the elements.\n4. The Qwikloader uses the `q-e:click` and `q:base` attributes along with the `document.baseURI` to build a full URL for fetching the lazy-loaded handler. Assuming the original page was served up from `http://localhost/` the fetch URL becomes `http://localhost/build/myHandler.js`.\n5. Qwikloader retrieves the `clickHandler` symbol, exported from `http://localhost/build/myHandler.js` and invokes it.\n\n## Events and the Qwikloader\n\nThe registration of the listener creates two problems in the context of SSR/SSG that Qwik needs to solve. (For context, remember that Qwik is resumable, that is, it can continue executing the application from where the server paused without being forced to download and execute code eagerly.)\n\n1. **listener location**: Qwik needs to know where the events are in the HTML which came from the SSR/SSG.\n2. **listener code**: Qwik needs to know what code should run if the event is triggered.\n\nWithout the above information, Qwik would be forced to download the component template and execute it so that the listener location and closure can be recovered. This process is known as hydration, and Qwik explicitly tries to avoid hydration.\n\nQwik serializes the event listeners into the DOM in the form of [QRLs](/docs/advanced/qrl.md). For example:\n\n```html\n<div>\n <button q-e:click=\"./chunk-a.js#Counter_button_onClick[0]\">0</button>\n</div>\n```\n\nThe critical thing to notice is that Qwik generated an `q-e:click` attribute, containing the value `./chunk-a.js#Counter_button_onClick[0]`. In the above example the `q-e:click` attribute solves the listener location problem, and the attribute value solves the listener code problem. By serializing the listeners into the HTML Qwik applications do not need to perform hydration on startup.\n"},{"id":"/docs/advanced/state-prewarm/","title":"State Prewarm | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/state-prewarm/","content":"# State Prewarm\n\nQwik resumes an SSR-rendered application from serialized state in the HTML. By default, that state\nstays lazy in the browser: Qwik parses the state payload, but individual state roots are\ndeserialized only when code reads them.\n\nThis keeps startup work low, which is usually the best default. On very large pages, however, the\nfirst read can touch a large connected state graph. In that case the lazy read can turn into one\nlarge synchronous task. `statePrewarm` is an opt-in render option that performs that state work\nduring client resume and slices it into yielded tasks.\n\n## What It Does\n\nWhen `statePrewarm` is enabled, Qwik eagerly deserializes the container state as part of client\nresume.\n\n- The number is a root-count threshold.\n- If the serialized state has fewer roots than the threshold, state remains lazy.\n- If the serialized state has at least that many roots, Qwik deserializes the state eagerly during\n resume.\n- The work is yielded across small tasks, so the browser can stay responsive.\n\n`statePrewarm` does not load all QRL chunks or run components. It only\nprepares serialized state so later synchronous state reads are cheaper.\n\n The default is `false`. With no `statePrewarm` option, Qwik keeps serialized state lazy.\n\n## When To Use It\n\nUse `statePrewarm` only when profiling shows that the first state access creates a long task during\nresume. This is most useful for pages with a large serialized state graph, such as data-heavy product\npages, dashboards, search pages, or large routed documents.\n\nIt is usually not needed for small or typical pages. Prewarming can increase the amount of work done\nduring client resume, even though that work is split into smaller tasks.\n\nGood reasons to enable it:\n\n- A performance trace shows a long deserialize or state-inflate task after the first state read.\n- The page serializes thousands of state roots.\n- The page feels blocked soon after resume, and the stack points to state deserialization.\n\nReasons to keep it disabled:\n\n- The page has little serialized state.\n- The state is rarely read on startup.\n- You want the smallest possible amount of client work during resume.\n\n## Setting The Threshold\n\nSet `statePrewarm` on the server render options. The value is the minimum number of serialized state\nroots required before Qwik prewarms the state.\n\n```tsx\nimport { renderToStream, type RenderOptions } from '@qwik.dev/core/server';\nimport Root from './root';\n\nexport default function (opts: RenderOptions) {\n return renderToStream(<Root />, {\n ...opts,\n statePrewarm: 2048,\n });\n}\n```\n\nThe same option is available with `renderToString`:\n\n```tsx\nimport { renderToString, type RenderOptions } from '@qwik.dev/core/server';\nimport Root from './root';\n\nexport default function (opts: RenderOptions) {\n return renderToString(<Root />, {\n ...opts,\n statePrewarm: 2048,\n });\n}\n```\n\nIn Qwik Router applications, set `statePrewarm` in the server entry or custom renderer where\n`renderToStream` receives the adapter-provided render options:\n\n```tsx\nexport default function (opts: RenderOptions) {\n return renderToStream(<Root />, {\n ...opts,\n statePrewarm: 2048,\n });\n}\n```\n\nUse a lower number to prewarm smaller state payloads:\n\n```tsx\nrenderToStream(<Root />, {\n ...opts,\n statePrewarm: 512,\n});\n```\n\nUse `0` to prewarm any non-empty serialized state:\n\n```tsx\nrenderToStream(<Root />, {\n ...opts,\n statePrewarm: 0,\n});\n```\n\n## Disabling It\n\nThe default is disabled, so most applications do not need to set anything.\n\n```tsx\nrenderToStream(<Root />, {\n ...opts,\n statePrewarm: false,\n});\n```\n\n`false` and `undefined` both mean that Qwik will not emit the internal prewarm marker and the\nbrowser will keep state lazy.\n\n## Choosing A Value\n\nStart with a conservative value such as `2048` and compare traces before and after the change. The\ngoal is not to reduce total deserialization work. The goal is to avoid one large synchronous task by\ndoing the state work earlier in the resume process and slicing it.\n\nAfter rebuilding and cache-busting the app, check:\n\n- Whether long tasks caused by state deserialization disappear.\n- Whether state work during resume is split into smaller tasks.\n- Whether the additional resume work is acceptable for the page.\n\nIf the page still has long tasks after enabling `statePrewarm`, inspect the trace for other causes\nsuch as layout, rendering, third-party scripts, image decode, or application microtasks.\n"},{"id":"/docs/advanced/vite/","title":"Vite | Advanced","description":"","url":"https://next.qwik.dev/docs/advanced/vite/","content":"# Vite\n\nQwik leverages [Vite](https://vitejs.dev/) to provide a fast development experience. Vite is a build tool that serves your code via native ES Modules during development.\nThis means that it doesn't need to bundle your code or transpile it to work in the browser. It also comes with lightning fast hot module replacement (HMR) that updates your browser instantly when you make changes to your code.\n\n## Configuration\n\nAfter scaffolding a new Qwik project, you'll find a `vite.config.js` file in the root of your project. This is where you can configure Vite.\n\n## Vite Plugins\n\nQwik comes with two plugins that make it easy to use Vite with Qwik and Qwik Router.\n\n```ts title=\"vite.config.ts\"\nimport { defineConfig } from 'vite';\nimport { qwikRouter } from '@qwik.dev/router/vite';\nimport { qwikVite } from '@qwik.dev/core/optimizer';\nimport tsconfigPaths from 'vite-tsconfig-paths';\n\nexport default defineConfig(() => {\n return {\n plugins: [qwikRouter(), qwikVite(), tsconfigPaths({ root: '.' })],\n };\n});\n```\n\n### `qwikVite()`\n\nTo modify the configuration, you can pass an object to the `qwikVite` function. Possible options are:\n\n#### `debug`\n\n```js\n/**\n * Prints verbose Qwik plugin debug logs and shows chunk file names ouput in preview/production environments.\n * Default `false`\n */\ndebug?: boolean;\n```\n\n#### `entryStrategy`\n\n```js\n/**\n * The Qwik entry strategy to use while bundling for production.\n * During development the type is always `hook`.\n * Default `{ type: \"smart\" }`)\n */\nentryStrategy?: EntryStrategy;\n```\n\n#### `srcDir`\n\n```js\n/**\n * The source directory to find all the Qwik components. Since Qwik\n * does not have a single input, the `srcDir` is use to recursively\n * find Qwik files.\n * Default `src`\n */\nsrcDir?: string;\n```\n\n#### `tsconfigFileNames`\n\n```js\n/**\n * List of tsconfig.json files to use for ESLint warnings during development.\n * Default `['tsconfig.json']`\n */\ntsconfigFileNames?: string[];\n```\n\n#### `vendorRoots`\n\n```js\n/**\n * List of directories to recursively search for Qwik components or Vendors.\n * Default `[]`\n */\nvendorRoots?: string[];\n```\n\n#### `client`\n\n```js\nclient?: {\n /**\n * The entry point for the client builds. Typically this would be\n * the application's main component.\n * Default `src/components/app/app.tsx`\n */\n input?: string[] | string;\n /**\n * Output directory for the client build.\n * Default `dist`\n */\n outDir?: string;\n /**\n * The client build will create a manifest and this hook\n * is called with the generated build data.\n * Default `undefined`\n */\n manifestOutput?: (manifest: QwikManifest) => Promise<void> | void;\n};\n```\n\n#### `ssr`\n\n```js\nssr?: {\n /**\n * The entry point for the SSR renderer. This file should export\n * a `render()` function. This entry point and `render()` export\n * function is also used for Vite's SSR development and Node.js\n * debug mode.\n * Default `src/entry.ssr.tsx`\n */\n input?: string;\n /**\n * Output directory for the server build.\n * Default `dist`\n */\n outDir?: string;\n /**\n * The SSR build requires the manifest generated during the client build.\n * By default, this plugin will wire the client manifest to the ssr build.\n * However, the `manifestInput` option can be used to manually provide a manifest.\n * Default `undefined`\n */\n manifestInput?: QwikManifest;\n};\n```\n\n#### `optimizerOptions`\n\n```js\n/**\n * Options for the Qwik optimizer.\n * Default `undefined`\n */\noptimizerOptions?: OptimizerOptions;\n```\n\n#### `transformedModuleOutput`\n\n```js\n/**\n * Hook that's called after the build and provides all of the transformed\n * modules that were used before bundling.\n */\ntransformedModuleOutput?:\n | ((transformedModules: TransformModule[]) => Promise<void> | void)\n | null;\n```\n\n#### `devTools`\n\n```js\ndevTools?: {\n /**\n * Validates image sizes for CLS issues during development.\n * In case of issues, provides you with a correct image size resolutions.\n * If set to `false`, image dev tool will be disabled.\n */\n imageDevTools?: boolean | true;\n /**\n * Press-hold the defined keys to enable qwik dev inspector.\n * By default the behavior is activated by pressing the left or right `Alt` key.\n * If set to `false`, qwik dev inspector will be disabled.\n * Valid values are `KeyboardEvent.code` values.\n * Please note that the 'Left' and 'Right' suffixes are ignored.\n */\n clickToSource?: string[] | false;\n};\n```\n\n### `qwikRouter()`\n\nTo modify the configuration, you can pass an object to the `qwikRouter` function. Possible options are:\n\n#### `routesDir`\n\n```js\n/**\n * Directory of the `routes`. Defaults to `src/routes`.\n */\nroutesDir?: string;\n```\n\n#### `serverPluginsDir`\n\n```js\n/**\n * Directory of the `server plugins`. Defaults to `src/server-plugins`.\n */\nserverPluginsDir?: string;\n```\n\n#### `basePathname`\n\n```js\n/**\n * The base pathname is used to create absolute URL paths up to\n * the `hostname`, and must always start and end with a\n * `/`. Defaults to `/`.\n */\nbasePathname?: string;\n```\n\n#### `trailingSlash`\n\n```js\n/**\n * Ensure a trailing slash ends page urls. Defaults to `true`.\n * (Note: Previous versions defaulted to `false`).\n */\ntrailingSlash?: boolean;\n```\n\n#### `mdxPlugins`\n\n```js\n/**\n * Enable or disable MDX plugins included by default in qwik-router.\n */\nmdxPlugins?: MdxPlugins;\n```\n\n#### `mdx`\n\n```js\n/**\n* MDX Options https://mdxjs.com/\n*/\nmdx?: any;\n```\n\n#### `platform`\n\n```js\n/**\n* The platform object which can be used to mock the Cloudflare bindings.\n*/\nplatform?: Record<string, unknown>;\n```\n\n## Troubleshooting\n\nBefore creating an issue on the Qwik repository please check the `Troubleshooting` section of the [Vite documentation](https://vitejs.dev/guide/troubleshooting.html) and make sure you're using the recommended version.\n"},{"id":"/docs/concepts/progressive/","title":"Progressive | Concepts","description":"","url":"https://next.qwik.dev/docs/concepts/progressive/","content":"# Progressive\n\nProgressive is about downloading code according to the application's needs, without eagerly downloading the entire code base.\n\nThis connects to the [core principle](/docs/concepts/think-qwik.md) of Qwik which focuses on delaying **the loading** and execution of JavaScript for as long as possible. Qwik needs to break up the application into many lazy loadable chunks to achieve that.\n\n## Current state-of-the-art\n\n[Existing frameworks suffer from two problems](https://www.builder.io/blog/dont-blame-the-developer-for-what-the-frameworks-did):\n\n- Lazy loading boundaries are completely delegated to the developer\n- Frameworks can only lazy load components that are not in the current render tree.\n\nThe problem is that the frameworks need to reconcile their internal state with the DOM. And this means that at least once in the application [hydration](../../concepts/resumable/#resumable-vs-hydration) occurs. Frameworks are required to be able to do a full render to rebuild the framework's internal state. After the first render, the frameworks can be more surgical about their updates, but the damage has been done, the code has been downloaded. So, two issues now arise:\n\n- Frameworks need to download and execute components to rebuild the render tree on startup. (See [hydration is pure overhead](https://www.builder.io/blog/hydration-is-pure-overhead)) This forces eager download and execution of all components in the render tree.\n- The event handlers come with the components even though they are not needed at the time of rendering. The inclusion of event handlers forces the download of unnecessary code.\n\n## Solution\n\nQwik's architecture takes full advantage of modern tooling to automate the problem of entry point generation. Developers can write components normally, while the Qwik optimizer will split the components into chunks and download them when needed.\n\nIn addition, the framework runtime does not need to download code that is not required for interactivity, even if the component is part of the render tree.\n\n### Optimizer\n\n[Optimizer](/docs/advanced/optimizer.md) is a code transformation that extracts functions into top-level importable symbols, which allows the Qwik runtime to lazy-load the JavaScript on an as-needed basis.\n\nThe Optimizer and Qwik runtime work together to achieve the desired result of fine-grained lazy loading.\n\nWithout the Optimizer, either:\n\n- The code would have to be broken up by the developer into importable parts. This would be unnatural to write an application, making for a bad DX.\n- The application would have to load a lot of unnecessary code as there would be no lazy-loaded boundaries.\n\nQwik runtime must understand the Optimizer output. What needs to be understood here is that by breaking up the component into lazy-loadable chunks, the lazy loading requirement introduces asynchronous code into the framework. The framework has to be written differently to take asynchronicity into account. Existing frameworks assume that all code is available synchronously. This assumption prevents an easy insertion of lazy-loading into existing frameworks. (For example, when a new component is created, the framework assumes that its initialization code can be invoked in a synchronous fashion. If this is the first time component is referenced, then its code needs to be lazy-loaded, and therefore the framework must take that into account).\n\n### Lazy-loading\n\nLazy-loading is asynchronous. Qwik is an asynchronous framework. Qwik understands that at any time, it may not have a reference to a callback, and therefore, it may need to lazy-load it. (In contrast, most existing frameworks assume that all of the code is available synchronously, making lazy-loading non-trivial).\n\nIn Qwik everything is lazy-loadable:\n\n- Component on render - initialization block and render block\n- Component tasks - side-effects, only downloaded if inputs change\n- Listeners - only downloaded on interaction\n- Styles - only downloaded if the server did not already provide them\n\nLazy-loading is a core property of the framework and not an afterthought.\n\n### Optimizer and `$`\n\nTake a look at this example again:\n\n```tsx\n// the `$` suffix for `component` indicates that the component should be\n// lazy-loaded.\nexport const Counter = component$(() => {\n const count = useSignal(0);\n\n // the `$` suffix for `onClick` indicates that the implementation for\n // the handler should be lazy-loaded.\n return <button onClick$={() => count.value++}>{count.value}</button>;\n});\n```\n\nNotice the presence of `$` in the code. `$` is a marker that tells the Optimizer that the function\nfollowing it should be lazy-loaded. The `$` is a single character that hints to the Optimizer and the developer to let them know\nthat asynchronous lazy-loading occurs here.\n"},{"id":"/docs/deprecated-features/","title":"Deprecated Features | Guides","description":"","url":"https://next.qwik.dev/docs/deprecated-features/","content":"# Deprecated features\n\nThese features were deprecated in the preparation of Qwik for its stable release.\n\nIf you happened to come across one of them and don't know what its replacement is, we quickly mention them in this table with the link to their new documentation .\n\n## Qwik\n\n### Deprecated functions and their replacements\n\n----\n\n| Deprecated | Replacements |\n| :-------- | :-------\n| `useWatch$` | [useTask$](https://qwik.dev/docs/core/tasks/#usetask) |\n| `useMount$` | [useTask$](https://qwik.dev/docs/core/tasks/#usetask) |\n| `useServerMount` | [useTask$](https://qwik.dev/docs/core/tasks/#usetask) + [isServer](https://qwik.dev/docs/guides/qwik-nutshell/#isbrowser-&-isserver-conditionals)\n| `useClientMount` | [useTask$](https://qwik.dev/docs/core/tasks/#usetask) + [isBrowser](https://qwik.dev/docs/guides/qwik-nutshell/#isbrowser-&-isserver-conditionals)\n| `useClientEffect` - `useClientEffectQrl` | [useVisibleTask$](https://qwik.dev/docs/core/tasks/#usevisibletask) |\n| `useBrowserVisibleTask` - `useBrowserVisibleTaskQrl` | [useVisibleTask$](https://qwik.dev/docs/core/tasks/#usevisibletask) |\n| `useEnvData` | [useServerData](https://qwik.dev/api/qwik/#useserverdata) |\n| `useRef` | [useSignal](https://qwik.dev/docs/core/state/#usesignal) |\n| `createContext` | [createContextId](https://qwik.dev/docs/core/context/#createcontextid) |\n\n## Qwik Router (Formerly named \"Qwik City\")\n\n### Deprecated functions and their replacements\n----\n\n| Deprecated | Replacements\n| :-------- | :-------\n| `useEndpoint ` | [routeLoader$](https://qwik.dev/docs/route-loader/#routeloader)\n| `loader$` - `loaderQrl` | [routeLoader$](https://qwik.dev/docs/route-loader/#routeloader)\n| `action$` - `actionQrl` | [routeAction$](https://qwik.dev/docs/action/#routeaction)\n"},{"id":"/docs/faq/","title":"Frequently Asked Questions | Introduction","description":"","url":"https://next.qwik.dev/docs/faq/","content":"# FAQ\n\n## Is _@QwikDev_ a sentient AI?\n\nYes, and I am very funny too! [follow me](https://twitter.com/QwikDev)\n\n## How is Qwik different from other frameworks?\n\nQwik has **two** hidden superpowers:\n- The fastest TTI (Time To Interactive) among reactive web frameworks thanks to its javascript streaming architecture.\n- An SSR-first resumable mental model, that is as easy to grasp as good ol' CSR/SPA.\n\nThanks to the ability to run render functions and tasks only on the server during startup, writing Qwik code feels like SSR and CSR are part of the same world, without the worries of hitting a performance wall along the road.\n\nYou can focus on code and features without worrying so much about the amount of code or how it's written.\n\nSee [think qwik](/docs/concepts/think-qwik.md) for a deep dive on Qwik's mental modal.\n\n## Why another framework?\n\nWithout a resumable model, javascript streaming is hardly achievable. Even with some sort of on-demand lazy hydration — e.g. by hydrating a component on user interaction for example — all side effects would still need to run eagerly on the client.\n\nIf you're already familiar with Qwik, this would be the equivalent of doing all your side effects solely in `useVisibleTask$` hooks and downloading eagerly all those chunks on startup, but worse since the bundles would also include the rest of the component's code.\n\n## Is Qwik hard to learn?\n\nQwik’s syntax and APIs are pretty similar to other reactive frameworks. It follows JSX, compiles to fine-grained reactivity with hooks, effects, and data-fetching.\n\nThe major authoring DX difference is its SSR-first, resumable architecture (`useTask$` vs `useVisibleTask$`), which is straightforward to learn and involves far less gotchas than hydration mismatch runtime errors. Qwik warns you about SSR serialization boundaries at authoring time so you and your agents can be confident the code will work in production.\n\nQwik also comes with Qwik Router which handles file based routing and data fetching through loaders and actions, similar to React Router.\n\nMany resources are at your disposal to learn Qwik: the [getting started](./getting-started) guide, the interactive [tutorial](../../tutorial/welcome/overview/) the documentation itself and online video courses.\n\n## What are all those `$` signs?\n\nYou might have noticed there are more [`$`](/docs/advanced/dollar.md) signs than usual in Qwik apps, such as: `component$()`, `useTask$()`, and `<div onClick$={() => console.log('click')} />`. It serves as a marker to split your code into smaller segmented chunks and enable javascript streaming prioritized event preloads.\n\n**Example:**\n```tsx\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n console.log('render');\n return <button onClick$={() => console.log('hello')}>Hello Qwik</button>;\n});\n```\n\nThanks to the `$` syntax, the component above is split into:\n```js title=\"app.js\"\nimport { componentQrl, qrl } from '@qwik.dev/core';\n\nconst App = /*#__PURE__*/ componentQrl(\n qrl(() => import('./app_component_akbu84a8zes.js'), 'App_component_AkbU84a8zes')\n);\n\nexport { App };\n```\n\n```js title=\"app_component_akbu84a8zes.js\"\nimport { jsx as _jsx } from '@qwik.dev/core/jsx-runtime';\nimport { qrl } from '@qwik.dev/core';\nexport const App_component_AkbU84a8zes = () => {\n console.log('render');\n return /*#__PURE__*/ _jsx('p', {\n onClick$: qrl(\n () => import('./app_component_p_onclick_01pegc10cpw'),\n 'App_component_p_onClick_01pEgC10cpw'\n ),\n children: 'Hello Qwik',\n });\n};\n```\n\n```js title=\"app_component_p_onclick_01pegc10cpw.js\"\nexport const App_component_p_onClick_01pEgC10cpw = () => console.log('hello');\n```\n\nThe `$` is not related to `jQuery`, Svelte or any other framework.\n\n## Isn't lazy-loading on user interaction bad for the user experience?\n\nA common misconception is that since Qwik relies on lazy-loading, it downloads the javascript modules on user interaction. Qwik **preloads** the javascript modules on startup so that in most cases they are already preloaded and can execute right away on user interaction. It is only when the code for a given user interaction has **not** been preloaded **yet** that Qwik will JIT preload the corresponding chunks to execute them as soon as possible.\n\nIn order to improve the likelihood of the code being preloaded for a given user interaction, Qwik uses code metadata to speculatively preload the code that is most likely to be requested. In addition, [Qwik insights](/docs/labs/insights.md) can be used to gather user data and know which modules are most likely to be requested by users and therefore know how to prioritize them and in which order.\n\nWhat is bad for the user experience, is having to eagerly execute and therefore download a lot of code on startup, slowing down TTI proportionally to the amount of code. This is what the other reactive frameworks do, and prevents them from being able to take advantage of speculative and JIT preloading.\n\n## Does Qwik generate too many javascript chunks?\n\nIn dev mode, Qwik splits your code into the smallest possible chunks. In production, it bundles related chunks back together to avoid making too many requests. It is also possible to not bundle related chunks together, which reduces cache invalidation and therefore improves cache hit rates but can be slightly more expensive if your deployment provider charges on a per-request basis.\n\n## Does Qwik use a vDOM (Virtual DOM)?\n\nNot in the traditional sense. In most cases, Qwik relies on serialized state and direct fine-grained reactivity DOM updates using signals. There is no component re-render mechanisms to know and think about.\n\nIf the change in state does not have a structural change then Qwik will most likely not use vDOM. For example:\n```ts title=\"No DOM structure change, only update value\"\nexport const NoStructuralChange = component$(() => {\n const count = useSignal(0);\n\n return (\n <>\n {/* This will not cause vDOM to activate. (No DOM structure change, only update text value) */}\n <div>Count: {count.value}</div>\n <button onClick$={() => count.value++}>+1</button>\n </>\n );\n});\n```\n\nWhen there is a structural change, Qwik relies on a what we call a vNode tree. In the following example, the DOM structure needs to be updated (replace `<h1>` with `<button>`), so the vNode tree will be used for rendering:\n```ts title=\"DOM structure change\"\nexport const StructuralChange = component$(() => {\n const isLoggedIn = useSignal(false);\n return (\n <div>\n {isLoggedIn.value ? <h1>you are logged in!</h1> : <button>Log in</button>}\n </div>\n )\n});\n```\n\nUnlike with React's vDOM, re-rendering the vNode tree does not mean re-running hooks. In Qwik, it is purely a question of how much DOM needs to be updated.\n\n## Can Qwik Router do SPA?\n\nYes, and you can even choose between MPA and SPA on a `<Link>` vs `<a>` basis. Using the `<Link>` component triggers an SPA navigation while `<a>` naturally triggers a standard browser MPA navigation.\n\nMPA vs SPA is no longer an architectural decision taken at the beginning of the project, but a decision made for every link.\n\n## When should I use SPA over MPA in Qwik?\nIn Qwik, the difference isn’t as big as it is for the other reactive frameworks.\n\nIn terms of performance, SPA requires a tiny inline script but allows instant navigations once all the code has been preloaded and the other routes Link prefetched. On the other hand, if there are still ongoing preloads, MPA is faster because there is no need to load render functions on the client.\n\nIn terms of UI, SPA retains state while MPA resets it. SPA also means different accessibility patterns.\n\n## Can I enjoy the rich React ecosystem?\n\nYes! Qwik can `qwikify$` React components, [check out the docs](/docs/integrations/react.md).\n\n## Does Qwik do partial hydration?\n\nNo. Partial hydration (or island architecture), popularized by [Astro](https://astro.build/), is about breaking the app into islands of interactivity to avoid [full-page hydration](https://www.builder.io/blog/hydration-is-pure-overhead), where all existing components in the page need to be downloaded and executed.\n\nFor this to work, developers need to manually define the islands, and then manually describe in which situations they should be hydrated. The islands also cannot communicate with each other.\n\nInstead, Qwik components do not hydrate at all. Qwik achieves this through a powerful serialization system that serializes only the necessary state in the reactivity graph. This way, the app can resume without eagerly running any JS.\n\nWe think resumability scales without the negative trade-offs of partial hydration.\n\n## Which browsers are supported?\n\nQwik uses Vite under the hood so you shouldn't need to worry about whether the browser supports it if you're targeting modern web users.\nHere is the [Vite browser compatibility](https://vite.dev/guide/build.html#browser-compatibility).\n\n## In which languages is Qwik written?\n\nMost of Qwik is written in [TypeScript](https://www.typescriptlang.org/), a superset of JavaScript that adds optional static typing and other features. However, the Qwik compiler (or optimizer) is written in Rust, a language that is very fast and memory efficient.\n\n## Does Qwik have a community?\n\nYes! there is a growing community of Qwik developers at [Discord](https://qwik.dev/chat) and [GitHub](https://github.com/QwikDev/qwik). They are making amazing contributions to the framework, building sites at scale, and helping each other. [Join us](https://qwik.dev/chat).\n\n## Is Qwik an \"Alex Russell Approved\" framework?\n\nYes! Alex Russell ([@slightlylate](https://twitter.com/slightlylate)), known for his contributions to PWAs, W3C TAG, WC, TC39 & ES6, Chrome Frame, Dojo, and more, is often highly critical of JavaScript frameworks. Nonetheless, [he approves of Qwik](https://infrequently.org/2023/02/the-market-for-lemons/#fn-alex-approved-1).\n\n## Is it true that Qwik serializes too much data in the HTML?\n\nFalse. Qwik serializes only the data that is needed for the current page. If a page has 1000 components but only one is interactive the amount of data serialized is proportional to the amount of interactivity, not the amount of components.\n\n## Is Qwik open source?\n\nYes, the license is [MIT](https://github.com/QwikDev/qwik/blob/main/LICENSE). Installing Qwik will not bloat your node_modules nor your lawyers.\n\n## What’s the catch?\n\nThere’s none. We are open about the pros and cons and like with any tool choice, there are tradeoffs that should be considered. Javascript streaming as an innovation speeds up TTI significantly and therefore benefits the user experience, but it comes with a slightly different DX and less maturity.\n\nOn the DX, developers must learn about the async $ syntax, serialization boundaries, and `useTask$` vs `useVisibleTask$`.\n\nOn maturity, Qwik remains a relatively new, less battle tested reactive framework, and as such may evolve more rapidly and more significantly. You may also have to `qwikify$` certain niche library components until there is a Qwik port for it. And some areas of the framework, like SSR render or reactivity performance might still not be fully optimized.\n\nOverall, we believe those cons are largely outweighed by the fact that Qwik scales significantly more and is much smoother to use as applications grow.\n"},{"id":"/docs/advanced/complex-forms/","title":"Complex Forms | Advanced","description":"Learn how to create complex forms with arrays and objects.","url":"https://next.qwik.dev/docs/advanced/complex-forms/","content":"# Complex Forms\n\n## What are Complex Forms?\n\nComplex forms would typically contain data in a structure that is more than just simple key/value pairs. For example, a list of people who each have their own email, phone and street address. This would essentially be an array of objects.\n\n## Input naming\n\n### Objects\n\nNested items can be created by separating the items with `.` (dot) in the name. For example, `person.name` would be converted to `{ person: { name: 'sam' } }`.\n\n### Arrays\n\nArrays, either top-level or nested are created by specifying the zero-based index in the name. For example `person.pets.0` would be converted to `{ person: { pets: [ 'cat' ] } }`.\n\n### Example\n\nThe key to creating a complex form is in the naming of the inputs. Below would be an example of the list described above:\n```html\n<form>\n <input name=\"person.0.name\" value=\"Sam\">\n <input name=\"person.0.email\" value=\"sam@complexform.com\">\n <input name=\"person.0.pets.0\" value=\"cat\">\n <input name=\"person.0.pets.1\" value=\"dog\">\n <input name=\"person.0.address.street\" value=\"1234 Example Ave.\">\n <input name=\"person.0.address.city\" value=\"Qwik\">\n <input name=\"person.0.address.state\" value=\"IA\">\n <input name=\"person.0.address.zip\" value=\"00000\">\n <input name=\"person.0.pets.0\" value=\"beaver\">\n\n <input name=\"person.1.name\" value=\"Bonnie\">\n <input name=\"person.1.email\" value=\"bonnie@hishai.net\">\n <input name=\"person.1.address.street\" value=\"768 Resolution Way\">\n <input name=\"person.1.address.city\" value=\"Jaffa\">\n <input name=\"person.1.address.state\" value=\"IL\">\n <input name=\"person.1.address.zip\" value=\"01948\">\n</form>\n```\n\n#### Output object\n\nAfter submitting the form the data would be parsed in an object like this:\n```json\n{\n \"person\": [\n {\n \"name\": \"Sam\",\n \"email\": \"sam@complexform.com\",\n \"address\": {\n \"street\": \"1234 Example Ave.\",\n \"city\": \"Qwik\",\n \"state\": \"IA\",\n \"zip\": \"00000\"\n },\n \"pets\": [\"beaver\"]\n },\n {\n \"name\": \"Bonnie\",\n \"email\": \"bonnie@hishai.net\",\n \"address\": {\n \"street\": \"768 Resolution Way\",\n \"city\": \"Jaffa\",\n \"state\": \"IL\",\n \"zip\": \"01948\"\n }\n }\n ]\n}\n```\n\n## Using with Actions\n\nComplex forms can be validated using zod$ with routeAction$ and globalAction$. Continuing with the previous examples it would look like this:\n\n```tsx\nexport const action = routeAction$(\n async (person) => {\n return { success: true, person, };\n },\n // Zod schema is used to validate the FormData\n zod$({\n person: z.array(\n z.object({\n name: z.string(),\n email: z.string().email(),\n address: z.object({\n street: z.string(),\n city: z.string(),\n state: z.string(),\n zip: z.coerce.number()\n }),\n pets: z.array(z.string())\n })\n ),\n })\n);\n```\n\n### Field errors also in dot notation (almost)\n\nIf you use dot notation, the error messages are also returned in dot notation in the `fieldErrors` property. This has the advantage that the input name and fieldError key match.\n\nFor the this action:\n```tsx\nexport const addPersonAction = routeAction$(\n async person => {\n return { success: true, person };\n },\n // Zod schema is used to validate the FormData\n zod$({\n person: z.object({\n name: z.string(),\n email: z.string().email(),\n address: z.object({\n street: z.string(),\n city: z.string(),\n state: z.string(),\n zip: z.coerce.number(),\n }),\n pets: z.array(z.string()),\n }),\n })\n);\n```\n\nYou would get this kind of `fieldErrors` if all are wrong:\n\n```ts\n{\n \"person.name\": \"Invalid string\",\n \"person.email\": \"Invalid email\",\n \"person.address.street\": \"Invalid string\",\n \"person.address.city\": \"Invalid string\",\n \"person.address.state\": \"Invalid string\",\n \"person.address.zip\": \"Invalid number\",\n \"person.pets[]\": [\"Required\"]\n}\n```\n\nIf you make person an array, the error messages will switch to a slightly different notation as:\n\n```ts\n{\n \"person[].name\": [\"Invalid string\"],\n \"person[].email\": [\"Invalid email\"],\n \"person[].address.street\": [\"Invalid string\"],\n \"person[].address.city\": [\"Invalid string\"],\n \"person[].address.state\": [\"Invalid string\"],\n \"person[].address.zip\": [\"Invalid number\"],\n \"person[].pets[]\": [\"Required\"]\n}\n```\n\nIf you completely forget to assign a value to an array type, lets say you completely forget person in the form. The error is then in `fieldErrors[\"person[]\"]`.\n\nThis way you can easily match the error messages to the input names like this:\n\n```tsx\nexport const useAddPersonAction = routeAction$(\n async person => {\n console.log(person);\n return { success: true, person };\n },\n zod$({\n person: z.object({\n name: z.string().min(2),\n email: z.string().email(),\n address: z.object({\n street: z.string().min(2),\n city: z.string().min(2),\n state: z.string().min(2),\n zip: z.coerce.number(),\n }),\n pets: z.array(z.string().min(2)),\n }),\n })\n);\n\nexport default component$(() => {\n const testAction = useAddPersonAction();\n\n const renderError = (errorMessage: string | undefined) => {\n if (!errorMessage) return null;\n return <p class=\"error\">{errorMessage}</p>;\n };\n\n return (\n <Form action={testAction}>\n <input type=\"email\" name=\"person.email\" placeholder=\"Email\" />\n {renderError(testAction.value?.fieldErrors?.[\"person.email\"])}\n <input type=\"text\" name=\"person.name\" placeholder=\"Name\" />\n {renderError(testAction.value?.fieldErrors?.[\"person.name\"])}\n <input type=\"text\" name=\"person.address.street\" placeholder=\"Street\" />\n {renderError(testAction.value?.fieldErrors?.[\"person.address.street\"])}\n <input type=\"text\" name=\"person.address.city\" placeholder=\"City\" />\n {renderError(testAction.value?.fieldErrors?.[\"person.address.city\"])}\n <input type=\"text\" name=\"person.address.state\" placeholder=\"State\" />\n {renderError(testAction.value?.fieldErrors?.[\"person.address.state\"])}\n <input type=\"text\" name=\"person.address.zip\" placeholder=\"Zip\" />\n {renderError(testAction.value?.fieldErrors?.[\"person.address.zip\"])}\n <input type=\"text\" name=\"person.pets.0\" placeholder=\"Pet 1\" />\n {renderError(testAction.value?.fieldErrors?.[\"person.pets[]\"]?.[0])}\n <button>Send</button>\n </Form>\n );\n});\n```\nFor this example the `fieldErrors` look like this:\n\n```json\n{\n \"person.name\": \"String must contain at least 2 character(s)\",\n \"person.email\": \"Invalid email\",\n \"person.address.street\": \"String must contain at least 2 character(s)\",\n \"person.address.city\": \"String must contain at least 2 character(s)\",\n \"person.address.state\": \"String must contain at least 2 character(s)\",\n \"person.pets[]\": [\n \"String must contain at least 2 character(s)\"\n ]\n}\n```\n"},{"id":"/docs/advanced/content-security-policy/","title":"Content Security Policy | Advanced","description":"Learn how to create a content security policy (CSP) to keep your Qwik app safe.","url":"https://next.qwik.dev/docs/advanced/content-security-policy/","content":"# Content Security Policy\n\n## What is CSP?\n\n[Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft, to site defacement, to malware distribution.\n\n## Steps to integrate\n\nThese steps only work for SSR approach. If you are using the Server Side Generation approach, you don't have an up and running server, so this code will not run during the page request.\n\n### Add a route plugin\n\nTo add the middleware plugin to your application, simply add a file named ```plugin@your-plugin-name.ts``` to the routes folder.\nThis file will be loaded with every request, allowing you to add headers, modify the response, and more.\n\n```bash {3} /plugin@csp\\.ts/ title=\"Add the plugin\"\nsrc/\n`-- routes/\n |-- plugin@csp.ts # The plugin which runs on every request (route middleware)\n |-- contact/\n | `-- index.mdx # https://example.com/contact\n |-- about/\n | `-- index.md # https://example.com/about\n |-- index.mdx # https://example.com/\n |\n `-- layout.tsx # This layout is used for all pages\n```\n\n#### Example\n\n**CSP Template Defaults**\n\nThis template provides very permissive backward-compatible defaults. It is highly recommended that you customize it to better suit your specific use case. As this is an advanced topic, you should take a closer look at [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) or [web.dev](https://web.dev/csp/) to get a better understanding of CSP. Please note that in dev mode the Vite scripts have no nonce and will report. For this reason, the example will not add csp in dev mode.\n\n```typescript title=\"src/routes/plugin@csp.ts\"\nimport type { RequestHandler } from \"@qwik.dev/router\";\nimport { isDev } from \"@qwik.dev/core\";\n\nexport const onRequest: RequestHandler = event => {\n if (isDev) return; // Will not return CSP headers in dev mode\n const nonce = Date.now().toString(36); // Your custom nonce logic here\n event.sharedMap.set(\"@nonce\", nonce);\n const csp = [\n `default-src 'self' 'unsafe-inline'`,\n `font-src 'self'`,\n `img-src 'self' 'unsafe-inline' data:`,\n `script-src 'self' 'unsafe-inline' https: 'nonce-${nonce}' 'strict-dynamic'`,\n `style-src 'self' 'unsafe-inline'`,\n `frame-src 'self' 'nonce-${nonce}'`,\n `object-src 'none'`,\n `base-uri 'self'`,\n ];\n\n event.headers.set(\"Content-Security-Policy\", csp.join(\"; \"));\n};\n```\n\n### Custom scripts\n\nIf you have custom script tags that you need to add the nonce to, you can use the `useServerData` hook to get the nonce from the server and add it to your script tags.\n\n```tsx {2,5} /nonce/ title=\"src/components/some-component.tsx\"\nexport default component$(() => {\n const nonce = useServerData<string | undefined>(\"nonce\");\n return (\n <div>\n <script nonce={nonce}>alert(\"Hello world\")</script>\n </div>\n );\n});\n```\n\n## Validate your CSP\n\nThere is a great tool to validate your CSP: [https://csp-evaluator.withgoogle.com/](https://csp-evaluator.withgoogle.com/)\n"},{"id":"/docs/advanced/menu/","title":"Menu | Advanced","description":"How to use menus to define site navigation.","url":"https://next.qwik.dev/docs/advanced/menu/","content":"# Menu\n\nMenus allow you to describe the site navigation structure in a simple declarative way. Menus come in two steps:\n\n1. Defining a `menu.md` file that contains the menu structure for the directory it's in.\n2. Using the [`useContent()`](/docs/api.md#usecontent) function to retrieve the menu structure in a template for rendering. [Read more here](/docs/api.md#usecontent)\n\n## File Structure\n\nFirst layout files as follows:\n\n```bash\nsrc/\n`-- routes/\n `-- some/\n |-- menu.md\n |-- layout.tsx\n `-- path/\n `-- index.tsx # https://example.com/some/path\n```\n\nNavigating to `https://example.com/some/path` activates:\n\n- `src/routes/some/path/index.tsx`: This component will be used for rendering the page content.\n- `src/routes/some/layout.tsx`: This layout will be used to provide content around the `src/routes/some/path/index.tsx`. Internally the layout can use `src/routes/some/menu.md` to render the menus.\n- `src/routes/some/menu.md`: This file will be used to declare the menu structure which will be rendered by `src/routes/some/layout.tsx`.\n\n## Declaring Menu Structure\n\nUse `menu.md` to declare the menu structure.\n\n- Use the headings (`#`, `##`, etc..) to define menu depth\n- Use the bulleted list (`-`) to define menu items.\n\n```markdown title=\"src/route/some/menu.md\"\n# Docs\n\n## Getting Started\n\n- [Introduction](introduction/index.md)\n\n## Components\n\n- [Basics](/docs/core/basics/)\n```\n\n## Retrieving Menu Structure\n\nAt runtime, any component can retrieve the menu with [`useContent()`](/docs/api.md#usecontent) hook. The type returned is `ContentMenu`.\n\nThe example above will return:\n\n```javascript\n{\n text: \"Docs\",\n items: [\n {\n text: \"Getting Started\",\n items: [\n {\n text: \"Introduction\",\n href: \"/docs/introduction\"\n }\n ],\n },\n {\n text: \"Components\",\n items: [\n {\n text: \"Basics\",\n href: \"/docs/(qwik)/core/basics\"\n }\n ],\n },\n ],\n}\n```\n\n## Using `ContentMenu` in a layout\n\nWhile [`useContent()`](/docs/api.md#usecontent) can be invoked from any component that is part of the current route, it is typically used in a layout component (or a component used by layout) to render the menu. An example usage is shown here:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { useLocation, useContent } from '@qwik.dev/router';\nexport default component$(() => {\n const { menu } = useContent();\n const { url } = useLocation();\n\n return (\n <nav class=\"menu\">\n {menu\n ? menu.items?.map((item, index) => (\n <div key={index}>\n <h5>{item.text}</h5>\n <ul>\n {item.items?.map((item, subIndex) => (\n <li key={`item-${index}-${subIndex}`}>\n <a\n href={item.href}\n class={{\n 'is-active': url.pathname === item.href,\n }}\n >\n {item.text}\n </a>\n </li>\n ))}\n </ul>\n </div>\n ))\n : null}\n </nav>\n );\n});\n```\n"},{"id":"/docs/advanced/plugins/","title":"Qwik Plugins | Qwik Router","description":"Learn about advanced routing in Qwik Router, including 404 page handling, grouped layouts, named layouts, nested layouts, and plugin.ts files.","url":"https://next.qwik.dev/docs/advanced/plugins/","content":"# Qwik Plugins\nQwik plugins, named as `plugin.ts` or `plugin@<name>.ts`, handle incoming requests prior to root layout execution and are located in the `src/routes` directory. Request handlers like `onRequest`, `onGet`, `onPost` in these plugins are called before `server$` functions. For multiple plugins, `plugin.ts` handlers execute first, followed by `plugin@<name>.ts` handlers in alphabetical order. Middleware functions should be defined in `plugin.ts` to ensure execution for all requests.\n\n### The order of execution of `plugin.ts` files\n\n If `plugin.ts` file exists and if it has exported request handlers, then they are executed first.\n\nThen exported request handlers from `plugin@<name>.ts` files are executed in alphabetical order of the file names. For example, `onGet` from `plugin@auth.ts` is executed before `onGet` from `plugin@security.ts` because `auth` is alphabetically before `security`.\n\nFinally, if a `server$` function exists, it's executed last.\n\n## Middleware and `server$`\n\nWhen using `server$`, it's important to understand how [middleware functions](/docs/middleware.md#middleware-function) are executed. Middleware functions defined in `layout` files do not run for `server$` requests. This can lead to confusion, especially when developers expect certain middleware to be executed for both page requests and `server$` requests.\n\nTo ensure that a middleware function runs for both types of requests, it should be defined in the `plugin.ts` file. This ensures that the middleware is executed consistently for all incoming requests, regardless of whether they are normal page requests or `server$` requests.\n"},{"id":"/docs/advanced/request-handling/","title":"Request Handling | Advanced","description":"How to handle requests in Qwik Router, including REST endpoints, and middlewares.","url":"https://next.qwik.dev/docs/advanced/request-handling/","content":"# Request Handling\n\nEach `layout.ts` and `index.ts` file inside the `src/routes` directory has the ability to access the current HTTP request, response, and URL. This allows you to retrieve and modify data, and even respond with custom content.\n\nQwik Router implements a middleware system based on the hierarchy of the `src/routes` directory. The middleware system is used to handle HTTP requests and responses and is available to pages, layouts, and [endpoints](/docs/endpoints.md).\n\nEach route can add HTTP request and response handlers, allowing developers to retrieve and modify data. The handlers can also be used by [endpoints](/docs/endpoints.md), which only respond with data rather than a page's HTML.\n\nThis feature enables you to handle any request event, have side effects on the request pipeline, just before you render the component and respond with custom content. It is available to pages, layouts and endpoint routes, but not on regular components.\n\n## Request and Response Handlers\n\nOn pages, layouts, and [endpoints](/docs/endpoints.md), we can access request data by implementing request handler functions such as `onGet`, `onPost`, `onPut`, etc. These functions are executed according to the [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) used for this route.\n\nAdditionally, an `onRequest` function can be used to handle any request method, rather than a specific one, in the form of a [middleware](/docs/middleware.md). For example, if both `onGet` and `onRequest` is provided, for a `GET` request, the `onGet` will be called. However, in this scenario, if a `POST` request method came in, then the `onRequest` handler would be called since an `onPost` was not provided.\nThe `onRequest` is available as a catch-all to any request methods that do not have a specific method.\n\n```tsx\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler<ProductData> = async ({ params }) => {\n // put your DB access here (hard coding data for simplicity)\n return {\n skuId: params.skuId,\n price: 123.45,\n description: `Description for ${params.skuId}`,\n };\n};\n```\n\n## Request Event\n\nThe request handler functions receive a `RequestEvent` argument which has the following properties:\n\n| Field | Description |\n| ---------- | ----------------------------------------------------------------------------- |\n| `request` | The request object |\n| `response` | The response object, which can be used to set response `headers` and `status` |\n| `url` | URL which includes `pathname`, `hostname`, etc. |\n| `next` | Next middleware function |\n| `abort` | Request abort function |\n| `params` | Custom user params found within the URL |\n| `cookie` | Get and set cookies. |\n| `internalRequest` | Internal JSON request kind (`'loader'` or `'action'`) or `false` for normal page requests. |\n| `platform` | Platform data object (useful for Cloudflare, Netlify, etc) |\n\n### Cookie\n\n```tsx\ninterface Cookie {\n get: (key: string) => CookieValue | null;\n set: (key: string, value: string | number | Record<string, any>, options?: CookieOptions) => void;\n delete: (key: string) => void;\n has: (key: string) => boolean;\n}\n```\n\n**get**\nTakes a string with the cookie name and returns the `CookieValue`, if present and null if not.\n\n```tsx\ninterface CookieValue {\n value: string;\n json: <T = unknown>() => T;\n number: () => number;\n}\n```\n\nA cookie value is a simple record with three fields:\n\n1. `value`: Contains the cookie value as a string\n2. `json()`: Runs `JSON.parse()` on the value and returns the result\n3. `number()`: Runs `Number()` on the value and returns the result\n\n**getAll**\nReturns an object with all cookies, if any. _This is sometimes required if the names of cookies are unknown and must be parsed through._\n\n**set**\nTakes a key and value and creates a header that will be appended to the response. Value can be a `string | number | Record<string, any>`\n\nAs a third argument, you can optionally provide a `CookieOptions` record for setting additional fields.\n\n```tsx\nexport interface CookieOptions {\n domain?: string;\n expires?: Date | string;\n httpOnly?: boolean;\n maxAge?: number | [number, 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks'];\n path?: string;\n sameSite?: 'lax' | 'none' | 'strict';\n secure?: boolean;\n}\n```\n\nFor more information on these attributes and their values, please refer to [the MDN article on the Set-Cookie header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes).\n\n**delete**\nAppends a header with the provided key to the cookie. The new header will have an expired date in the `expires` field, telling the browsers to remove it.\n\n```tsx\ncookie.delete('my-cookie');\n// equivalent to\ncookie.set('my-cookie', 'deleted', new Date(0));\n// or\ncookie.set('my-cookie', '');\n```\n\nOptionally, you can set the path, sameSite and/or domain when deleting the cookie. If your cookie was created with a path/domain, you must set these fields for the deletion to take effect.\n\n```tsx\ncookie.delete('my-cookie', { domain: 'https://qwik.dev', path: '/docs/' });\n```\n\n**has**\nA convenience method which returns true or false based on the presence of the provided key in cookie.\n\n```tsx\ncookie.has('my-cookie');\n```\n"},{"id":"/docs/advanced/sitemaps/","title":"Generating Sitemaps | Advanced","description":"Learn how to generate a sitemap for your site in Qwik Router.","url":"https://next.qwik.dev/docs/advanced/sitemaps/","content":"# Generating Sitemaps\n\n## Generating Sitemaps in SSG\n\nBy default, when Static Site Generated (SSG) pages are built, a [sitemap](https://en.wikipedia.org/wiki/Sitemaps) is generated for the site. The `sitemap.xml` is automatically generated based on the pages that were built. This means that if you have a page that is not built, it will not be included in the sitemap.\n\n### Configuration\n\nThe sitemap can be configured using the adapter's vite config file. The example below is configuring the Cloudflare adapter. The default sitemap file path is `sitemap.xml`, but you can use the `sitemapOutFile` option to change the file path.\n\n```ts\n plugins: [\n cloudflarePagesAdapter({\n ssg: {\n include: ['/*'],\n origin: 'https://qwik.dev',\n sitemapOutFile: 'sitemap.xml',\n },\n }),\n ]\n```\n\nThe `include` option is used to specify which pages should be built, which also adds them to the sitemap. Any pages added to the `exclude` option will also exclude them from the sitemap.\n\nThe `origin` option is used to specify the origin of the site and is used to generate the absolute URLs for the sitemap.\n\n### robots.txt\n\nDepending on your site setup, you'll probably want to add a [robots.txt](https://en.wikipedia.org/wiki/Robots.txt) file to your site. This can be done by adding a `robots.txt` file to the `public` directory. Any file in the `public` directory is treated as a static file and deploy alongside the build. The following is an example of a `public/robots.txt` file:\n\n```bash\nUser-agent: *\nAllow: /\n\nSitemap: https://<YOUR_HOSTNAME>/sitemap.xml\n```\n\nNote the added `Sitemap` directive to the `robots.txt` file which tells search engines where to find the sitemap for your site. Be sure to replace `<YOUR_HOSTNAME>` with the hostname of your site.\n\n## Generating Dynamic Sitemaps in SSR\n\nIn addition to generating sitemaps for Static Site Generation (SSG), you can also generate sitemaps dynamically with Server-Side Rendering (SSR). This is useful if your site has content that is not known at build time or is frequently updated.\n\nTo generate a dynamic sitemap in SSR, you can create a route that serves a `dynamic-sitemap.xml` file based on your site’s routes and other dynamic content. Below is an example of how to set this up.\n\n### Create a Sitemap Function\n\nFirst, create a function that generates the sitemap XML based on the routes you want to include. You can create this function in a file such as `src/routes/dynamic-sitemap.xml/create-sitemap.ts`:\n\n```typescript\n// src/routes/dynamic-sitemap.xml/create-sitemap.ts\n\nexport interface SitemapEntry {\n loc: string;\n priority: number;\n}\n\nexport function createSitemap(entries: SitemapEntry[]) {\n const baseUrl = \"https://<YOUR_HOSTNAME>\";\n\n return `\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n${entries.map(\n (entry) => `\n <url>\n <loc>${baseUrl}${entry.loc.startsWith(\"/\") ? \"\" : \"/\"}${entry.loc}</loc>\n <priority>${entry.priority}</priority>\n </url>`,\n)}\n</urlset>`.trim();\n}\n```\n\n### Set Up a Route for the Dynamic Sitemap\n\nNext, set up a route that will use the sitemap function to generate the sitemap dynamically. Create a file like src/routes/dynamic-sitemap.xml/index.tsx:\n\n```tsx\n// src/routes/dynamic-sitemap.xml/index.tsx\n\nimport { getRoutes, type RequestHandler, type RouteData } from \"@qwik.dev/router\";\nimport { createSitemap } from \"./create-sitemap\";\n\n// Collects the static page paths of the route trie; dynamic routes need your own data.\nconst collectPaths = (node: RouteData, path = \"/\"): string[] => {\n const paths = node._I ? [path] : [];\n for (const group of node._M ?? []) {\n paths.push(...collectPaths(group, path));\n }\n for (const [key, child] of Object.entries(node)) {\n // A single `_` marks metadata; `__x` stores the static segment `_x`.\n if (key.startsWith(\"_\") && !key.startsWith(\"__\")) {\n continue;\n }\n const segment = key.startsWith(\"__\") ? key.slice(1) : key;\n paths.push(...collectPaths(child as RouteData, `${path}${segment}/`));\n }\n return paths;\n};\n\nexport const onGet: RequestHandler = async (ev) => {\n const siteRoutes = collectPaths(await getRoutes())\n .filter(route => route !== \"/\"); // Exclude the '/' route\n\n const sitemap = createSitemap([\n { loc: \"/\", priority: 1 }, // Manually include the root route\n ...siteRoutes.map((route) => ({\n loc: route,\n priority: 0.9, // Default priority, adjust as needed\n })),\n ]);\n\n const response = new Response(sitemap, {\n status: 200,\n headers: { \"Content-Type\": \"text/xml\" },\n });\n\n ev.send(response);\n};\n```\n\nThis route dynamically creates the sitemap XML based on the routes in your Qwik application.\n\n### robots.txt\n\nTo ensure that search engines know where to find your dynamic sitemap, you should also add or update your robots.txt file. Add the following line to your robots.txt file, which is typically located in your public directory:\n\n```bash\nUser-agent: *\nAllow: /\n\n# Uncomment the following line and replace <unindexedFolder> with the actual folder name you want to disallow\n# Disallow: /<unindexedFolder>/\n\nSitemap: https://<YOUR_HOSTNAME>/dynamic-sitemap.xml\n```\n\nBe sure to replace `<YOUR_HOSTNAME>` with your actual site URL.\n\nThis setup will dynamically generate and serve a dynamic.sitemap.xml whenever it is requested, keeping it up to date with the latest routes and changes to your site.\n"},{"id":"/docs/advanced/speculative-module-fetching/","title":"Speculative Module Fetching | Advanced","description":"Learn how Qwik handles loading bundles in the background and filling the cache with Speculative Module Fetching.","url":"https://next.qwik.dev/docs/advanced/speculative-module-fetching/","content":"# Speculative Module Fetching\n\nQwik is able to load a page and become interactive extremely fast due to its ability to startup _without_ JavaScript. In addition to this, Speculative Module Fetching is a powerful feature that allows Qwik to pre-populate the browser's cache in a background thread.\n\nQwik's goal is to optimize loading by caching only the necessary parts of the application based on potential user interactions. It avoids loading unnecessary bundles by understanding which interactions are not possible.\n\n### Pre-populating the Cache\n\nEach page load will pre-populate the cache with bundles that _could_ be executed on the page by the user at that moment. For example, let's say that the page has a click listener on a button. When the page loads, the Qwik's first job is to ensure the code for that click listener is already in the [browser's cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache). When the user clicks the button, Qwik makes a request to the event listener's function and any code dependencies to execute that function. This might include importing other modules.\n\nThe initial page load prepares the cache for the next probable interaction and also downloads other necessary code incrementally. When a follow-up interaction happens, such as opening a modal or menu, Qwik will ask the browser to preload the code for that interaction. Pre-populating the cache happens continuously as users interact with the application.\n\n### Reducing Network Waterfalls\n\nA network waterfall occurs when multiple requests are made sequentially, one after another. This sequential process can degrade performance significantly since the time to download all necessary modules is extended, compared to a scenario where all modules begin downloading at the same time in parallel.\n\nBelow is an example with three modules: A, B and C. Module A imports B, and B imports C. The HTML document is what starts the waterfall by first requesting Module A.\n\n```ts\nimport './b.js';\nconsole.log('Module A');\n```\n\n```ts\nimport './c.js';\nconsole.log('Module B');\n```\n\n```ts\nconsole.log('Module C');\n```\n\n```html\n<script type=\"module\" src=\"./a.js\"></script>\n```\n\nIn this example, when Module `A` is first requested, the browser has no idea that it should also start requesting Module `B` and `C`. It doesn't even know it needs to start requesting Module `B`, until AFTER Module `A` has finished downloading. It's a common problem in that the browser doesn't know ahead of time what it should start to request, until after each module has finished downloading.\n\nHowever, Qwik knows the module graph and controls QRL segment loading, we do know all of the modules which _will_ be requested next. So when Qwik sees that it will require a module, it will tell the browser to preload it and all of its dependencies.\n\n### Details\n\nThe Qwik build process generates a `q-manifest.json` file. The `q-manifest.json` includes a detailed module graph of how bundles are associated and which symbols are within each bundle.\n\nThis is then further used to generate the `build/q-bundle-graph-xyz.json` file, which is a compact representation of the module graph, including probabilities of which bundlers are more likely to be requested next given a certain bundle has loaded, and is loaded by Qwik to preload QRL segment loading.\n\nQwik Router also injects all routes with their dependencies into this bundlegraph file.\n\nWhen a container resumes, it will fetch the bundlegraph file (probably from the cache) and use it to prefetch modules needed for event handlers and routes.\n\nStatic imports are preloaded with high priority, and dynamic imports are preloaded with low priority. The browser will decide when to download the modules.\n\nThe preloading happens with the `_preload` function, which is an internal Qwik API. It works by traversing the bundlegraph and adding `<link rel=\"modulepreload\">` tags for each bundle that is likely to be requested next.\n\n## During Development\n\nSpeculative module fetching only really works in preview or on a production build. In development, we don't have the bundle graph available, so we can't prevent waterfalls from happening. However, we do ask the browser to preload the bundles that are most likely to be requested after SSR.\n"},{"id":"/docs/advanced/static-assets/","title":"Static Assets | Advanced","description":"How to serve static assets in your Qwik app.","url":"https://next.qwik.dev/docs/advanced/static-assets/","content":"# Static Assets\n\nUse the `/public` folder to store all static assets such as images, fonts, etc.\n\nAll static assets are served from your server's root (`/` as in `https://example.com/`) folder and superimposed under your routes (routes have priority).\n\n```bash\npublic/\n|-- favicon.ico # https://example.com/favicon.ico\n`-- images/\n `-- logo.png # https://example.com/images/logo.png\n```\n"},{"id":"/docs/api/","title":"API Reference | Qwik Router","description":"Qwik Router API reference.","url":"https://next.qwik.dev/docs/api/","content":"# API reference\n\n## `useContent()`\n\nThe [`useContent()`](/docs/api.md#usecontent) function retrieves the nearest content information for the current route. The returned object includes:\n\n```ts\nheadings: ContentHeading[] | undefined;\nmenu: ContentMenu | undefined;\n```\n\nThe `headings` array includes data about a markdown file's `<h1>` to `<h6>` [html heading elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements).\n\nMenus are contextual data declared with `menu.md` files. See [menus file definition](/docs/advanced/menu.md) for more information on the file format and location.\n\n## `useDocumentHead()`\n\nUse the `useDocumentHead()` function to read the document [head metadata](/docs/pages.md#head-export) that is generated from `head` exports and markdown files.\n\n`useDocumentHead()` retrieves a readonly `DocumentHeadValue` object:\n\n```ts\nexport interface DocumentHeadValue<\n FrontMatter extends Record<string, any> = Record<string, unknown>,\n> {\n /** Sets `document.title`. */\n readonly title?: string;\n /** Used to manually set meta tags in the head. */\n readonly meta?: readonly DocumentMeta[];\n /** Used to manually append `<link>` elements to the `<head>`. */\n readonly links?: readonly DocumentLink[];\n /** Used to manually append `<style>` elements to the `<head>`. */\n readonly styles?: readonly DocumentStyle[];\n /** Used to manually append `<script>` elements to the `<head>`. */\n readonly scripts?: readonly DocumentScript[];\n /**\n * Arbitrary object containing custom data. When the document head is created from markdown files,\n * the frontmatter attributes that are not recognized as a well-known meta names (such as title,\n * description, author, etc...), are stored in this property.\n */\n readonly frontmatter?: Readonly<FrontMatter>;\n}\n```\n\nTo get this data into the `<head>` element of the document, you can do it manually, for example:\n\n```tsx\nimport { component$ } from \"@qwik.dev/core\";\nimport { useDocumentHead } from \"@qwik.dev/router\";\n\n/** Use inside of the `<head>` element in `src/root.tsx` */\nexport const RouterHead = component$(() => {\n const head = useDocumentHead();\n\n return (\n <>\n {head.title && <title>{head.title}</title>}\n {head.meta.map((m) => (\n <meta {...m} />\n ))}\n {head.links.map((l) => (\n <link {...l} />\n ))}\n {head.styles.map((s) => {\n // Support for the old `props` property\n const props = s.props || s;\n return (\n <style\n {...props}\n dangerouslySetInnerHTML={s.style || props.dangerouslySetInnerHTML}\n key={s.key}\n />\n );\n })}\n {head.scripts.map((s) => {\n // Support for the old `props` property\n const props = s.props || s;\n return (\n <script\n {...props}\n dangerouslySetInnerHTML={s.script || props.dangerouslySetInnerHTML}\n key={s.key}\n />\n );\n })}\n </>\n );\n});\n```\n\nYou can also use the [`DocumentHeadTags`](#documentheadtags) component to render the head tags.\n\n## `<DocumentHeadTags>`\n\nThe `<DocumentHeadTags>` component renders the head tags collected from `head` exports and markdown files.\n\nPlace it inside of the `<head>` element in `src/root.tsx`:\n\n```tsx\n// ...\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n\n <link rel=\"canonical\" href={loc.url.href} />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"/favicon.svg\" />\n\n <DocumentHeadTags />\n </head>\n// ...\n```\n\nYou can partially override the head, for example if you want to change the title:\n\n```tsx\nimport { DocumentHeadTags, useDocumentHead } from '@qwik.dev/router';\n\nexport default component$(() => {\n const head = useDocumentHead();\n return <DocumentHeadTags title={`${head.title} - My App`} />;\n});\n```\n\nYou don't have to use this component, you can also do it yourself for full control. Just copy the code from this component and modify it to your needs.\n\nNote that this component normally only runs once, during SSR. You can use Signals in your `src/root.tsx` to make runtime changes to `<head>` if needed.\n\n## `useLocation()`\n\nUse the [`useLocation()`](/docs/api.md#uselocation) function to retrieve a `RouteLocation` object for the current location.\n\nThe `useLocation()` function provides the current URL and params. It also determines if the app is currently navigating, which is useful for showing a loading indicator.\n\n```tsx\nexport interface RouteLocation {\n /**\n * Route params extracted from the URL.\n */\n readonly params: Record<string, string>;\n /**\n * The current URL.\n */\n readonly url: URL;\n /**\n * True if the app is currently navigating.\n */\n readonly isNavigating: boolean;\n}\n```\n\nThe return value of [`useLocation()`](/docs/api.md#uselocation) is similar to `document.location`, but it is safe to use on the server where there is no global `location` object, and it's reactive so it can be tracked.\n\n### Path Route Parameters\n\n`useLocation()` encodes the [Route Parameters](/docs/routing.md) as params.\n\nAssume you have:\n\n- File: `src/routes/sku/[skuId]/index.tsx`\n- User navigates to: `https://example.com/sku/1234`\n- Then the `skuId` can be retrieved through `useLocation().params.skuId`\n\n```tsx /useLocation/ title=\"src/routes/sku/[skuId]/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { useLocation } from '@qwik.dev/router';\n\nexport default component$(() => {\n const loc = useLocation();\n\n return (\n <>\n <h1>SKU</h1>\n {loc.isNavigating && <p>Loading...</p>}\n <p>pathname: {loc.url.pathname}</p>\n <p>skuId: {loc.params.skuId}</p>\n </>\n );\n});\n```\n\nThe above code would generate:\n\n```html\n<h1>SKU</h1>\n<p>pathname: /sku/1234/</p>\n<p>skuId: 1234</p>\n```\n\n### `useLocation` in `root.tsx` is not supported\n\nTo access the current url from `root.tsx` use this pattern:\n```ts\nconst serverDataUrl = useServerData<string>('url');\nconst url = new URL(serverDataUrl || 'https://unknown');\n```\n\n`useLocation` is a read-only API, you should never attempt to mutate the values of the `loc` object returned. Instead look into the `useNavigate()` API.\n\n## `useNavigate()`\n\nThe `useNavigate()` hook returns a function that programmatically navigates to the next page without requiring a user click or causing a full-page reload. This function can be called with a string argument to \"push\" a new path, or without arguments to cause an SPA refresh of the page. This is the API used by the `<Link>` component internally to support SPA navigation.\n\n```tsx {12,21} /useNavigate/\nimport { component$ } from '@qwik.dev/core';\nimport { useNavigate } from '@qwik.dev/router';\n\nexport default component$(() => {\n const nav = useNavigate();\n\n return (\n <>\n <button\n onClick$={async () => {\n // SPA navigate to /dashboard\n await nav('/dashboard');\n }}\n >\n Go to dashboard\n </button>\n\n <button\n onClick$={async() => {\n // refresh page: call without arguments\n await nav();\n }}\n >\n Refresh page\n </button>\n </>\n );\n});\n```\n\nThis component has a button that when clicked, will navigate to `/dashboard` without causing a page reload.\n\nFor SEO and accessibility it's better to use the `` component instead of `useNavigate()` programmatically to navigate to a new page after some user interaction.\n\n### Going back\n\nTo programmatically navigate back to the previous page, use the useNavigate and useLocation hooks.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { useNavigate, useLocation } from '@qwik.dev/router';\n\nexport const BackButton = component$(() => {\n const nav = useNavigate();\n const loc = useLocation();\n\n return (\n <button onClick$={() => loc.prevUrl ? window.history.back() : nav('/')}>\n Go Back\n </button>\n );\n});\n\n```\n\nThe fallback in the nav function ensures that if the previous URL (loc.prevUrl) is not available, the user is redirected to a default path (eg. the root path /). This is useful in scenarios where the navigation history might not include a previous URL, such as when the user directly lands on a specific page without navigating from another page within the app.\n\nThe **loc.prevUrl** is only available when the user navigates to a page using the [`useNavigate()`](#usenavigate) or [``](/docs/cookbook/nav-link.md). It is not available when the user navigates to a page using [`the anchor element`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a).\n\n## `routeLoader$()`\n\nThe `routeLoader$()` function is used to declare a new Server Loader in the given page/middleware or layout. Qwik Router will execute all the declared loaders for the given route match. Qwik Components can later reference the loaders by importing them and calling the returned custom hook function in order to retrieve the data.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useGetTime = routeLoader$(async () => {\n return { time: new Date() }\n});\nexport default component$(() => {\n const signal = useGetTime(); // Signal<{time: Date}>\n console.log('Date': signal.value.time);\n return (\n <div>{signal.value.time.toISOString()}</div>\n )\n});\n```\n\nPlease refer to the [Route Loader](/docs/route-loader.md) section for more information.\n\n## `routeAction$()`\n\nThe `routeAction$()` function is used to declare a new Server Action in the given page/middleware or layout. Qwik Router will execute only the invoked action after some user interaction (such as a button click or a form submission).\n\nPlease refer to the [Server Actions](/docs/action.md) section for more information.\n\n## `getRouterConfig()`\n\nQwik Router generates the route config of your application at build time. Read it through these functions. On the server, a Qwik library kept external reads the config of the app serving the current request:\n\n- `getRouterConfig()` resolves the whole config, with the route trie and the server plugins.\n- `getRoutes()` resolves the route trie.\n- `getBasePathname()` returns the base pathname the app is served under, such as `/`.\n- `getTrailingSlash()` returns whether the app's URLs end with a slash.\n\n```tsx\nimport { getRoutes } from '@qwik.dev/router';\n\nconst routes = await getRoutes();\n```\n\nA production server build leaves out the pages it prerendered without server code, so its route trie only holds the routes the server still serves.\n\nThe `@qwik-router-config` virtual module still exports the same values for existing code, but it only resolves inside the app build.\n\n## `useQwikRouter()`\n\nThe `useQwikRouter()` function is used to initialize Qwik Router in the existing document, providing the necessary context for Qwik Router to work, such as [`useContent()`](/docs/api.md#usecontent), `useLocation()` and `<RouterOutlet />`.\n\nThis hook should be located at the very root of your application. In most of the starters, you will find it in the `src/root.tsx` file.\n\n```tsx title=\"src/root.tsx\"\nimport { useQwikRouter } from '@qwik.dev/router';\n\nexport default component$(() => {\n useQwikRouter();\n\n return (\n <>\n <head>\n {/* ... */}\n </head>\n <body>\n <RouterOutlet />\n </body>\n </>\n );\n});\n```\n\n`useQwikRouter()` should only be called once, in the root of your application. If your root component is reactive, you should move the reactive part into a child component, or you can use the `` component instead.\n\n## `<QwikRouterProvider>`\n\nThe `QwikRouterProvider` component is a wrapper around the `useQwikRouter()` hook. It does not render any DOM element, not even the matched route. We recommend using the hook instead of this component, except when your root component is reactive.\n\n```tsx title=\"src/root.tsx\"\nimport { QwikRouterProvider, RouterOutlet } from '@qwik.dev/router';\n\nexport default component$(() => (\n <QwikRouterProvider>\n <head>\n {/* ... */}\n </head>\n <body>\n <RouterOutlet />\n </body>\n </QwikRouterProvider>\n));\n```\n\n## `<QwikRouterMockProvider>`\n\nThe `QwikRouterMockProvider` component initializes a Qwik Router context for testing. It provides the necessary context for Qwik Router code to work in tests, such as [`useContent()`](/docs/api.md#usecontent). Vice versa for `useNavigate()`, `<Link>`, `useLocation()` and so on.\nIt is recommended that you use this in your test files.\n\n`QwikRouterMockProvider` does not render any DOM elements, meaning it won't be visible in snapshots\n\nIf you are looking for a general example on how to integrate vitest into your Qwik look checkout the [vitest integration documentation](/docs/integrations/vitest.md)\n\n```tsx title=\"src/components/card.spec.tsx\"\nimport { createDOM } from '@qwik.dev/core/testing';\nimport { QwikRouterMockProvider } from '@qwik.dev/router';\nimport { test, expect } from 'vitest';\n\n// Component with two props. Uses <Link> internally. Omitted for brevity\nimport { Card } from './card';\n\nconst cases = [\n {text: 'qwik', link:'https://qwik.dev/docs/api'},\n {text: 'vitest', link: 'https://vitest.dev'}\n];\n\ntest.each(cases)('should render card with %s %s', async ({text, link}) => {\n const { screen, render } = await createDOM();\n await render(\n <QwikRouterMockProvider>\n <Card text={text} link={link} />\n </QwikRouterMockProvider>,\n );\n expect(screen.innerHTML).toMatchSnapshot();\n});\n```\n\nA `goto` prop can be passed to customize the `navigate` behavior during tests\n\n```tsx title=\"src/components/button.spec.tsx\"\nimport { $ } from '@qwik.dev/core';\nimport { createDOM } from '@qwik.dev/core/testing';\nimport { test, expect, vi } from 'vitest';\n\n// Component with one prop. Uses useNavigate internally. Omitted for brevity\nimport { Button } from '../button';\n\nconst goto = vi.fn(async (path, options) => {\n console.log(`Navigating to ${path} with ${options}`);\n});\n\ntest('should render the button and navigate', async () => {\n const { screen, render, userEvent } = await createDOM();\n const goto$ = $(goto);\n await render(\n <QwikRouterMockProvider goto={goto$}>\n <Button id=\"button\" />\n </QwikRouterMockProvider>,\n );\n expect(screen.innerHTML).toMatchSnapshot();\n await userEvent('#button', 'click');\n expect(goto).toHaveBeenCalled();\n});\n```\n\nIf you are using `routeLoader$`s in a Qwik Component that you want to test, you can provide a `loaders` prop to mock the data returned by the loaders\n\n```ts title=\"src/loaders/product.loader.ts\"\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProductData = routeLoader$(async () => {\n const res = await fetch('https://.../product');\n const product = (await res.json()) as Product;\n return product;\n});\n```\n\n```tsx title=\"src/components/product.tsx\"\nimport { component$ } from '@builder.io/qwik';\n\nimport { useProductData } from '../loaders/product.loader';\n\nexport const Footer = component$(() => {\n const signal = useProductData();\n return <footer>Product name: {signal.value.product.name}</footer>;\n});\n```\n\n```tsx title=\"src/components/product.spec.tsx\"\nimport { createDOM } from '@builder.io/qwik/testing';\nimport { test, expect } from 'vitest';\n\nimport { Footer } from './product';\nimport { useProductData } from '../loaders/product.loader';\n\ntest('should render footer with product name', async () => {\n const { screen, render } = await createDOM();\n const loadersMock = [\n {\n loader: useProductData,\n data: { product: { name: 'Test Product' } },\n },\n ];\n await render(\n <QwikCityMockProvider loaders={loadersMock}>\n <Footer />\n </QwikCityMockProvider>,\n );\n expect(screen.innerHTML).toMatchSnapshot();\n});\n```\n\nThe same approach can be used to mock `routeAction$`s by providing an `actions` prop to the `QwikCityMockProvider`\n\n```tsx title=\"src/components/user-form.spec.tsx\"\nimport { $ } from '@builder.io/qwik';\nimport { createDOM } from '@builder.io/qwik/testing';\nimport { test, expect } from 'vitest';\n\nimport { UserForm } from './user-form';\nimport { useAddUser } from '../loaders/add-user.action';\n\ntest('should call addUser action with correct data', async () => {\n const { screen, render } = await createDOM();\n const actionsMock = [\n {\n action: useAddUser,\n handler: $(async (data) => {\n console.log('useAddUser action called with data:', data);\n }),\n },\n ];\n await render(\n <QwikCityMockProvider actions={actionsMock}>\n <UserForm />\n </QwikCityMockProvider>,\n );\n expect(screen.innerHTML).toMatchSnapshot();\n});\n```\n\n## `<RouterOutlet>`\n\nThe `RouterOutlet` component is responsible for rendering the matched route at a given moment, it internally uses the [`useContent()`](/docs/api.md#usecontent) to render the current page, as well as all of the nested layouts.\n\nThis component is usually located as a child of `<body>`, in most of the starters you will find it in the `src/root.tsx` file (refer to the example in `QwikRouterProvider`).\n\n## `<Form>`\n\nThe `Form` component is a wrapper around the native `<form>` element, and it's designed to work side by side with [Server Actions](/docs/action.md#using-actions-with-form).\n\nSince this component uses the native `<form>` element, it will work with any browser with and without JavaScript enabled. In addition, it enhances the native `<form>` element by capturing the `submit` event and preventing the default behavior, so it will behave like an SPA (Single Page Application) instead of a full page reload.\n\n```tsx title=\"src/routes/login/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { Form, routeAction$ } from '@qwik.dev/router';\n\n// this action will be called when the form is submitted\nexport const useLoginAction = routeAction$((data, { cookies, redirect }) => {\n if (validate(data.username, data.password)) {\n cookies.set('auth', getAuthToken(data.username));\n throw redirect(302, '/dashboard');\n }\n});\n\nexport default component$(() => {\n const login = useLoginAction();\n\n return (\n <Form action={login}>\n <input type=\"text\" name=\"username\" />\n <input type=\"password\" name=\"password\" />\n <button type=\"submit\">Login</button>\n </Form>\n );\n});\n```\n\n## `<Link>`\n\nThe `Link` component works like the `<a>` anchor element, but instead of causing a full page to reload, it will navigate as a SPA (Single Page Navigation). This is useful if you need to navigate without losing your current state.\n\nFull-page reloads in Qwik are extremely cheap. Other frameworks abuse SPA links because a full-page reload requires JS to hydrate and re-execute everything. This is not the case for Qwik. Through investigation of internal testing, using `` usually leads to the most snappy interactions.\n\nUnder the hood, the `<Link>` component uses the [`useNavigate()`](/docs/api.md#usenavigate) API and prevents the default behavior of the native `<a>`:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { useNavigate } from '@qwik.dev/router';\n\nexport const Link = component$<LinkProps>((props) => {\n const nav = useNavigate();\n\n return (\n <a\n preventdefault:click\n onClick$={() => {\n nav(props.href);\n }}\n {...props}\n >\n <Slot />\n </a>\n );\n});\n```\n\n### Usage\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Link } from '@qwik.dev/router';\n\nexport default component$(() => {\n return (\n <div>\n <a href=\"/docs\" class=\"my-link\">\n full-page reload\n </a>\n <Link href=\"/docs\" class=\"my-link\">\n spa navigation\n </Link>\n </div>\n );\n});\n```\n\n### Prefetch\n\n`Link` can prefetch route bundles, route data, or both before the user navigates.\n\nThis **improves UX performance** for client-side (**SPA**) navigations, especially for pages that\nwait on `routeLoader$`, `onGet`, databases, or API calls.\n\nUse `prefetchBundles` to control when Qwik prefetches the javascript bundles required for the target\nroute. Use `prefetchData` to control when Qwik prefetches and caches route data for the target route.\n\nBy default, `prefetchBundles` uses `visible`, while `prefetchData` uses `intent`. This means route\nbundles are prefetched when the link enters the viewport, and route data is prefetched when the\nuser shows navigation intent with `pointerenter`, hover, or focus.\n\nAvailable strategy values are:\n\n- `visible` to prefetch when the link becomes visible in the viewport\n- `intent` to prefetch when the user shows intent with `pointerenter`, hover, or focus\n- `commit` to prefetch when the user commits with `pointerdown` or the `Enter` key\n- `off` to disable prefetching\n\nPrefetching will not occur if the user has the **data saver** setting enabled.\n\nThe older `prefetch` prop is deprecated. For compatibility, `prefetch=\"js\"` prefetches route\nbundles when the link becomes visible and turns route data prefetching off by default,\n`prefetch={true}` prefetches route bundles and route data when the link becomes visible, and\n`prefetch={false}` disables prefetching.\n\n**Warning**\nRoute data prefetching fetches one `q-loader-*.json` file per `routeLoader$` on the target route. If you use `visible` route data prefetching for many visible links, the browser may start many of these requests at once.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Link } from '@qwik.dev/router';\n\nexport default component$(() => {\n return (\n <div>\n <Link href=\"/a\" prefetchBundles=\"visible\">\n route bundles will be prefetched when visible\n </Link>\n <Link href=\"/b\" prefetchData=\"intent\">\n route data will be prefetched on intent\n </Link>\n <Link href=\"/c\" prefetchBundles=\"visible\" prefetchData=\"commit\">\n bundle and data prefetching use different strategies\n </Link>\n <Link href=\"/d\" prefetch={false}>\n prefetching is disabled\n </Link>\n </div>\n );\n});\n```\n"},{"id":"/docs/caching/","title":"Caching | Qwik Router","description":"Learn how to handle caching in your Qwik Router app to keep your site as fast as possible.","url":"https://next.qwik.dev/docs/caching/","content":"# Caching Responses\n\nCaching responses is critical for keeping your site as fast as possible, both for [pages](/docs/pages.md) as well as [middleware](/docs/middleware.md).\n\nA option is to use [stale-while-revalidate](https://web.dev/stale-while-revalidate/) caching for all responses. Note that this means that users will see a cached response even if the server is updated, and only when the user refreshes will they see the updated content.\n\nFor instance, we can add an `onGet` export to our root [layout](/docs/layout.md) (`src/routes/layout.tsx`) like so, to apply good caching defaults site-wide:\n\n```tsx title=\"src/routes/layout.tsx\"\nimport { component$, Slot } from \"@qwik.dev/core\";\nimport type { RequestHandler } from \"@qwik.dev/router\";\n\nexport const onGet: RequestHandler = async ({ cacheControl }) => {\n cacheControl({\n // Always serve a cached response by default, up to a week stale\n staleWhileRevalidate: 60 * 60 * 24 * 7,\n // Max once every 5 seconds, revalidate on the server to get a fresh version of this page\n maxAge: 5,\n });\n};\n\nexport default component$(() => {\n return (\n <main class=\"mx-auto max-w-[2200px] relative\">\n <Slot />\n </main>\n );\n});\n```\n\nWith the above setup, you will not only have better performance (pages are always served instantly from cache), but you can also have significantly decreased hosting costs, as our server or edge functions only need to run at most once every 5 seconds per page.\n\n## `cacheControl`\n\nAny method that takes a [request event](https://qwik.dev/docs/advanced/request-handling/#request-event) can call `request.cacheControl` to set the cache control headers for the response:\n\n```tsx title=\"src/routes/layout.tsx\"\nimport type { RequestHandler } from \"@qwik.dev/router\";\n\nexport const onGet: RequestHandler = async ({ cacheControl }) => {\n cacheControl({\n public: true,\n maxAge: 5,\n sMaxAge: 10,\n staleWhileRevalidate: 60 * 60 * 24 * 365,\n });\n};\n```\n\nIf you have default caching set at the root, but want to disable caching for a specific page, you can override this setting using nested layouts. The below example overrides caching for dashboard pages.\n\n```tsx title=\"src/routes/dashboard/layout.tsx\"\nimport type { RequestHandler } from \"@qwik.dev/router\";\n\n// Override caching for /dashboard pages to not cache as they are unique per visitor\nexport const onGet: RequestHandler = async ({ cacheControl }) => {\n cacheControl({\n public: false,\n maxAge: 0,\n sMaxAge: 0,\n staleWhileRevalidate: 0,\n });\n};\n\n```\n\nYou can see the full [API reference](https://qwik.dev/api/qwik-router-middleware-request-handler/) of options you can pass to `request.cacheControl`.\n\n## When not to cache\n\nCaching is generally beneficial, but not right for every page all the time. If your site has URLs that will show different content to different people — for example, pages exclusive to logged-in users or pages that show content based on a user's location — you should avoid using cache-control headers to cache these pages. Instead, render the content of these pages on the server side on a per-visitor basis.\n\nFor high traffic pages that look the same to everyone, such as a homepage, caching is great for enhancing performance and reducing cost. For pages specifically for logged in users that may have less traffic, it may advisable to disable caching.\n\nYou can conditionally change cache behaviors with any logic you like:\n\n```tsx title=\"src/routes/layout.tsx\"\nimport type { RequestHandler } from \"@qwik.dev/router\";\n\nexport const onGet: RequestHandler = async ({ cacheControl, url }) => {\n // Only our homepage is public and should be CDN cached. Other pages are unique per visitor\n if (url.pathname === '/') {\n cacheControl({\n public: true,\n maxAge: 5,\n staleWhileRevalidate: 60 * 60 * 24 * 365,\n });\n }\n};\n```\n\n## CDN Cache Controls\n\nFor even more control on your caching strategy, your CDN might have another layer of cache control headers.\n\nThe `cacheControl` convenience method can receive a second argument (set to `\"Cache-Control\"` by default). You can pass in any string value specific to your CDN such as \"CDN-Cache-Control\", \"Cloudflare-CDN-Cache-Control\", \"Vercel-CDN-Cache-Control\", etc.\n\n```tsx\ncacheControl({\n maxAge: 5,\n staleWhileRevalidate: 60 * 60 * 24 * 365,\n}, \"CDN-Cache-Control\");\n```\n\n### Missing Controls\n\nSome CDNs (such as Vercel Edge) may strip some of your \"Cache-Control\" headers.\n\n[On Vercel's documentation:](https://vercel.com/docs/edge-network/caching#cdn-cache-control)\nIf you set Cache-Control without a CDN-Cache-Control, the Vercel Edge Network strips s-maxage and stale-while-revalidate from the response before sending it to the browser. To determine if the response was served from the cache, check the [x-vercel-cache](https://vercel.com/docs/edge-network/caching#x-vercel-cache) header in the response.\n\nIf your CDN, such as Vercel Edge, automatically removes certain cache control headers and you wish to implement caching strategies like \"stale-while-revalidate\" or \"s-maxage\" in the browser, you can specify an additional cacheControl:\n\n```tsx title=\"src/routes/layout.tsx\"\nimport type { RequestHandler } from \"@qwik.dev/router\";\n\nexport const onGet: RequestHandler = async ({ cacheControl }) => {\n // If you want the browser to use \"stale-while-revalidate\" or \"s-maxage\" Cache Control headers, you have to add the second cacheControl with \"CDN-Cache-Control\" or \"Vercel-CDN-Cache-Control\" on Vercel Edge\n cacheControl({\n staleWhileRevalidate: 60 * 60 * 24 * 365,\n maxAge: 5,\n });\n cacheControl({\n maxAge: 5,\n staleWhileRevalidate: 60 * 60 * 24 * 365,\n }, \"CDN-Cache-Control\");\n};\n```\n\n### Caching bundles and assets\n\nSee [Cache Headers](/docs/deployments.md#cache-headers) for more information.\n\n## SSR Caching\n\nQwik Router includes a built-in in-memory SSR cache that can serve pre-rendered HTML without re-executing components. This is controlled through the `eTag` and `cacheKey` exports (or via `routeConfig`).\n\n### `eTag`\n\nThe `eTag` export defines an [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) for the page. When a browser sends an `If-None-Match` header matching the ETag, the server responds with `304 Not Modified` (empty body) instead of sending the HTML.\n\nIt can be:\n\n- **A static string** -- e.g. a deployment version or content version.\n- **A function** receiving `DocumentHeadProps` -- compute the ETag from route data (loaders, params, etc.). Return `null` to skip the ETag for this request.\n\nQwik normalizes eTag values by stripping weak-form `W/` prefixes, quotes, and forbidden chars. Values that normalize to an empty string are treated as absent.\n\nQwik sends all eTags as \"strong\", for a simpler API. This only makes a difference with ranged HTTP requests, which are not relevant for SSR or route loader data.\n\nAn eTag *must* always change when the content changes, and ideally should not change when the content is the same.\n\n```tsx title=\"src/routes/product/[id]/index.tsx\"\nimport type { RouteConfig } from '@qwik.dev/router';\n\n// Static eTag (e.g., for content that changes only on deployment)\nexport const routeConfig: RouteConfig = {\n eTag: 'v1.2.3',\n};\n\n// Dynamic eTag based on data\nexport const routeConfig: RouteConfig = ({ resolveValue }) => {\n const product = resolveValue(useProduct);\n return {\n eTag: `product-${product.id}-${product.updatedAt}`,\n };\n};\n```\n\n> **Note**: Markdown (`.md`) files automatically get an eTag based on a content hash. MDX files (`.mdx`) do not, since they can contain dynamic JavaScript.\n\n### `cacheKey`\n\nThe `cacheKey` export enables in-memory SSR caching. When set, rendered HTML is cached and served on subsequent requests with the same cache key, completely bypassing SSR.\n\n- `true`: uses the default cache key — `${status}|${eTag}|${pathname}` when an `eTag` is set, otherwise `${status}|${pathname}`.\n- Function `(requestEv, eTag) => string | null`: return a custom key, or `null` to skip caching this request. The second argument is the normalized eTag (or an empty string when none was provided or it normalized to an empty string).\n\n```tsx title=\"src/routes/product/[id]/index.tsx\"\nimport type { RouteConfig } from '@qwik.dev/router';\n\nexport const routeConfig: RouteConfig = {\n eTag: 'v1',\n cacheKey: true, // cache using default key format\n};\n\n// Custom key — vary on a `lang` cookie\nexport const routeConfig: RouteConfig = {\n cacheKey: (ev, eTag) => {\n const lang = ev.cookie.get('lang')?.value ?? 'en';\n return `${ev.url.pathname}|${lang}|${eTag ?? '*'}`;\n },\n};\n```\n\n> **Security warning**: The in-memory cache is shared by every visitor of the server process, and the default key (`cacheKey: true`) contains nothing that identifies the visitor — no cookie, session, or `Authorization` header. Never use `cacheKey: true` on a route or layout that renders per-visitor content: the first visitor's HTML would be served to everyone else requesting the same URL. On a cache hit nothing is re-rendered, so checks inside components do not run either.\n>\n> For personalized routes, either skip caching for identified visitors or fold the identifying value into the key:\n\n```tsx title=\"src/routes/account/index.tsx\"\nimport type { RouteConfig } from '@qwik.dev/router';\n\nexport const routeConfig: RouteConfig = {\n // Only cache for anonymous visitors; `null` skips the cache\n cacheKey: (ev) => (ev.cookie.has('session') ? null : ev.url.pathname),\n};\n```\n\n`cacheKey` can be set without an `eTag`. In that case the first SSR streams as usual (no ETag header on the first response), and the cache write hashes the rendered HTML so subsequent hits serve the entry with a stable ETag and can answer conditional requests with `304`.\n\nThe cache uses LRU eviction with a default capacity of 50 entries. You can configure this in your server entry:\n\n```tsx title=\"src/entry.server.tsx\"\n// Set before any request handling\nglobalThis.__SSR_CACHE_SIZE__ = 100; // or 0 to disable\n```\n\n### Clearing the cache\n\nUse `clearSsrCache()` to invalidate cached pages after deployments or data changes:\n\n```tsx\nimport { clearSsrCache } from '@qwik.dev/router/middleware/request-handler';\n\n// Clear a specific entry\nclearSsrCache('200|v1|/products/123');\n\n// Clear the entire cache\nclearSsrCache();\n```\n\n### Layout-level caching\n\nLayouts can define `eTag` and `cacheKey` via `routeConfig` to apply caching to an entire subtree. Pages can override these values in their own `routeConfig`:\n\n```tsx title=\"src/routes/blog/layout.tsx\"\nimport type { RouteConfig } from '@qwik.dev/router';\n\n// All blog pages use SSR caching by default\nexport const routeConfig: RouteConfig = {\n cacheKey: true,\n};\n```\n\nA layout-level `cacheKey` applies to every page below it, so make sure none of them render per-visitor content (see the [security warning](#cachekey) above).\n\nSee the [routeConfig documentation](/docs/pages.md#routeconfig-export) for the full resolution rules.\n\n## Loader caching\n\n`routeLoader$` accepts an `eTag` (string or function) and a `cacheKey` option that mirror the SSR-side ones, but applied to the loader's JSON response.\n\nQwik normalizes explicit loader eTag values by stripping weak-form `W/` prefixes, quotes, and forbidden chars, then sends a strong `ETag` header. Values that normalize to an empty string are treated as absent.\n\n```tsx\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useProduct = routeLoader$(\n async ({ params }) => {\n return await db.product.find(params.id);\n },\n {\n // Auto-hashed eTag derived from the serialized response on cache miss; stored alongside the\n // body so future hits serve the same validator and answer `If-None-Match` with `304`.\n cacheKey: true,\n }\n);\n```\n\n- `eTag` (string | function): explicit validator. Set before the loader runs, so a matching `If-None-Match` short-circuits with `304` and the loader is skipped entirely.\n- `cacheKey` (`true` | function): enables an in-memory cache for the serialized JSON response. Default key: `${pathname}|${filteredSearch}|${loaderId}`, suffixed with `|${eTag}` when an explicit eTag is set.\n\n> **Security warning**: On a cache hit the loader function is **not executed**, so any authentication or authorization check written inside the loader is skipped and the cached JSON is returned to whoever asks. The default key does not identify the visitor. Do not use `cacheKey: true` on loaders that return per-visitor data — return `null` from a custom `cacheKey` function for identified visitors, or include the identifying value in the key — and enforce access control in `onRequest` middleware, which always runs before the cache lookup.\n\nLoader `cacheKey` callbacks receive the loader-filtered request event. They can read the filtered search string from `ev.url.search`.\n\nOn a cache miss the loader runs, the serialized response is stored alongside its eTag (the explicit one if provided, or an auto-hash of the serialized body), then sent. On a cache hit the stored `{ eTag, data }` pair is served directly — `If-None-Match` is checked against the stored eTag and a `304` is returned when it matches. Redirects and errors are never cached.\n\nClear the loader cache the same way as the SSR cache:\n\n```tsx\nimport { clearLoaderCache } from '@qwik.dev/router/middleware/request-handler';\n\nclearLoaderCache(); // clear all\nclearLoaderCache('/products/123||hash'); // clear one entry\n```\n"},{"id":"/docs/endpoints/","title":"Endpoints | Qwik Router","description":"Endpoints are middleware functions used to control and return data in various formats like RESTful API, GraphQL API, JSON, XML, reverse proxy, or other API types.","url":"https://next.qwik.dev/docs/endpoints/","content":"# Endpoints\n\nA [middleware function](/docs/middleware.md) that returns a response is called an endpoint. Endpoints are useful for returning data such as RESTful API, GraphQL API, JSON, XML, reverse proxy or any other type of API where you need to control all aspects of the HTTP response. Returning a response (using `json` for example) will stop the execution of subsequent middleware functions past this point in the middleware chain.\n\nAll endpoints receive a [`RequestEvent`](/docs/middleware.md#requestevent) API for controlling the response of the endpoint.\n\nFor example, when navigating to `/greet/` URL this endpoint will return `{\"hello\":\"world\"}`.\n\nFile: `src/routes/greet/index.tsx`\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ json }) => {\n json(200, { hello: 'world' });\n};\n```\n\nSending a response is what differentiates an endpoint from a middleware. Sending a response (using `json()` for example) will therefore implicitly halt the middleware chain.\n\n## Create a reverse proxy using a fetch\n\nA reverse proxy can be created by using the `fetch()` method to request another server. Then use the `send()` method to send the response back to the client.\n\n```tsx\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ send, url }) => {\n const response = await fetch(\n new URL('/demo/qwikrouter/middleware/json/', url)\n );\n send(response.status, await response.text());\n};\n```\n\n## Create a stream response manually\n\nEndpoints can manually write to the HTTP response stream, using the `getWritableStream()` method. This can be useful for creating a streaming endpoint, such as a server-sent events endpoint.\n\n```tsx\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async (requestEvent) => {\n const writableStream = requestEvent.getWritableStream();\n const writer = writableStream.getWriter();\n const encoder = new TextEncoder();\n\n writer.write(encoder.encode('Hello World\\n'));\n await wait(100);\n writer.write(encoder.encode('After 100ms\\n'));\n await wait(100);\n writer.write(encoder.encode('After 200ms\\n'));\n await wait(100);\n writer.write(encoder.encode('END'));\n writer.close();\n};\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n```\n\n## Endpoint vs `server$`\n\nEndpoints are low level APIs that give developers full control over the HTTP response. They are only recommended when you need to create an API to be consumed by an external entity such as a mobile app or a third-party service.\n\nThe [`server$`](/docs/server$.md) functions are usually a better option when you need to run some code on the server and return a response back to the app. The `server$` is strongly typed and provides a more convenient API for returning data.\n"},{"id":"/docs/error-handling/","title":"Error handling | Qwik Router","description":"","url":"https://next.qwik.dev/docs/error-handling/","content":"# Error handling\n\nWhen an error is thrown in a loader or `server$` function, a 500 error is returned to the client along with the error. This is useful during development but isn't always desirable for production systems. Qwik provides the tools necessary to customise how errors are handled.\n\nThrowing a `ServerError` instance allows you to return custom errors to the browser with a different status code and serialised data.\n\nLoaders also provide a helper function on the event object to easily create new ServerErrors.\n\n```tsx\n// Throw ServerErrors from a routerLoader$\nconst useProduct = routeLoader$(async (ev) => {\n const product = await fetch('api/product/1')\n\n if (!product) {\n // Throw a 404 with a custom payload\n throw new ServerError(404, 'Product not found')\n\n // Or use the existing helper function\n throw ev.error(404, 'Product not found')\n }\n\n return product\n})\n\n// Throw ServerErrors from a server$\nconst getPrices = server$(() => {\n if (!isAuthenticated()) {\n throw new ServerError(401, { code: 401 })\n }\n\n return fetch('api/product/1/prices')\n})\n\nexport default component$(() => {\n const product = useProduct()\n\n useVisibleTask(() => {\n getPrices()\n .then()\n .catch(err => {\n // The payload from a ServerError is deserialised as the error caught in the client\n if (err.code === 401) {\n // Navigate to login page\n }\n\n // Show generic error\n })\n })\n\n return <div>Product page</div>\n})\n```\n\n## Error interceptor\n\nIntercepting errors with middleware has a few usecases: you might want to hide error details in production systems, add structured error logging, or map the error status codes from RPC API calls to HTTP status codes. This is all achieveable with middleware in a `plugin` file.\n\n```tsx\n// src/routes/plugin@errors.ts\nimport { type RequestHandler } from '@qwik.dev/router'\nimport { RedirectMessage, ServerError } from '@qwik.dev/router/middleware/request-handler'\nimport { isDev } from '@qwik.dev/core/build'\n\nexport const onRequest: RequestHandler = async ({ next }) => {\n try {\n return await next();\n } catch (err) {\n // Pass through 3xx redirects\n if (err instanceof RedirectMessage) {\n throw err\n }\n\n // Pass through ServerErrors\n if (err instanceof ServerError) {\n throw err\n }\n\n // Log unknown errors\n console.error('unknown error', err)\n\n if (isDev) {\n throw err\n } else {\n throw new ServerError(500, 'Internal server error');\n }\n }\n};\n\n```\n"},{"id":"/docs/guides/best-practices/","title":"Best Practices | Guides","description":"Learn the best practices for Qwik, a guide for understanding how to use Qwik to its full potential.","url":"https://next.qwik.dev/docs/guides/best-practices/","content":"# Best Practices\n\n## Inline operations in templates\n\nQwik optimizer can better optimize the reactivity of the application if the operations are inlined in the template.\n\n```tsx title=\"Suboptimal implementation\"\n// Don't do this!\nexport default component$(() => {\n const signal = useSignal(0);\n const isBiggerThanZero = signal.value > 0 ? 'Bigger than zero' : 'Smaller than zero';\n return (\n <div>\n <button onClick$={() => signal.value++}>+</button>\n <button onClick$={() => signal.value--}>-</button>\n <div>{isBiggerThanZero} - Current value: { signal.value }</div>\n </div>\n );\n});\n```\n\nThe above implementation will cause the whole template to be re-rendered when the signal changes. This is because the `isBiggerThanZero` is not inlined in the template.\n\n```tsx title=\"Optimal Implementation\"\nexport default component$(() => {\n const signal = useSignal(0);\n return (\n <div>\n <button onClick$={() => signal.value++}>+</button>\n <button onClick$={() => signal.value--}>-</button>\n <div>\n {signal.value > 0 ? 'Bigger than zero' : 'Smaller than zero'} - Current\n value: {signal.value}\n </div>\n </div>\n );\n});\n```\n\n## Moving signal reads to `useTask$` or `useComputed$`\n\nThis is similar to the tip above.\n\nEvery time Qwik \"reads\" a signal/store value\nthe function that the \"read\" is happening at, will re-run again\non every change to that signal.\n\nThat’s why it’s better to \"read\" values (and track them)\ninside of `useTask$` or `useComputed$` functions instead of inside component functions,\nwhenever possible.\n\nBecause otherwise, your component function will re-run\non each change.\n\n```tsx title=\"Suboptimal implementation\"\n// Don't do this!\nexport default component$(() => {\n const count = useSignal(1);\n const doubleCount = count.value*2;\n return (\n <div>{doubleCount}</div>\n );\n});\n```\n\nThe above implementation will cause the whole template to be re-rendered when the signal changes.\n\nBelow, only the `useComputed$` function will re-run on any `count.value` change:\n\n```tsx title=\"Optimal Implementation\"\nexport default component$(() => {\n const count = useSignal(1);\n const dobuleCount = useComputed$(() => count.value*2);\n return (\n <div>{doubleCount.value}</div>\n );\n});\n```\n\nFor async derived values (like search suggestions), use `useComputed$` with an async function and abort in-flight work on each keystroke:\n\n```tsx title=\"Async derived value with cancellation\"\nexport default component$(() => {\n const query = useSignal('');\n const results = useComputed$(async ({ abortSignal }) => {\n const q = query.value;\n const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, {\n signal: abortSignal,\n });\n return res.json();\n }, { initial: [] });\n\n return <div>{results.value.length} results</div>;\n});\n```\n\n## Use `useVisibleTask$()` as a last resort\n\nAlthough convenient, `useVisibleTask$()` runs code eagerly and blocks the main thread, preventing user interaction until the task is finished. You can think of it as an escape hatch.\n\nWhen in doubt, instead of \"useVisibleTask$()\" use:\n- `useTask$()` -> perform code execution in SSR mode.\n- `useOn()` -> listen to events on the root element of `the current component`.\n- `useOnWindow()` -> listen to events on the `window` object.\n- `useOnDocument()` -> listen to events on the `document` object.\n\nSometimes though, it is the only way to achieve the result.\n\nIn that case, you can add `// eslint-disable-next-line qwik/no-use-visible-task` to the line before \"useVisibleTask$\" to remove the warning.\n\n### Register DOM events with `useOn()`, `useOnWindow()`, or `useOnDocument()`\n\nQwik allows to register event listeners in a declarative way, using the `useOn()` or using JSX.\n\nWhen using `useVisibleTask$()` to programmatically register events, we are downloading and executing JavaScript eagerly, even if the event is not triggered.\n\n```tsx title=\"Suboptimal implementation\"\n// Don't do this!\nuseVisibleTask$(({ cleanup }) => {\n const listener = (event) => {\n const mouseEvent = event as MouseEvent;\n console.log(mouseEvent.x, mouseEvent.y);\n };\n document.addEventListener('mousemove', listener);\n\n cleanup(() => {\n document.removeEventListener('mousemove', listener);\n });\n});\n```\n\nThe above implementation causes more JavaScript to load eagerly, rather than responding precisely to user events. Increased upfront JavaScript loading results in slower app performance. See [below](#delaying-core-execution) for more details.\n\nInstead, use the `useOnDocument()` hook to register events on the `document` object, this way Qwik will not execute any JS until the event is triggered.\n\n```tsx title=\"Optimal Implementation\"\nuseOnDocument(\n 'mousemove',\n $((event) => {\n const mouseEvent = event as MouseEvent;\n console.log(mouseEvent.x, mouseEvent.y);\n // No manual clean up required!\n })\n);\n```\n\n## Avoid accessing the location from the `window` object\n\nDon't access `window.location` directly, use `useLocation()` hook instead.\n\n```tsx title=\"Suboptimal implementation\"\n// Don't do this!\nuseVisibleTask$(()=> {\n if (window.location.href).includes('foo') {\n //... do the thing\n }\n})\n// or\nuseTask$(() => {\n if (isBrowser) {\n if (window.location.href).includes('foo') {\n //... do the thing\n }\n }\n})\n```\n\nMany actions related to location information can be executed during the initial server-side render, resulting in pure HTML without any JavaScript overhead.\n\nForcing this logic to run on the client side introduces increased upfront JavaScript and leads to eager loading.\n\n```tsx title=\"Optimal Implementation\"\n// Do this!\nconst location = useLocation();\n\nif (location.url.href.includes('foo')) {\n // Do the thing\n}\n```\n\n### Exception\n\nWhen using SSG for purely static files, it's inevitable to rely on the server without current location information during the build time.\n\nHowever, exercise caution! If the required information (such as query parameters) isn't needed until a user event occurs, incorporate the check within your event handling code.\n\nThis approach helps to prevent eager loading of JavaScript and improves performance.\n\nSee: [useLocation() Docs](/docs/api.md#uselocation)\n\n## Delaying Core Execution\nAt load time we want to execute as little as possible to free main thread for other priority. With Qwik you can even delay the framework execution (called \"core\"), but there are some rules to follow.\n\nSome things to keep in mind before checking the rules :\n- Delaying core execution usually comes at the price of devX, this is an advance performance trick.\n- Like other chunks, core will be preloaded so the app doesn't have to load it at execution time.\n\n### useVisibleTask$\n\n`useVisibleTask$` will **always** execute core before its callback is called.\n\n```jsx\n// Requires core when component is visible in the viewport\nuseVisibleTask$(() => {\n console.log('Hello core');\n});\n\n// Requires core on requestIdleCallback\nuseVisibleTask$(\n () => console.log('Hello core'),\n { strategy: 'document-idle' }\n);\n```\n\nIn **some** cases you can replace `useVisibleTask$` with either `useOn` or `useTask$`\n\n#### useOn\n\nReplace `useVisibleTask$` with `useOn('qvisible')` / `useOn('qidle')` if\n\n- You only need to trigger a callback once\n- The code must run on the client\n\n`useOn`, `useOnDocument` & `useOnWindow` execute core if they use a variable from the component scope :\n\n```jsx title=\"Comparing core execution\"\nimport { libId } from 'library';\nconst globalId = 'global-id';\nconst Component = component$(() => {\n const ref = useSignal();\n const id = useId();\n\n // Executes core at load time\n useOnDocument('qidle', $(() => console.log(ref)));\n // Executes core at load time\n useOnDocument('qidle', $(() => console.log(id)));\n // Does not execute core at load time\n useOnDocument('qidle', $(() => console.log(globalId)));\n // Does not execute core at load time\n useOnDocument('qidle', $(() => console.log(libId)));\n // Does not execute core at load time\n useOnDocument('qidle', $(() => console.log('id')));\n\n return (\n <p ref={ref}></p>\n <p id={id}></p>\n <p id={globalId}></p>\n <p id={libId}></p>\n <p id=\"id\"></p>\n )\n})\n```\n\n#### useTask$\n\nReplace `useVisibleTask$` with `useTask$` if\n\n- You need to listen on state changes\n- The code can execute on the server\n\n```jsx\nconst Component = component$(() => {\n const search = useSignal();\n // Does not execute until `search` changes\n useTask$(({ track }) => {\n track(search);\n console.log(search.value);\n });\n return <input bind:value={search} type=\"search\" />;\n});\n```\n\n#### useOn + useTask$\n\nA classic usecase of `useVisibleTask$` is to start listening on browser specific event:\n\n```jsx\nconst isMobile = useSignal(false);\nuseVisibleTask$(({ cleanup }) => {\n const query = window.matchMedia('(max-width: 400px)');\n const handler = (event) => {\n isMobile.value = event.matches;\n };\n query.addEventListener('change', handler);\n cleanup(() => query.removeEventListener('change', handler));\n});\n```\n\nIn this case we actually need core when the handler is triggered. Here is how to delay core execution :\n\n```jsx\nconst isMobile = useSignal(false);\n// On idle, start listening on the event\nuseOnDocument(\n 'qidle',\n sync$(() => {\n const query = window.matchMedia('(max-width: 400px)');\n const handler = (event) => {\n // Forward the event to the document\n const copy = new event.constructor('media-query:(max-width: 400px)', event);\n document.dispatchEvent(copy);\n };\n // Store mediaQuery & handler to cleanup later\n document['cleanup:media-query:(max-width: 400px)'] = () => {\n query.removeEventListener('change', handler)\n };\n query.addEventListener('change', handler);\n })\n);\n\n// useOnDocument execute core when it actually needs it\nuseOnDocument(\n 'media-query:(max-width: 400px)',\n $((event) => {\n isMobile.value = event.matches;\n })\n);\n\n// useTask$ is used to cleanup event listeners\nuseTask$(({ cleanup }) => {\n cleanup(() => {\n if (!document['cleanup:media-query:(max-width: 400px)']) return;\n document['cleanup:media-query:(max-width: 400px)']();\n delete document['cleanup:media-query:(max-width: 400px)'];\n });\n});\n```\n\nAs we can see, this is a LOT of work, and it's not a great dev experience ! But if you're building a library or just trying to go as lean as possible, this is possible.\n"},{"id":"/docs/guides/bundle/","title":"Bundle Optimization | Guides","description":"Learn about bundle optimization in Qwik, a JavaScript framework for building web applications. This guide explains how to optimize your code by co-locating symbols and chunks, and provides examples of how to create and use symbols in your source code. Follow along with the code snippets and try them out in the included CodeSandbox demo.","url":"https://next.qwik.dev/docs/guides/bundle/","content":"# Bundle Optimization\n\nBundle Optimization refers to the process of deciding which symbol goes to which bundle so that the application can co-locate the code that is used together. Having the symbols co-located can make the application load faster.\n\n## Symbols vs Chunks\n\nSymbols are individual lazy-loadable pieces in Qwik. A symbol is created whenever you use the `__$(__)` in your source code.\n\nFor example, the code below creates two symbols from `component$` and `onClick$`.\n\n```tsx /component$/ /onClick$/\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const count = useSignal(0);\n\n return (\n <button onClick$={() => count.value++}>\n Increment {count.value}\n </button>\n );\n});\n```\n\nThe optimizer rewrites the above code to something like this:\n\nFile: `chunk-1.js`\n```tsx\nexport default componentQRL(qrl('./chunk-1.js', 's_ABC123'));\n\nexport const s_ABC123 = () => {\n const count = useSignal(0);\n\n return (\n <button onClickQRL={qrl('/.chunk-1.js', 's_XYZ342')}>\n Increment {count.value}\n </button>\n );\n};\n\nexport const s_XYZ432 = () => {\n const [count] = useLexicalScope();\n return count.value++;\n}\n```\n\nIn the above example, all of the symbols (`sABC123` and `s_XYZ432`) are co-located in the same chunk (`./chunk-1.js`).\n\nChunks are JavaScript bundles that can contain one or more symbols.\n\n## Optimal Symbol Distribution\n\nYou can think of bundle optimization as a slider that allows us to optimize the symbol delivery.\n- On one end of the slider, we have a single chunk that contains all of the symbols. This is equivalent to the application without any sort of lazy loading. (This is how most applications are written today.)\n- On the other extreme of the slider, we have a separate chunk for each symbol. This is how Qwik applications behave during development. Each symbol is in its own chunk.\n\nThe problem with a single chunk is:\n- It will contain many symbols which are not needed by the client. (Wasted bandwidth.)\n- The client can't run any symbols until the whole chunk is loaded.\n\nThe problem with a separate chunk for each symbol is:\n- The client will have to make many requests to load all of the chunks, often leading to undesirable waterfall requests.\n\nThe optimal solution is somewhere in the middle. We want to have a small number of chunks, but we also want to have the symbols that are used together to be co-located in the same chunk. Having a small number of chunks allows us to prioritize the order in which chunks load but at the same time amortize the cost of making HTTP requests. Having symbols co-located allows us to minimize the waterfall.\n\nThe good news is that with Qwik you are in full control of which symbol goes into which chunk. Normally breaking up your application for lazy loading requires the developer to write dynamic imports and re-factor the code. In Qwik, all `$()` are potential lazy load locations, all that is needed is to inform the bundler how to distribute the symbols.\n\n## `qwikVite()` Plugin\n\n`qwikVite()` plugin inside your `vite.config.ts` controls the symbol distribution. Normally the `entryStrategy` is set to `smart` which allows the Qwik to make heuristic guesses as to how the symbols should be lazy loaded. But it is possible to override the heuristic by providing `manual` configuration like this in `vite.config.ts` file:\n\n```typescript\nexport default defineConfig(() => {\n const routesDir = resolve('src', 'routes');\n return {\n // ...\n qwikVite({\n entryStrategy: {\n type: 'smart',\n manual: {\n ...bundle('bundleA', [\n 's_I5CyQjO9FjQ',\n 's_NsnidK2eXPg',\n 's_kDw0latGeM0',\n ]),\n ...bundle('bundleB', [\n 's_vXb90XKAnjE',\n 's_hYpp40gCb60',\n ]),\n ...bundle('bundleC', [\n 's_AqHBIVNKf34',\n 's_oEksvFPgMEM',\n 's_eePwnt3YTI8',\n ]),\n },\n },\n }),\n };\n});\n\nfunction bundle(bundleName: string, symbols: string[]) {\n return symbols.reduce((obj, key) => {\n // Sometimes symbols are prefixed with `s_`, remove it.\n obj[key.replace('s_', '')] = obj[key] = bundleName;\n return obj;\n }, {} as Record<string, string>);\n}\n```\n\nSo the question becomes how do you get the symbol names such as `s_I5CyQjO9FjQ`? See the next section Runtime Analytics.\n\n## Runtime analytics\n\nThe fundamental problem to solve is that determining the optimal bundles is not statically possible. The ideal bundles will depend on the user's behavior. Only after observing users' behavior can we determine which symbols are used together.\n\nTo collect symbol usage from a running application:\n\n1. Insert this code into your app:\n ```html\n <script>\n window.symbols = [];\n document.addEventListener('qsymbol', (e) => window.symbols.push(e.detail.symbol));\n </script>\n ```\n2. Perform some set of operations mimicking user behavior.\n3. Open the console and type `symbols` to see the list of symbols used. Use that information to update the `vite.config.ts` file.\n\nWe are looking into creating better ways of collecting this information in the future. (See [Insights](/docs/labs/insights.md).)\n\nSymbols hashes are designed to be stable even across many compilations. However, if the code undergoes complex refactoring it is possible for the hash to change. This will not break the application, but it may cause the symbol to be moved to a different sub-optimal chunk until runtime analytics can be collected again.\n\n## Service worker\n\nQwik apps employ a service worker to ensure that bundles are prefetched into the browser's cache and that any user interaction would result in a cache hit, hence no delay in interaction.\n\nSee [Speculative Module Fetching](/docs/advanced/speculative-module-fetching.md).\n\nService Worker feature is available only in secure contexts (HTTPS), in some or all supporting browsers. See the [`serviceWorker` property API specs](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/serviceWorker).\n\n## Events\n\nAll information regarding when the symbols are loaded can be observed by listening to the following custom events:\n\n### `qprefetch` custom event details.\n\n`qprefetch` event is fired when a new code path is exposed to the user by rendering a new application view. (For example, rendering a new modal dialog will have a new button. We would like to ensure that the new button code is prefetched so that if the user interacts with the button there will be no delay.)\nUsually, a service worker listens to the `qprefetch` event and loads the symbol into the cache. The service worker has a map of symbols to bundles, and it uses this information to determine which bundles to prefetch based on a symbol.\n\n```typescript\nexport interface QPrefetchDetail {\n /// A list of symbols to prefetch.\n symbols: string[];\n}\n```\n\n### `qsymbol` custom event details.\n\n`qsymbol` event is fired every time Qwik needs to resolve a symbol. Listening to this event can give you insight into when different symbols are loaded by your application. The information can then be used to better optimize your bundles by putting symbols that are needed together in the same bundle.\n\n```typescript\nexport interface QSymbolDetail {\n /// Optional DOM event which triggered the symbol resolution.\n element?: Element;\n /// Request time when the symbol was resolved.\n reqTime: number;\n /// Symbol being resolved.\n symbol: string;\n}\n```\n\n## Waterfall\n\nThe service worker attempts to minimize the waterfall by prefetching the bundles. To be able to do that the service worker has a `manifest` of symbols and chunks. The `manifest` represents a full graph of all of the symbols and their corresponding chunks. It also knows the import graph, so if a symbol is prefetched, the service worker will also prefetch all other symbols which are needed as part of the import graph.\n"},{"id":"/docs/guides/capacitor/","title":"Qwik Hybrid Native App Overview | Guides","description":"Learn to build hybrid native apps with Qwik.","url":"https://next.qwik.dev/docs/guides/capacitor/","content":"# Qwik for iOS and Android\n\n## Modernizing Mobile Development with a Hybrid Approach\n\nTraditionally, building native mobile applications meant managing two separate codebases: **Swift/Objective-C** for iOS and **Kotlin/Java** for Android. While this approach offers deep integration with each platform, it comes with significant drawbacks, including **increased development time**, **higher costs**, and **doubled maintenance efforts** for every feature or bug fix.\n\nThis new hybrid approach combines **[Qwik's](https://qwik.dev/) performance-optimized framework** with **[Capacitor's](https://capacitorjs.com/) native runtime** and **[Capawesome's](https://capawesome.io/) rich plugin ecosystem**, enabling developers to build high-performance mobile applications from a **single TypeScript codebase**. This architecture bridges the gap between web and native development, allowing:\n\n- Single codebase for iOS and Android\n- Reduced development and maintenance costs\n- Streamlined update process\n- Broad device compatibility\n- Access to native device features\n- Minimal code duplication\n\n## How It Works\n\nThe architecture combines three complementary technologies—**Qwik**, **Capacitor**, and a robust **plugin ecosystem**—to create a streamlined, high-performance hybrid mobile development platform. This approach prioritizes **speed**, **native integration**, and **efficient resource usage**, ensuring a smooth experience for both developers and end-users.\n\n### **1. Qwik Static Site Generation (SSG)**\n\nAt the core of this stack, your application is built as a **Qwik Static Site**. Qwik's **[Static Site Generation (SSG)](https://qwik.dev/docs/guides/static-site-generation/)** approach ensures that most of the application is pre-rendered at build time, resulting in **lightweight assets** that are optimized for mobile devices.\n\n**Why Static for Capacitor?**\n- **On-Device Hosting:** The static assets are served directly from the device's file system, eliminating the need for a remote server.\n- **Offline Availability:** Since the assets are bundled within the app, no network connection is required to load the initial UI.\n- **Faster Startup Times:** Pre-rendered assets minimize processing overhead, allowing the app to launch quickly.\n- **Improved Stability:** Reduced reliance on external servers leads to fewer points of failure.\n\n**Key Benefits of Qwik SSG:**\n- **Resumable Rendering:** Qwik's architecture allows code to execute only where and when it’s needed.\n- **Minimal Resource Usage:** Efficient rendering keeps CPU and memory usage low.\n- **Scalable Design:** Performance remains consistent across devices with varying capabilities.\n\nTogether, Qwik SSG and Capacitor enable an architecture where your app's web content behaves like native assets, loaded directly from the device with no dependency on external servers.\n\n### **2. Capacitor Integration**\n\nCapacitor acts as the bridge between your Qwik-generated static assets and native mobile APIs. It wraps your app in a native runtime, making it possible to access native device capabilities directly from your TypeScript code.\n\n**Why Capacitor is Essential:**\n- **Seamless Web-to-Native Bridge:** Native APIs (e.g., camera, storage, geolocation) are exposed to your Qwik app through JavaScript-friendly plugins.\n- **Local Asset Hosting:** Your app is served from local files, avoiding the latency and reliability issues of remote servers.\n- **Unified Build Workflow:** The same codebase is built for both iOS and Android, reducing duplication and maintenance overhead.\n- **Modern Tooling:** Capacitor integrates smoothly with build tools like Vite and development environments like VSCode.\n\n**Key Benefits of Capacitor:**\n- **Simplified Build Process:** Fewer steps and tools are required to compile and deploy native apps.\n- **Effortless Platform Management:** Easily add and manage platform-specific dependencies with Capacitor CLI.\n- **Native Runtime Stability:** Ensures that native code executes predictably across different devices.\n\nBy using Capacitor, your static Qwik app becomes a self-contained mobile app that can interact with device hardware and APIs as if it were built natively. Please refer to the official [Capacitor documentation](https://capacitorjs.com/docs) for more information on how to use Capacitor.\n\n### **3. Accessing Native Features**\n\nCapacitor enables your Qwik app to interact with native device features through an extensive ecosystem of **plugins**. These plugins act as modular bridges that translate JavaScript API calls into native commands, allowing seamless access to hardware and platform-specific functionality like the camera, GPS, or file system.\n\n#### **Capacitor Plugins:**\n- Developed and maintained by the Capacitor core team.\n- Provide robust APIs for essential device features, such as the camera, geolocation, file system, and push notifications.\n- Frequently updated to ensure compatibility with the latest iOS and Android versions.\n- Supported by comprehensive documentation and examples, making them easy to implement and maintain.\n\nCapacitor Plugins can be found [here](https://capacitorjs.com/docs/plugins).\n\n#### **Capawesome Plugins:**\n\nCapawesome expands Capacitor’s functionality with a collection of plugins designed to address advanced and specialized use cases not always covered by Capacitor's core plugin set. Two notable examples demonstrate its unique value:\n\n- **Live Updates:** Enables over-the-air updates for the app's web layer, allowing developers to deliver bug fixes, improvements, and new features without requiring users to download a new version from the app store. This reduces release cycle friction and ensures users always have the latest experience.\n\n- **Bluetooth Low Energy (BLE):** Offers reliable APIs for communicating with Bluetooth Low Energy peripherals, supporting secure and efficient interactions with devices such as fitness trackers, medical sensors, and smart IoT equipment.\n\nCapawesome plugins are built with a **TypeScript-first philosophy**, ensuring strong type safety, modern development standards, and seamless integration with development tools and workflows. This focus results in plugins that are easier to maintain, debug, and scale across projects.\n\nMany more Capawesome Plugins can be found [here](https://capawesome.io/plugins/).\n\n#### **Cordova Plugins:**\n- Provide access to a large library of plugins from the Cordova ecosystem, offering compatibility with legacy hybrid solutions.\n- Ideal for leveraging specialized or less commonly used native features not yet supported by Capacitor or Capawesome.\n- Capacitor’s compatibility layer ensures smooth integration, but long-term support may vary based on the plugin.\n\nCordova Plugins can be found [here](https://cordova.apache.org/plugins/).\n\n## **Prerequisites and Initial Setup**\n\n### **Required Tools**\n- **Node.js** (18.x or later)\n- **npm** or **pnpm**\n- **iOS Requirements:**\n - macOS computer\n - Xcode (latest version)\n - CocoaPods\n- **Android Requirements:**\n - Android Studio\n - Android SDK\n - Gradle\n\nPlease refer to each platform's official documentation for installation instructions and application build process.\n\n### **Environment Setup**\n\n1. **Create a Qwik Project**\n Start by creating a new Qwik project using the CLI:\n ```bash\n pnpm create qwik@latest\n ```\n\n2. **Add the Static Adapter**\n To prepare your Qwik app for static site generation (SSG), install the **static adapter**:\n ```bash\n pnpm run qwik add static\n ```\n This step ensures your app generates pre-rendered static files suitable for Capacitor.\n\n3. **Add Capacitor to Your Qwik Project**\n Install Capacitor dependencies and initialize Capacitor:\n ```bash\n pnpm i @capacitor/cli @capacitor/core\n npx cap init\n ```\n\n4. **Configure Capacitor**\n Your `capacitor.config.ts` file should looks something like this:\n ```typescript\n import type { CapacitorConfig } from '@capacitor/cli';\n\n const config: CapacitorConfig = {\n appId: 'com.example.app',\n appName: 'my-qwik-empty-starter',\n webDir: 'dist',\n server: {\n iosScheme: 'capacitor',\n androidScheme: 'https'\n }\n };\n\n export default config;\n ```\n\n5. **Install Platform-Specific Dependencies**\n Add support for iOS and Android platforms:\n ```bash\n pnpm i @capacitor/ios @capacitor/android\n ```\n\n6. **Initialize Native Platforms**\n Create the native project files:\n ```bash\n npx cap add ios\n npx cap add android\n ```\n\n## Development Workflow\n\n### Building and Running\n\nIn this section, we’ll walk through the process of creating a **production-ready build** of your Qwik application, syncing it with native platforms using **Capacitor**, and deploying it to an **iOS simulator** or **Android emulator**. This workflow ensures that your app is packaged with optimized static assets, making it ready for testing and deployment on mobile devices. Whether you're verifying functionality, refining the user experience, or preparing for final distribution, running the app in a native simulator or emulator is an essential step in validating its performance and behavior across platforms.\n\n1. Create a production build of your Qwik app:\n```bash\npnpm run build\n```\n\n2. Sync web assets to native platforms:\n```bash\nnpx cap sync\n```\n\n3. Run the app in simulator/emulator:\n```bash\nnpx cap run ios # Runs the app in an iOS simulator\nnpx cap run android # Runs the app in an Android emulator\n```\n\nAlternatively you can open native IDEs:\n```bash\nnpx cap open ios # Opens Xcode\nnpx cap open android # Opens Android Studio\n```\n\n## **How to Use Native Functionality with Plugins**\n\nThe **Device Plugin** is a straightforward example of how to integrate native functionality into your Qwik app using Capacitor. This plugin allows you to access key device-specific information, such as the model, operating system, and OS version. This data can be valuable for debugging, adapting your app's behavior based on the device's capabilities, or collecting insights for analytics. Importantly, the Device plugin works seamlessly in both iOS simulators and Android emulators, making it an ideal choice for testing native integration without requiring additional configuration.\n### Install the Device Plugin\n\n1. Add the Device plugin to your project:\n\n```bash\npnpm i @capacitor/device\n```\n\n2. Add the plugin to your `capacitor.config.ts` file:\n\n```TypeScript\nplugins: {\n Device: {\n // No configuration required\n },\n},\n```\n\n3. Update your Qwik component `index.tsx` to use the Device plugin:\n\n```tsx\nimport { component$, useSignal, useVisibleTask$ } from '@qwik.dev/core';\nimport { Device } from '@capacitor/device';\n\nexport const DeviceInfoComponent = component$(() => {\n const deviceInfo = useSignal<string | null>(null);\n\n useVisibleTask$(async () => {\n const info = await Device.getInfo();\n deviceInfo.value = `Model: ${info.model}, OS: ${info.operatingSystem}, Version: ${info.osVersion}`;\n });\n\n return (\n <div style={{ paddingTop: \"40px\" }}>\n <h2>Device Information</h2>\n {deviceInfo.value ? (\n <p>{deviceInfo.value}</p>\n ) : (\n <p>Loading device information...</p>\n )}\n </div>\n );\n});\n```\n\n4. Update the native platforms:\n\nYou will need to update the native platforms to ensure that the plugin is properly integrated into your app. This step ensures that the native code is available for the Qwik app.\n\n***NOTE:** As of the time of writing this guide, a bug exists in XCode that requires you to delete the iOS app before redeploying.*\n\n```bash\nnpx cap sync\nnpx cap run ios # Runs the app in an iOS simulator\nnpx cap run android # Runs the app in an Android emulator\n```\n\n## **Over-the-Air Updates with Capawesome**\n\nThis is a highly simplified example of how to self-host a live update from your local system. To implement a robust OTA update system please follow the guides provided at Capawesome.\n\n1. Install the Live Update plugin:\n\n```bash\npnpm i @capawesome/capacitor-live-update\n```\n\n2. Update your `capacitor.config.ts` file to enable live reload:\n\n```typescript\n plugins: {\n ...\n LiveUpdate: {\n appId: \"YOUR_APP_ID\",\n // publicKey:\n // \"-----BEGIN PUBLIC KEY-----\\nYOUR_PUBLIC_KEY\\n-----END PUBLIC KEY-----\",\n },\n },\n```\n\n3. Update your `index.tsx` as follows and be sure to set `YOUR_IP`. When the user clicks the button, it will update the app.\n\n```tsx\nimport {\n $,\n component$,\n useComputed$,\n useSignal,\n useVisibleTask$,\n} from \"@qwik.dev/core\";\nimport type { DocumentHead } from \"@qwik.dev/router\";\nimport { LiveUpdate } from \"@capawesome/capacitor-live-update\";\n\nconst VERSION = \"1.0.0\";\nconst OTA_SERVER_URL = \"http://YOUR_IP:8000\";\nconst wait = () => new Promise((resolve) => setTimeout(resolve, 1000));\n\nexport default component$(() => {\n const version = useSignal<string>(VERSION);\n const updateStatus = useSignal<string | null>(null);\n const otaUrl = useComputed$(() => `${OTA_SERVER_URL}/${version.value}.zip`);\n\n const handleUpdate = $(async () => {\n try {\n updateStatus.value = `Checking for existing bundle...`;\n console.log(updateStatus.value);\n await wait();\n\n const { bundleIds } = await LiveUpdate.getBundles();\n const bundleExists = bundleIds.includes(version.value);\n\n if (bundleExists) {\n updateStatus.value = `Bundle ${version.value} already exists. Switching to it...`;\n console.log(updateStatus.value);\n await wait();\n\n await LiveUpdate.setNextBundle({ bundleId: version.value });\n await LiveUpdate.reload();\n\n updateStatus.value = `Switched to existing bundle ${version.value}!`;\n console.log(updateStatus.value);\n await wait();\n } else {\n updateStatus.value = `Downloading update from ${otaUrl.value}...`;\n console.log(updateStatus.value);\n await wait();\n\n await LiveUpdate.downloadBundle({\n url: otaUrl.value,\n bundleId: version.value,\n });\n\n updateStatus.value = \"Applying update...\";\n console.log(updateStatus.value);\n await wait();\n\n await LiveUpdate.setNextBundle({ bundleId: version.value });\n await LiveUpdate.reload();\n\n updateStatus.value = \"Update applied successfully!\";\n console.log(updateStatus.value);\n await wait();\n }\n } catch (error) {\n updateStatus.value = `Update to ${otaUrl.value} failed. Error: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`;\n console.error(updateStatus.value);\n await wait();\n }\n });\n\n useVisibleTask$(async () => {\n try {\n updateStatus.value = \"App ready\";\n console.log(updateStatus.value);\n await wait();\n\n LiveUpdate.ready();\n } catch (error) {\n (updateStatus.value = \"Error notifying app readiness:\"), error;\n console.error(updateStatus.value);\n await wait();\n }\n });\n\n return (\n <div style={{ padding: \"40px\" }}>\n <h2>OTA Update</h2>\n <h3>Current Version: {VERSION}</h3>\n <p>Enter the version you want to update to and click the button below.</p>\n\n <div style={{ marginBottom: \"20px\" }}>\n <label>\n Version:\n <input\n value={version.value}\n onInput$={(event) =>\n (version.value = (event.target as HTMLInputElement).value)\n }\n style={{\n marginLeft: \"10px\",\n padding: \"8px\",\n fontSize: \"14px\",\n borderRadius: \"5px\",\n border: \"1px solid #ccc\",\n }}\n />\n </label>\n </div>\n\n <button\n onClick$={handleUpdate}\n style={{\n marginTop: \"10px\",\n padding: \"10px 20px\",\n fontSize: \"14px\",\n cursor: \"pointer\",\n borderRadius: \"5px\",\n border: \"none\",\n backgroundColor: \"#0078D4\",\n color: \"#fff\",\n }}\n >\n Update Now\n </button>\n\n {updateStatus.value && (\n <p style={{ marginTop: \"20px\" }}>{updateStatus.value}</p>\n )}\n </div>\n );\n});\n\nexport const head: DocumentHead = {\n title: \"Dynamic OTA Update with Capawesome\",\n meta: [\n {\n name: \"description\",\n content: \"Qwik app with OTA updates.\",\n },\n ],\n};\n```\n\n4. Build the initial app and deploy it to your device.\n\nBuild and deploy the app to your device.\n\n```bash\npnpm run build\nnpx cap sync\nnpx cap run ios # Runs the app in an iOS simulator\nnpx cap run android # Runs the app in an Android emulator\n```\n\n5. Build OTA update bundles.\n\nUpdate the version number in the `index.tsx` file and zip it with the same version number (i.e. `1.0.1.zip`). You can build multiple versions and switch between them.\n\n```bash\nmkdir -p ota_bundles # Only required the first time\npnpm run build\nzip -r ota_bundles/VERSION.zip dist/*\n```\n\n6. Start a simple OTA Bundle Server to host your compressed bundles.\n\n```bash\nnpx serve ota_bundles -l 8000\n```\n\n7. Test Over-the-Air Updates from the OTA Bundle Server.\n\nOnce the app is updated, the new version will be used across app launches. You can repeat step 5 to create a new bundles.\n\n#### **Capawesome Cloud**\n\nIf you are using [Capawesome Cloud](https://capawesome.io/cloud/), you can use the Live Update plugin to update your app without having to build and host a new version of the app. This is a great option for production environments.\n\n### Live Development\n\nLive development is a critical part of building modern hybrid mobile applications, allowing developers to make changes to their code and see the results in real-time on a connected device or simulator. With Capacitor’s live reload feature, you can bridge the gap between rapid web development workflows and native mobile deployment. Instead of waiting through lengthy build and redeployment cycles, live development enables instant feedback, making it easier to fine-tune UI elements, test native functionality, and troubleshoot platform-specific behaviors. This approach reduces development friction, accelerates iteration, and fosters a smoother experience when building, testing, and refining Qwik-powered mobile apps.\n\n1. Update `vite.config.ts` to enable access to the dev server from the local network:\n```typescript\n server: {\n ...\n host: true, // Enables access from the local network\n }\n ```\n\n2. Update `capacitor.config.ts` to enable live reload from the dev server's network accessible IP address:\n```typescript\nconst config: CapacitorConfig = {\n ...\n server: {\n url: 'http://YOUR_IP:5172',\n cleartext: true\n }\n};\n```\n\n3. Run the app in simulator/emulator:\n```bash\nnpx cap run ios\nnpx cap run android\n```\n\n4. Start Qwik's dev server:\n```bash\npnpm run dev\n```\n\n**NOTE:** After you run the dev server, you will need to restart the native IDEs to see the changes.\n"},{"id":"/docs/guides/debugging/","title":"Debugging | Introduction","description":"Learn a few debugging tips to streamline your journey with Qwik.","url":"https://next.qwik.dev/docs/guides/debugging/","content":"# Debugging\n\n## Save yourself a bit of time with 'click to source'\n\nDuring development, you can quickly access the source code of any element on a webpage by holding Option (⌥) or Alt key,\nclick on whatever you're curious about, and Qwik will immediately open your source code right on top of that element.\nSeriously, any component, link, header - you name it, you can peek at its code.\n\nQwik tries to guess what code editor you like to use.\nIf it guesses wrong, no biggie! Just give Qwik a hint by setting the `LAUNCH_EDITOR` environment variable.\nFor example, if you're on a Mac and use VS Code, you'd type `export LAUNCH_EDITOR=code` in your terminal.\n\nUnder the hood [launch-editor library](https://github.com/yyx990803/launch-editor/tree/master) is used, here are the [supported editors](https://github.com/yyx990803/launch-editor/tree/master?tab=readme-ov-file#supported-editors)\n\n## Finding leftover `console.log` statements\n\nWhen working on larger codebases, you might occasionally leave `console.log` statements in your code unintentionally. These can clutter your terminal output, and it's often difficult to identify which file and line number produced each log message.\n\n### Using ESLint rules (recommended)\n\nThe recommended approach is to configure ESLint to prevent `console.log` statements from being committed:\n\n```js\n// eslint.config.js\nexport default [\n {\n rules: {\n 'no-console': ['error', { allow: ['warn', 'error'] }],\n },\n },\n];\n```\n\nThis will catch `console.log` statements during development, preventing them from being committed.\n\n### Using IDE search\n\nMost IDEs provide powerful search functionality to find all occurrences of `console.log` across your codebase:\n- **VS Code**: Press `Ctrl+Shift+F` (or `Cmd+Shift+F` on Mac) and search for `console\\.log`\n- **Enable regex mode** to match only exact `console.log` calls and not `console.error` or `console.warn`\n\nThis approach is simple but requires manual review of each occurrence to determine if it's intentional or leftover debug code.\n\n### Using stack traces (temporary debugging)\n\nIf you need to identify existing leftover console.logs in a codebase that's already cluttered, you can temporarily override `console.log` to include stack traces.\n\n#### In client-side components\n\nYou can override `console.log` in your component code:\n\n```tsx\n// root.tsx or layout.tsx\nexport default component$(() => {\n // Override console.log to include stack traces\n useVisibleTask$(() => {\n const originalLog = console.log;\n console.log = (...args: any[]) => {\n const stack = new Error()\n .stack?.split('\\n')\n .filter((i) => !/^.*(\\.vite|\\.main\\.jsx|node_modules).*/.test(i));\n originalLog(stack, ...args);\n };\n });\n\n return (\n // your component JSX\n );\n});\n```\n\n#### In server-side entry files\n\nFor entry files like `entry.express.tsx`, `entry.dev.tsx`, or `entry.preview.tsx`, you can override `console.log` at the module level:\n\n```tsx\n// entry.express.tsx or entry.dev.tsx or entry.preview.tsx\n\n// Override console.log at the top level\nconst originalLog = console.log;\nconsole.log = (...args: any[]) => {\n const stack = new Error()\n .stack?.split('\\n')\n .filter((i) => !/^.*(node_modules|internal).*/.test(i));\n originalLog(stack, ...args);\n};\n\n// Rest of your entry file code...\n```\n\nRemember to remove these overrides after debugging. The filter regex should be adjusted based on your specific build setup.\n"},{"id":"/docs/guides/deploy/","title":"/docs/guides/deploy/","description":"","url":"https://next.qwik.dev/docs/guides/deploy/","content":"\n"},{"id":"/docs/guides/env-variables/","title":"Environment variables | Qwik Router","description":"Qwik apps can read environment variables in two main ways build-time variables and server-side variables.","url":"https://next.qwik.dev/docs/guides/env-variables/","content":"# Environment Variables\n\nEnvironment variables are a way to store configuration values or sensitive data that should not be included directly in your application code. These variables are typically used for things like API keys, database connection strings, or other environment-specific settings.\n\n## Types of Environment Variables\n### Build-time\n - Environment variables which are prepended with `PUBLIC_` and are available both on the `client` and the `server`.\n### Server-side\n - Environment Variables that are only accessible on the `server`.\n\n**IMPORTANT**\nDO NOT use `build-time` environment variables, (ie. variables that start with `PUBLIC_`) to store any sensitive information, such as API keys, secrets, passwords, etc. These variables are accessible in the browser — **ONLY PUBLIC DATA**.\n\n```ini title=\".env.local\"\n# This will only be available when run on the server\nAPI_KEY=secretApiKeyHere\n# This will be available everywhere\nPUBLIC_API_URL=https://api.example.com\n```\n\n## Default Environment Variables\nQwik Router includes a few environment variables out of the box\n - `BASE_URL`: `string` - Returns the base url for the page,\n - `MODE`: `string` - Returns the rendering mode,\n - `DEV`: `boolean` - Returns if you are in development mode,\n - `PROD`: `boolean` - Returns if you are in production mode,\n - `SSR`: `boolean` - Returns whether if this was rendered with ssr or not\n\nThe preferred method for accessing environment variables in Qwik is via `import.meta.env.*` (client side) or through the Request object when run server side.\n**IMPORTANT**\n`process.env` is a Node.js only API, and should be avoided at all costs.\n\n## Build-time variables\n\nBuild-time variables are powered by [Vite](https://vitejs.dev/guide/env-and-mode.html). They are defined in `.env` files and are available **in the browser and in the server-side code**.\n\nNotice that build-time variables should be considered as **public**, since they will be hardcoded in the browser build, which can be easily read by anyone.\n\nBuild-time variables are prefixed by default with `PUBLIC_` and can be accessed with `import.meta.env.PUBLIC_*`.\n\n### Defining Variables\n\n```ini title=\".env.local\" /PUBLIC_API_URL/#a\nPUBLIC_API_URL=https://api.example.com\n```\n\n### Usage\n\n```tsx {4} /PUBLIC_API_URL/#a title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n // `import.meta.env.PUBLIC_*` variables can be read anywhere, including browser\n return <div>PUBLIC_API_URL: {import.meta.env.PUBLIC_API_URL}</div>\n})\n```\n\n`import.meta.env.PUBLIC_*` variables can be read anywhere, but do not put any sensitive information in them, since they will be visible to the client.\n\n## Server-side Variables\n\nServer-side variables are fundamentally runtime variables that are only available in the server-side code.\n\nThey are not known at build-time and are not available in the browser, so they can be considered as **private**.\n\nDuring production, **setting server-side variables is very platform specific**. Most of the platforms allow you to set environment variables from their dashboard, or CLI. Please, refer to your platform (cloudflare, vercel, netlify) documentation for more information.\n\n**Special Considerations for Docker and Fastify**\n\n- **Docker:** While Docker allows the inclusion of environment variables directly in the Dockerfile, this method can expose sensitive data. A more secure practice is to manage these variables at runtime using Docker Compose. For example:\n```ini title=\"docker-compose.yml\"\nversion: '3.8'\nservices:\n your-service:\n image: your-image-name\n environment:\n - FOO=BAR\n```\n\n- **Fastify within Docker:** Environment variables placed in `.env` or `.env.local` files may not be automatically recognized in production environments when using Fastify. For these settings to take effect it may be necessary to explicitly load them within your Fastify application or pass them through Docker's environment management system (Docker Compose) as shown above.\n\n### Defining Variables\n\n```ini title=\".env.local\"\nDB_PRIVATE_KEY=123456789\n```\n\n**IMPORTANT**\nMake sure you never commit `.env.local` files to git.\n\n### Usage Examples\n\nServer-side variables can only be accessed in server-only APIs that expose the `RequestEvent` object, such as `routeLoader$()`, `routeAction$()`, `server$()` and endpoint handlers such as `onGet`, `onPost`, `onRequest` etc.\n\n```tsx /DB_PRIVATE_KEY/ title=\"src/routes/index.tsx\"\nimport {\n routeLoader$,\n routeAction$,\n server$,\n type RequestEvent,\n} from '@qwik.dev/router';\n\nexport const onGet = (requestEvent: RequestEvent) => {\n console.log(requestEvent.env.get('DB_PRIVATE_KEY'));\n};\n\nexport const onPost = (requestEvent: RequestEvent) => {\n console.log(requestEvent.env.get('DB_PRIVATE_KEY'));\n};\n\nexport const useAction = routeAction$(async (_, requestEvent) => {\n console.log(requestEvent.env.get('DB_PRIVATE_KEY'));\n});\n\nexport const useLoader = routeLoader$(async (requestEvent) => {\n console.log(requestEvent.env.get('DB_PRIVATE_KEY'));\n});\n\nexport const serverFunction = server$(function () {\n // `this` is the `RequestEvent` object\n console.log(this.env.get('DB_PRIVATE_KEY'));\n});\n```\n\n### Usage in serverfull architecture (Example:Express)\n\nFor accessing the .env variables in serverfull architecture you need to use singleton design pattern, initialize the db in a plugin, and access it with getDB wherever it is needed.\n\n```typescript title=\"src/util/db.ts\"\nlet _db!: AppDatabase;\n\nexport function getDB() {\n // eslint-disable-next-line\n if (!_db) {\n throw new Error('DB not set');\n }\n return _db;\n}\n\nexport async function initializeDbIfNeeded(factory: () => Promise<AppDatabase>) {\n // eslint-disable-next-line\n if (!_db) {\n _db = await factory();\n }\n}\n```\n\n```typescript title=\"src/routes/plugin@db.ts\"\nexport const onRequest: RequestHandler = async ({ env }) => {\n const url = env.get('PRIVATE_LIBSQL_DB_URL')!;\n const authToken = env.get('PRIVATE_LIBSQL_DB_API_TOKEN')!;\n await initializeDbIfNeeded(initLibSql(url, authToken));\n};\n```\n\n### Managing Environment Variables Throughout the Application Lifecycle\n\nIn modern applications, environment variables play a crucial role in managing application settings and configurations across various environments without hardcoding sensitive data into the source code.\n\nQwik Router adapters use the following:\n- Azure, Cloud Run, Netlify Edge, Node Server, use ORIGIN or URL\n- Cloudflare Pages uses CF_PAGES_URL or ORIGIN\n- Vercel uses VERCEL_URL\n\n**Additional Resources**\n\nThis is not a comprehensive guide on environment variables, nor does it cover all of the 3rd-Party hosting scenarios. It is meant to give insight that can be applied across various environments.\n\nSee this video for a detailed explanation:\nhttps://youtu.be/NPf39RWc8LM\n"},{"id":"/docs/guides/mdx/","title":"Markdown and MDX | Guides","description":"Learn how to use Markdown and MDX in Qwik Router.","url":"https://next.qwik.dev/docs/guides/mdx/","content":"# MDX\n\nAn alternative way to author content is using `.mdx` files ([Markdown JSX](https://mdxjs.com/)). These files are authored as Markdown, but they are compiled down to Qwik components. In addition to Markdown syntax, `.mdx` files can also refer to other components.\n\nLet's assume you have your routes set up like this:\n\n```bash\nsrc/\n`-- routes/\n `-- some/\n `-- path/\n `-- index.mdx # https://example.com/some/path\n```\n\n```markdown title=\"src/routes/some/path/index.mdx\"\n---\ntitle: Hello World Title\n---\n\nThis is a simple hello world component.\n\n```\n\nThe above component will be rendered at `https://example.com/some/path`.\n\n## Importing other components.\n\n[MDX](https://mdxjs.com/) is a creative opportunity for you to come up with new content quickly (\"Qwikly\" ) and if you need more interaction on your page you can seamlessly integrate your Qwik components like so:\n\n```bash\nsrc/\n|-- components/\n| `-- counter\n| `-- counter.tsx\n`-- routes/\n `-- some/\n `-- path/\n `-- index.mdx # https://example.com/some/path\n```\n\n```markdown title=\"src/routes/some/path/index.mdx\"\n---\ntitle: Hello World Title\n---\nimport { Counter } from \"../../../components/counter/counter\";\n\nThis is a simple hello world component.\n\n<Counter />\n\n```\n\n```tsx title=\"src/components/counter/counter.tsx\"\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport const Counter = component$(() => {\n const count = useSignal(0);\n\n return (\n <button class=\"counter\" type=\"button\" onClick$={() => count.value++}>\n Increment {count.value}\n </button>\n );\n});\n```\n\n**Note**: A key difference between Qwik Router and some other meta-frameworks' routers is directory-based routing. Every route needs to be defined as `a-directory/index.(tsx,ts,js,jsx,md,mdx)`.\n\nIn other meta-frameworks' routers `about.mdx` might render the route `http://example.com/about`. However, this will not work in the Qwik Router. You must rename the file to `about/index.mdx` for Qwik Router to know to render it.\n\n## Disabling default MDX plugins included.\n\nQwik Router includes 3 plugins by default.\n\n- [remarkGfm](https://github.com/remarkjs/remark-gfm): [GFM](https://github.github.com/gfm/) support (autolink literals, footnotes, strikethrough, tables, tasklists).\n- [rehypeSyntaxHighlight](https://github.com/wooorm/refractor): Lightweight, robust, elegant virtual syntax highlighting using Prism.\n- [rehypeAutolinkHeadings](https://github.com/rehypejs/rehype-autolink-headings): Plugin to add links to headings in HTML.\n\nThese plugins can be disabled independently in the following way:\n\n```tsx title=\"vite.config.js\"\nimport { defineConfig } from 'vite';\nimport { qwikRouter } from '@qwik.dev/router/vite';\n// See below\nimport rehypeAutolinkHeadings from 'rehype-autolink-headings';\nexport default defineConfig(() => {\n return {\n plugins: [\n qwikRouter({\n mdxPlugins: {\n remarkGfm: false,\n rehypeSyntaxHighlight: false,\n rehypeAutolinkHeadings: false,\n },\n mdx: {\n rehypePlugins: [\n // Plugins can now be added manually to use a different configuration\n [rehypeAutolinkHeadings, { behavior: 'wrap' }],\n ],\n },\n }),\n /* the rest of the configuration */\n ],\n };\n});\n```\n\n## Open Graph Properties\n\nYou can use `og` or `opengraph` property to define [Open Graph protocol](https://ogp.me/) metadata.\n\n```yaml\ntitle: My Title\ndescription: My Description\nog:\n - title: My Custom Title\n description: true\n - image: https://example.com/rock.jpg\n image:alt: A shiny red apple with a bite taken out\n - image: https://example.com/rock2.jpg\n```\n\nSetting `og:title` or `og:description` to `true` will check and use outside `title` and `description` property instead. Thus, you can avoid writing a same title and description twice.\n\nThe above example will generate the following HTML code.\n\n```html\n<title>My Title</title>\n<meta name=\"description\" content=\"My Description\" />\n\n<meta property=\"og:title\" content=\"My Custom Title\" />\n<meta property=\"og:description\" content=\"My Description\" />\n\n<meta property=\"og:image\" content=\"https://example.com/rock.jpg\" />\n<meta property=\"og:image:alt\" content=\"A shiny red apple with a bite taken out\" />\n\n<meta property=\"og:image\" content=\"https://example.com/rock2.jpg\" />\n```\n\n## Reading frontmatter data\nFrontmatter keys are accessible by leveraging the `useDocumentHead()` hook.\n\n```markdown title=\"src/routes/some/path/index.mdx\"\n---\ntitle: Hello World Title\ntags:\n - super\n - exiting\n - docs\n---\nimport { Tags } from \"../../../components/tags/tags\";\n\nThis is a simple hello world component.\n\n<Tags />\n```\n\n```tsx title=\"src/components/tags/tags.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { useDocumentHead } from '@qwik.dev/router';\n\nexport const Tags = component$(() => {\n const { frontmatter } = useDocumentHead();\n\n if (frontmatter.tags.length === 0) {\n return null;\n }\n\n return (\n <ul>\n {frontmatter.tags.map((tag: string) => (\n <li key={`tag-${tag}`}>{tag}</li>\n ))}\n </ul>\n );\n});\n```\n\n## `useContent()`\n\nThe [`useContent()`](/docs/api.md#usecontent) function retrieves the nearest content information for the current route. The returned object includes:\n\n```ts\nheadings: ContentHeading[] | undefined;\nmenu: ContentMenu | undefined;\n```\n\nThe `headings` array includes data about a markdown file's `<h1>` to `<h6>` [html heading elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements).\n\nMenus are contextual data declared with `menu.md` files. See [menus file definition](/docs/advanced/menu.md) for more information on the file format and location.\n\n# Dynamic Page Navigation with MDX\n\nWhen working with documentation or content-heavy pages in Qwik Router, you often need to generate a table of contents or sidebar navigation based on the page's content. Qwik Router provides a built-in solution for this through the `useContent()` hook, which can automatically extract headings from your MDX files.\n\n## Using `useContent()` for Page Navigation\n\nThe `useContent()` hook allows you to access metadata about your current MDX page, including all its headings. This is particularly useful for:\n\n- Creating a table of contents for long articles\n- Building dynamic sidebar navigation\n- Implementing \"jump to section\" functionality\n- Generating progress indicators for article sections\n\nHere's a complete example of how to create a dynamic table of contents:\n\n```tsx\nimport { component$, useContent } from '@builder.io/qwik';\n\nexport const TableOfContents = component$(() => {\n const content = useContent();\n\n return (\n <nav class=\"toc\">\n <h4>On this page</h4>\n <ul>\n {content.headings?.map((heading) => (\n <li\n key={heading.id}\n style={{\n // Indent based on heading level\n marginLeft: `${(heading.level - 1) * 12}px`\n }}\n >\n <a href={`#${heading.id}`}>{heading.text}</a>\n </li>\n ))}\n </ul>\n </nav>\n );\n});\n```\n\n## Understanding the Headings Data\n\nThe `headings` property from `useContent()` provides an array of heading objects with the following information:\n\n- `id`: The auto-generated ID for the heading (used for anchor links)\n- `text`: The actual text content of the heading\n- `level`: The heading level (1 for h1, 2 for h2, etc.)\n\nThis only works with `.mdx` files - headings in `.tsx` files are not detected.\n\n## Common Use Cases\n\n### Progressive Disclosure Navigation\n\nYou can create a collapsible navigation that shows the current section and its sub-sections:\n\n```tsx\nexport const ProgressiveNav = component$(() => {\n const content = useContent();\n const currentSection = useSignal<string | null>(null);\n\n return (\n <nav>\n {content.headings?.map((heading) => {\n if (heading.level === 2) { // Only show h2 as main sections\n const subHeadings = content.headings.filter(h =>\n h.level === 3 &&\n h.id.startsWith(heading.id.split('-')[0])\n );\n\n return (\n <div key={heading.id}>\n <a\n href={`#${heading.id}`}\n onClick$={() => currentSection.value = heading.id}\n >\n {heading.text}\n </a>\n {currentSection.value === heading.id && (\n <ul>\n {subHeadings.map(sub => (\n <li key={sub.id}>\n <a href={`#${sub.id}`}>{sub.text}</a>\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n }\n })}\n </nav>\n );\n});\n```\n\n### Reading Progress Indicator\n\nYou can combine heading information with scroll position to create a reading progress indicator:\n\n```tsx\nexport const ReadingProgress = component$(() => {\n const content = useContent();\n const activeSection = useSignal('');\n\n useOnWindow('scroll', $(() => {\n const headingElements = content.headings?.map(h =>\n document.getElementById(h.id)\n ).filter(Boolean) || [];\n\n const currentHeading = headingElements.find(el => {\n const rect = el!.getBoundingClientRect();\n return rect.top > 0 && rect.top < window.innerHeight / 2;\n });\n\n if (currentHeading) {\n activeSection.value = currentHeading.id;\n }\n }));\n\n return (\n <nav>\n {content.headings?.map(heading => (\n <a\n key={heading.id}\n href={`#${heading.id}`}\n class={{\n active: activeSection.value === heading.id\n }}\n >\n {heading.text}\n </a>\n ))}\n </nav>\n );\n});\n```\n\n## Tips and Best Practices\n\n1. **Consistent Heading Structure**: Maintain a logical heading hierarchy in your MDX files to ensure the navigation makes sense.\n\n2. **Performance**: The `useContent()` hook is optimized and won't cause unnecessary re-renders, so you can safely use it in navigation components.\n\n3. **Styling**: Consider using the heading level information to create visual hierarchy in your navigation:\n ```css\n .toc a {\n /* Base styles */\n }\n\n /* Style based on heading level */\n [data-level=\"1\"] { font-size: 1.2em; font-weight: bold; }\n [data-level=\"2\"] { font-size: 1.1em; }\n [data-level=\"3\"] { font-size: 1em; }\n ```\n\n4. **Accessibility**: Always ensure your dynamic navigation includes proper ARIA labels and keyboard navigation support.\n\n## Notes and Limitations\n\n- This functionality only works with `.mdx` files, not with `.tsx` or other file types\n- Headings must have unique content to generate unique IDs\n- The heading data is available only on the client-side after hydration\n- Consider using `useVisibleTask$` if you need to interact with the heading elements in the DOM\n"},{"id":"/docs/guides/qwik-nutshell/","title":"Qwik in a nutshell | Introduction","description":"Learn the general concepts of Qwik in this short introduction guide.","url":"https://next.qwik.dev/docs/guides/qwik-nutshell/","content":"# Qwik in a nutshell\n\n## Components\n\nQwik components are very similar to React components. They are functions that return JSX. However, `component$(...)` needs to be used, event handlers must have the `$` suffix, state is created using `useSignal()`, `class` is used instead of `className` and some other differences.\n\n```tsx title=\"src/components/my-other-component/index.tsx\"\nimport { component$, Slot } from '@qwik.dev/core';\nimport type { ClassList } from '@qwik.dev/core'\n\nexport const MyOtherComponent = component$((props: { class?: ClassList }) => { // return <div class={class}><Slot /></div>;\n});\n```\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\n\n// Other components can be imported and used in JSX.\nimport { MyOtherComponent } from './my-other-component';\n\ninterface MyComponentProps {\n step: number;\n}\n\n// Components are always declared with the `component$` function.\nexport const MyComponent = component$((props: MyComponentProps) => {\n // Components use the `useSignal` hook to create reactive state.\n const count = useSignal(0); // { value: 0 }\n return (\n <>\n <button\n onClick$={() => {\n // Event handlers have the `$` suffix.\n count.value = count.value + props.step;\n }}\n >\n Increment by {props.step}\n </button>\n <main\n class={{\n even: count.value % 2 === 0,\n odd: count.value % 2 === 1,\n }}\n >\n <h1>Count: {count.value}</h1>\n <MyOtherComponent class=\"correct-way\"> {/* */}\n {count.value > 10 && <p>Count is greater than 10</p>}\n {count.value > 10 ? <p>Count is greater than 10</p> : <p>Count is less than 10</p>}\n </MyOtherComponent>\n </main>\n </>\n );\n});\n```\n\n### Rendering a list of items\n\nLike in React, you can render a list of items using the `map` function, however every item in the list must have a unique `key` property. The `key` must be a string, or number and must be unique within the list.\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { US_PRESIDENTS } from './presidents';\n\nexport const PresidentsList = component$(() => {\n return (\n <ul>\n {US_PRESIDENTS.map((president) => (\n <li key={president.number}>\n <h2>{president.name}</h2>\n <p>{president.description}</p>\n </li>\n ))}\n </ul>\n );\n});\n```\n\n### Reusing event handlers\n\nEvent handlers can be reused across JSX nodes. This is done by creating a handler using the `$(...handler...)`.\n\n```tsx\nimport { $, component$, useSignal } from '@qwik.dev/core';\n\ninterface MyComponentProps {\n step: number;\n}\n\n// Components are always declared with the `component$` function.\nexport const MyComponent = component$(() => {\n const count = useSignal(0);\n\n // Notice the `$(...)` around the event handler function.\n const inputHandler = $((event, elem) => {\n console.log(event.type, elem.value);\n });\n\n return (\n <>\n <input name=\"name\" onInput$={inputHandler} />\n <input\n name=\"password\"\n onInput$={inputHandler}\n />\n </>\n );\n});\n```\n\n### Content projection\n\nContent projection is done by the `<Slot/>` component, which is exported from `@qwik.dev/core`. Slots can be named, and can be projected into using the `q:slot` attribute.\n\n```tsx\n// File: src/components/Button/Button.tsx\nimport { component$, Slot } from '@qwik.dev/core';\nimport styles from './Button.module.css';\n\nexport const Button = component$(() => {\n return (\n <button class={styles.button}>\n <div class={styles.start}>\n <Slot name=\"start\" />\n </div>\n <Slot />\n <div class={styles.end}>\n <Slot name=\"end\" />\n </div>\n </button>\n );\n});\n\nexport default component$(() => {\n return (\n <Button>\n <span q:slot=\"start\"></span>\n Hello world\n <span q:slot=\"end\"></span>\n </Button>\n );\n});\n```\n\n### Rules of use hooks\n\nMethods that start with `use` are special in Qwik, such as `useSignal()`, `useStore()`, `useOn()`, `useTask$()`, `useLocation()` and so on. Very similar to React hooks.\n\n- They can only be called within a component$.\n- They can only be called from the top level of a component$, not inside a conditional, or a loop.\n\n## Styling\n\nQwik supports out of the box, CSS modules, or even Tailwind, global CSS imports and lazy loading scoped CSS using `useStylesScoped$()`. CSS Modules are the recommended way to style Qwik components.\n\n### CSS Modules\n\nTo use CSS modules, simply create a `.module.css` file. For example, `src/components/MyComponent/MyComponent.module.css`.\n\n```css title=\"src/components/MyComponent/MyComponent.module.css\"\n.container {\n background-color: red;\n}\n```\n\nThen, import the CSS module in your component.\n\n```tsx title=\"src/components/MyComponent/MyComponent.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport styles from './MyComponent.module.css';\n\nexport default component$(() => {\n return <div class={styles.container}>Hello world</div>;\n});\n```\n\nRemember that Qwik uses `class` instead of `className` for CSS classes.\n\n## $(...) rules\n\nThe `$(...)` function and any function that end with `$` are special in Qwik, such as: `$()`, `useTask$()`, `useVisibleTask$()`... The `$` at the end represents a lazy loading boundary. There are some rules that apply to the first argument of any `$` function. It is NOT related to jQuery at all.\n\n- The first argument must be an imported variable.\n- The first argument must be a declared variable at the top level of the same module.\n- The first argument must be an expression any variables.\n- If the first argument is a function, it can only capture variables that are declared at the top level of the same module or which value is serializable. Serializable values include: `string`, `number`, `boolean`, `null`, `undefined`, `Array`, `Object`, `Date`, `RegExp`, `Map`, `Set`, `BigInt`, `Promise`, `Error`, `JSX nodes`, `Signal`, `Store` and even HTMLElements.\n\n```tsx\n// Valid examples of `$` functions.\nimport { $, component$, useSignal } from '@qwik.dev/core';\nimport { importedFunction } from './my-other-module';\n\nexport function exportedFunction() {\n console.log('exported function');\n}\n\nexport default component$(() => {\n // The first argument is a function.\n const valid1 = $((event, elem) => {\n console.log(event.type, elem.value);\n });\n\n // The first argument is an imported identifier.\n const valid2 = $(importedFunction);\n\n // The first argument is an identifier declared at the top level of the same module.\n const valid3 = $(exportedFunction);\n\n // The first argument is an expression without local variables.\n const valid4 = $([1, 2, { a: 'hello' }]);\n\n // The first argument is a function that captures a local variable.\n const localVariable = 1;\n const valid5 = $((event) => {\n console.log('local variable', localVariable);\n });\n});\n```\n\nHere are some examples of invalid `$` functions.\n\n```tsx\n// Invalid examples of `$` functions.\nimport { $, component$, useSignal } from '@qwik.dev/core';\nimport { importedVariable } from './my-other-module';\n\nexport default component$(() => {\n const unserializable = new CustomClass();\n const localVariable = 1;\n\n // The first argument is a local variable.\n const invalid1 = $(localVariable);\n\n // The first argument is a function that captures an unserializable local variable.\n const invalid2 = $((event) => {\n console.log('custom class', unserializable);\n });\n\n // The first argument is an expression that uses a local variable.\n const invalid3 = $(localVariable + 1);\n\n // The first argument is an expression that uses an imported variable.\n const invalid4 = $(importedVariable + 'hello');\n});\n```\n\n## Reactive state\n\n### `useSignal(initialValue?)`\n\n`useSignal()` is the main way to create reactive state. Signals can be shared across components, and any component or task that reads the signal (executing: `signal.value`) will be rendered when the signal changes.\n\n```ts\n// Typescript definition for `Signal<T>` and `useSignal<T>`\n\nexport interface Signal<T> {\n value: T;\n}\n\nexport const useSignal: <T>(value?: T | (() => T)): Signal<T>;\n```\n\n`useSignal(initialValue?)` takes an optional initial value and returns a `Signal<T>` object. The `Signal<T>` object has a `value` property that can be read and written to. When a component or task accesses the `value` property, it automatically creates a subscription, so when the `value` is changed, every component, task or another computed signals that read the `value` will be re-evaluated.\n\n### `useStore(initialValue?)`\n\n`useStore(initialValue?)` is similar to `useSignal` except that it creates a reactive javascript object, making every property of the object reactive, just like the `value` of a signal. Under the hood, `useStore` is implemented using a `Proxy` object that intercepts all property access, making the property reactive.\n\n```ts\n// Typescript definition `useStore<T>`\n\n// The `Reactive<T>` is a reactive version of the `T` type, every property of `T` behaves like a `Signal<T>`.\nexport interface Reactive<T extends Record<string, any>> extends T {}\n\nexport interface StoreOptions {\n // If `deep` is true, then nested property of the store will be wrapped in a `Signal<T>`.\n deep?: boolean;\n}\nexport const useStore: <T>(value?: T | (() => T), options?: StoreOptions): Reactive<T>;\n```\n\nIn practice, `useSignal` and `useStore` are very similar -- `useSignal(0) === useStore({ value: 0 })` -- but `useSignal` is preferable most of the time. Some use cases for `useStore` are:\n\n- When you need reactivity in an array.\n- When you want a reactive object that you can easily add properties to.\n\n```tsx\nimport { component$, useStore } from '@qwik.dev/core';\n\nexport const Counter = component$(() => {\n // The `useStore` hook is used to create a reactive store.\n const todoList = useStore(\n {\n array: [],\n },\n { deep: true }\n );\n\n // todoList.array is a reactive array, so we can push to it and the component will re-render.\n\n return (\n <>\n <h1>Todo List</h1>\n <ul>\n {todoList.array.map((todo) => (\n <li key={todo.id}>\n <input\n type=\"checkbox\"\n checked={todo.completed}\n onInput$={() => {\n // todoList is a reactive store\n // because we used `deep: true`, the `todo` object is also reactive.\n // so we can change the `completed` property and the component will re-render.\n todo.completed = !todo.completed;\n }}\n />\n {todo.text}\n </li>\n ))}\n </ul>\n </>\n );\n});\n```\n\n### `useTask$(() => { ... })`\n\n`useTask$` is used to create an async task. Tasks are useful to implement side effects, running heavy computation and async code as part of the rendering lifecycle. `useTask$` tasks are executed before the first render, and subsequently whenever a tracked signal or store changes, the task is re-executed.\n\n```tsx\nimport { component$, useSignal, useTask$ } from '@qwik.dev/core';\n\nexport const Counter = component$(() => {\n const page = useSignal(0);\n const listOfUsers = useSignal([]);\n\n // The `useTask$` hook is used to create a task.\n useTask$(() => {\n // The task is executed before the first render.\n console.log('Task executed before first render');\n });\n\n // You can create multiple tasks, and they can be async.\n useTask$(async (taskContext) => {\n // Since we want to re-run the task whenever the `page` changes,\n // we need to track it.\n taskContext.track(() => page.value);\n console.log('Task executed before the first render AND when page changes');\n console.log('Current page:', page.value);\n\n // Tasks can run async code, such as fetching data.\n const res = await fetch(`https://api.randomuser.me/?page=${page.value}`);\n const json = await res.json();\n\n // Assigning to a signal will trigger a re-render.\n listOfUsers.value = json.results;\n });\n\n return (\n <>\n <h1>Page {page.value}</h1>\n <ul>\n {listOfUsers.value.map((user) => (\n <li key={user.login.uuid}>\n {user.name.first} {user.name.last}\n </li>\n ))}\n </ul>\n <button onClick$={() => page.value++}>Next Page</button>\n </>\n );\n});\n```\n\n`useTask$()` will run in the server during SSR, and in the browser if the component is first mounted on the client. Because of that, it's not a good idea to access DOM APIs in a task, since they will not be available on the server. Instead, you should use event handlers or `useVisibleTask$()` to run a task only on the client/browser.\n\n### `useVisibleTask$(() => { ... })`\n\n`useVisibleTask$` is used to create a task that happens right AFTER the component is first mounted in the DOM. It's similar to `useTask$` except that it only runs on the client, and it's executed after the first render. Because it's executed after the render, it's ok to inspect the DOM, or use browser APIs.\n\n```tsx\nimport { component$, useSignal, useVisibleTask$ } from '@qwik.dev/core';\n\nexport const Clock = component$(() => {\n const time = useSignal(0);\n\n // The `useVisibleTask$` hook is used to create a task that runs eagerly on the client.\n useVisibleTask$((taskContext) => {\n // Since this VisibleTask is not tracking any signals, it will only run once.\n\n const interval = setInterval(() => {\n time.value = new Date();\n }, 1000);\n\n // The `cleanup` function is called when the component is unmounted, or when the task is re-run.\n taskContext.cleanup(() => clearInterval(interval));\n });\n\n return (\n <>\n <h1>Clock</h1>\n <h1>Seconds passed: {time.value}</h1>\n </>\n );\n});\n```\n\nSince Qwik does NOT execute any Javascript on the browser before user interaction, `useVisibleTask$()` is the only API that will run eagerly on the client, which is why it's a good place to do things like:\n\n- Access DOM APIs\n- Initialize browser-only libraries\n- Run analytics code\n- Start an animation, or a timer.\n\nNote that `useVisibleTask$()` should not be used to fetch data, because it will not run on the server. Instead, you should use `useTask$()` to fetch data, and then use `useVisibleTask$()` to do things like start an animation. Abusing `useVisibleTask$()` can lead to poor performance.\n\n## Routing\n\nQwik comes with a file-based router, which is similar to Next.js, but with a few differences. The router is based on the file-system, specifically in `src/routes/`. Creating a new `index.tsx` file in a folder under `src/routes/` will create a new route. For example, `src/routes/home/index.tsx` will create a route at `/home/`.\n\n```tsx title=\"src/routes/home/index.tsx\"\n\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return <h1>Home</h1>;\n});\n```\n\nIt is very important to export the component as the default export, otherwise the router will not be able to find it.\n\n### Route Parameters\n\nYou can create dynamic routes by adding a folder with `[param]` in the route path. For example, `src/routes/user/[id]/index.tsx` will create a route at `/user/:id/`. In order to access the route parameter, you can use the `useLocation` hook exported from `@qwik.dev/router`.\n\n```tsx title=\"src/routes/user/[userID]/index.tsx\"\n\nimport { component$ } from '@qwik.dev/core';\nimport { useLocation } from '@qwik.dev/router';\n\nexport default component$(() => {\n const loc = useLocation();\n return (\n <main>\n {loc.isNavigating && <p>Loading...</p>}\n <h1>User: {loc.params.userID}</h1>\n <p>Current URL: {loc.url.href}</p>\n </main>\n );\n});\n```\n\n`useLocation()` returns a reactive `RouteLocation` object, meaning that it will re-render whenever the route changes. The `RouteLocation` object has the following properties:\n\n```tsx\n/**\n * The current route location returned by `useLocation()`.\n */\nexport interface RouteLocation {\n readonly params: Readonly<Record<string, string>>;\n readonly url: URL;\n readonly isNavigating: boolean;\n}\n```\n\n### Linking to other routes\n\nTo link to other routes, you can use the `Link` component exported from `@qwik.dev/router`. The `Link` component takes all the properties of the `<a>` HTMLAnchorElement. The only difference is that it will use the Qwik router to SPA navigate to the route instead of doing a full page navigation.\n\n```tsx title=\"src/routes/index.tsx\"\n\nimport { component$ } from '@qwik.dev/core';\nimport { Link } from '@qwik.dev/router';\n\nexport default component$(() => {\n return (\n <>\n <h1>Home</h1>\n <Link href=\"/about/\">SPA navigate to /about/</Link>\n <a href=\"/about/\">Full page navigate to /about/</a>\n </>\n );\n});\n```\n\n## Fetching / loading data\n\nThe recommended way to load data from the server is to use the `routeLoader$()` function exported from `@qwik.dev/router`. The `routeLoader$()` function is used to create a data loader that will be executed on the server before the route is rendered. The return of `routeLoader$()` must be exported as a named export from the route file, ie, it can only be used in a `index.tsx`, inside of `src/routes/`.\n\n```tsx title=\"src/routes/user/[userID]/index.tsx\"\n\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\n// The `routeLoader$()` function is used to create a data loader that will be executed on the server before the route is rendered.\n// The return of `routeLoader$()` is a custom use hook, which can be used to access the data returned from `routeLoader$()`.\nexport const useUserData = routeLoader$(async (requestContext) => {\n const user = await db.table('users').get(requestContext.params.userID);\n return {\n name: user.name,\n email: user.email,\n };\n});\n\nexport default component$(() => {\n // The `useUserData` hook will return a `Signal` containing the data returned from `routeLoader$()`, which will re-render the component, whenever the navigation changes, and the routeLoader$() is re-run.\n const userData = useUserData();\n return (\n <main>\n <h1>User data</h1>\n <p>User name: {userData.value.name}</p>\n <p>User email: {userData.value.email}</p>\n </main>\n );\n});\n\n// Exported `head` function is used to set the document head for the route.\nexport const head: DocumentHead = ({resolveValue}) => {\n // It can use the `resolveValue()` method to resolve the value from `routeLoader$()`.\n const user = resolveValue(useUserData);\n return {\n title: `User: \"${user.name}\"`,\n meta: [\n {\n name: 'description',\n content: 'User page',\n },\n ],\n };\n};\n```\n\nThe `routeLoader$()` function takes a function that returns a promise. The promise is resolved on the server, and the resolved value is passed to the `useCustomLoader$()` hook. The `useCustomLoader$()` hook is a custom hook that is created by the `routeLoader$()` function. The `useCustomLoader$()` hook returns a `Signal` that contains the resolved value of the promise returned from the `routeLoader$()` function. The `useCustomLoader$()` hook will re-render the component whenever the route changes, and the `routeLoader$()` function is re-run.\n\n## Handle form submissions\n\nQwik provides the `routeAction$()` API exported from `@qwik.dev/router` to handle form requests on the server. `routeAction$()` is only executed on the server when the form is submitted.\n\n```tsx title=\"src/routes/user/[userID]/index.tsx\"\n\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$, Form } from '@qwik.dev/router';\nimport { zod$, z } from '@qwik.dev/utils';\n\n// The `routeAction$()` function is used to create a data loader that will be executed on the server when the form is submitted.\n// The return of `routeAction$()` is a custom use hook, which can be used to access the data returned from `routeAction$()`.\nexport const useUserUpdate = routeAction$(async (data, requestContext) => {\n const user = await db.table('users').get(requestContext.params.userID);\n user.name = data.name;\n user.email = data.email;\n await db.table('users').put(user);\n return {\n user,\n };\n}, zod$({\n name: z.string(),\n email: z.string(),\n}));\n\nexport default component$(() => {\n // The `useUserUpdate` hook will return an `ActionStore<T>` containing the `value` returned from `routeAction$()`, and some other properties, such as `submit()`, which is used to submit the form programmatically, and `isRunning`. All of these properties are reactive, and will re-render the component whenever they change.\n const userData = useUserUpdate();\n // userData.value is the value returned from `routeAction$()`, which is `undefined` before the form is submitted.\n // userData.formData is the form data that was submitted, it is `undefined` before the form is submitted.\n // userData.isRunning is a boolean that is true when the form is being submitted.\n // userData.submit() is a function that can be used to submit the form programmatically.\n // userData.actionPath is the path to the action, which is used to submit the form.\n return (\n <main>\n <h1>User data</h1>\n <Form action={userData}>\n <div>\n <label>User name: <input name=\"name\" defaultValue={userData.formData?.get('name')} /></label>\n </div>\n <div>\n <label>User email: <input name=\"email\" defaultValue={userData.formData?.get('email')} /></label>\n </div>\n <button type=\"submit\">Update</button>\n </Form>\n </main>\n );\n});\n```\n\nThe `routeAction$()` is used on pair with the `Form` component exported from `@qwik.dev/router`. The `Form` component is a wrapper around the native HTML `<form>` element. The `Form` component takes an `ActionStore<T>` as the `action` property. The `ActionStore<T>` is the return value of the `routeAction$()` function.\n\n## Run code only in the browser\n\nSince Qwik executes the same code on the server and in the browser, you cannot use `window` or other browser APIs in your code, because they don't exist when the code is executed on the server.\n\nIf you want to access browser APIs, such as `window`, `document`, `localStorage`, `sessionStorage`, `webgl` etc, you need to check if the code is running in the browser before accessing the browser APIs.\n\n```tsx\nimport { component$, isBrowser, useTask$, useVisibleTask$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const ref = useSignal<Element>();\n\n // useVisibleTask$ will only run in the browser\n useVisibleTask$(() => {\n // No need to check for `isBrowser` before accessing the DOM, because useVisibleTask$ will only run in the browser\n ref.value?.focus();\n document.title = 'Hello world';\n });\n\n // useTask might run on the server, so you need to check for `isBrowser` before accessing the DOM\n useTask$(() => {\n if (isBrowser) {\n // This code will only run in the browser only when the component is first rendered there\n ref.value?.focus();\n document.title = 'Hello world';\n }\n });\n\n return (\n <button\n ref={ref}\n onClick$={() => {\n // All event handlers are only executed in the browser, so it's safe to access the DOM\n ref.value?.focus();\n document.title = 'Hello world';\n }}\n >\n Click me\n </button>\n );\n});\n```\n\n### `useVisibleTask$(() => { ... })`\n\nThis API will declare a VisibleTask that is ensured to run only on the client/browser. It will never run on the server.\n\n### JSX event handlers\n\nJSX handlers such as `onClick$` and `onInput$` are only executed on the client. This is because they are DOM events, since there is no DOM on the server, they will not be executed on the server.\n\n## Run code only on the server\n\nSometimes you need to run code only on the server, such as fetching data or accessing a database. To solve this problem, Qwik provides a few APIs to run code only on the server.\n\n```tsx\nimport { component$, useTask$ } from '@qwik.dev/core';\nimport { server$, routeLoader$ } from '@qwik.dev/router';\nimport { isServer } from '@qwik.dev/core';\n\nexport const useGetProducts = routeLoader$((requestEvent) => {\n // This code will only run on the server\n const db = await openDB(requestEvent.env.get('DB_PRIVATE_KEY'));\n const product = await db.table('products').select();\n return product;\n})\n\nconst encryptOnServer = server$(function(message: string) {\n // `this` is the `requestEvent\n const secretKey = this.env.get('SECRET_KEY');\n const encryptedMessage = encrypt(message, secretKey);\n return encryptedMessage;\n});\n\nexport default component$(() => {\n useTask$(() => {\n if (isServer) {\n // This code will only run on the server only when the component is first rendered in the server\n }\n });\n\n return (\n <>\n <button\n onClick$={server$(() => {\n // This code will only run on the server when the button is clicked\n })}\n >\n Click me\n </button>\n\n <button\n onClick$={() => {\n // This code will call the server function, and wait for the result\n const encrypted = await encryptOnServer('Hello world');\n console.log(encrypted);\n }}\n >\n Click me\n </button>\n </>\n );\n});\n```\n\n### `routeAction$()`\n\nThe `routeAction$()` is a special component that is only executed on the server. It's used to handle form submissions, and other actions. For example, you can use it to add a user to a database, and then redirect to the user profile page.\n\n### `routeLoader$()`\n\nThe `routeLoader$()` is a special component that is only executed on the server. It's used to fetch data, and then render the page. For example, you can use it to fetch data from an API, and then render the page with the data.\n\n### `server$((...args) => { ... })`\n\nThe `server$()` is a special way to declare functions that only run on the server. If called from the client, they will behave like an RPC call, and will be executed on the server. They can take any serializable arguments, and return any serializable value.\n\n### `isServer` & `isBrowser` conditionals\n\nInstead of `if(typeof window !== 'undefined')`, it is recommended to use the `isServer` and `isBrowser` boolean helpers exported from `@qwik.dev/core` to ensure your code only runs in the browser. They contain slightly more robust checks to better detect the browser environment.\n\nHere is the source code for reference:\n\n```tsx\nexport const isBrowser: boolean = /*#__PURE__*/ (() =>\n typeof window !== 'undefined' &&\n typeof HTMLElement !== 'undefined' &&\n !!window.document &&\n String(HTMLElement).includes('[native code]'))();\n\nexport const isServer: boolean = !isBrowser;\n```\n\nHere is how you import these for reference:\n\n```tsx\nimport {isServer, isBrowser} from '@qwik.dev/core';\n\n// inside component$\n\nuseTask$(({ track }) => {\n track(interactionSig) // <-- tracks on the client when a signal has changed.\n\n // server code\n\n if (isServer) return;\n\n // client code here\n});\n\n//\n```\n"},{"id":"/docs/guides/redirects/","title":"Redirects | Guides","description":"Learn how to use redirects in Qwik Router.","url":"https://next.qwik.dev/docs/guides/redirects/","content":"# Redirects\n\nSometimes you want to redirect a user from the current page to another page.\n\nLet's say a user tries to go to a dashboard page but has not logged in yet. We want them to be redirected to a login page so they can be authenticated.\n\n```tsx title=\"src/routes/dashboard.tsx\"\nimport type { RequestEvent } from '@qwik.dev/router';\nimport { checkAuthorization } from '../auth'; // Your authorization code\nimport type { DashboardData } from '../types'; // Your types\n\nexport const onGet = async ({ cookie, redirect }: RequestEvent) => {\n const isAuthorized = checkAuthorization(cookie.get('cookie'));\n\n if (!isAuthorized) {\n // User is not authorized!\n // throw the redirect response to\n // relocate the user to the log-in page\n throw redirect(302, '/login');\n } else {\n // ...\n }\n};\n```\n\nThe `redirect()` function, which was destructured in the RequestHandler function arguments, takes a redirect status code and URL.\n\n```tsx\nthrow redirect(302, '/login');\n```\n\n[Common redirect status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages):\n\n- `301`: Moved Permanently. This and all future requests should be directed to the given URI.\n- `302`: Found. This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.\n- `307`: Temporary Redirect. The server sends this response to direct the client to get the requested resource at another URI with the same method that was used in the prior request. This has the same semantics as the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n- `308`: Permanent Redirect. This means that the resource is now permanently located at another URI, specified by the `Location` HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n\nIf you do not provide a status code, Qwik Router will default to a `302` Found status.\n\nRead more about redirect status codes [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages).\n\n## Managing multiple redirects\n\nIn some cases, you may need to manage multiple redirects based on different conditions. For example, you might want to redirect users from old URLs to new URLs after a site restructure. Additionally, you may want editors in a CMS to manage these redirects as well. Here's one of the ways you can handle multiple redirects in Qwik:\n\n```tsx title=\"src/routes/layout.tsx\"\nimport { type RequestHandler } from \"@qwik.dev/router\";\n\nexport const onGet: RequestHandler = async ({ url, redirect }) => {\n // qwik router request caching ...\n\n // example external data source\n async function fetchRules(): Promise<\n { source: string; destination: string; permanent: boolean }[]\n > {\n // Fetch data from a CMS or API, and add more rules as needed.\n // Filter and map your data to make it easier to handle, as simulated here:\n return [\n { source: \"/old-path\", destination: \"/new-path\", permanent: true },\n {\n source: \"/another-old-path\",\n destination: \"/another-new-path\",\n permanent: false,\n },\n ];\n }\n\n const redirectRules = await fetchRules();\n const redirectUrl = redirectRules.find((rule) => {\n if (url.pathname.endsWith(\"/\")) {\n return rule.source + \"/\" === url.pathname;\n }\n\n return rule.source === url.pathname;\n });\n\n if (redirectUrl) {\n throw redirect(redirectUrl.permanent ? 308 : 307, redirectUrl.destination);\n }\n};\n```\n\nThis code does not include caching mechanisms. Fetching redirect rules from an external source on every request can lead to performance issues. It's recommended to implement caching to improve efficiency.\n\nThe above example demonstrates:\n\n- Layouts: Grabbing data inside a [root layout's onGet handler](https://qwik.dev/docs/routing/#middleware-layouts).\n- URL Matching: When a user requests a URL, the handler checks if it matches any source in the redirect rules.\n- Redirect Execution: If a match is found, it redirects the user to the corresponding destination URL.\n- HTTP Status Codes: Uses status code [308](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308) for permanent redirects and [307](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307) for temporary ones.\n- Content Management Integration: Enables content editors to control redirects through external data sources like a CMS or API.\n"},{"id":"/docs/guides/serialization/","title":"Serialization and Serialization Boundaries | Guides","description":"Learn about serialization and serialization boundaries in Qwik, the process of converting data into a format that can be stored or transmitted.","url":"https://next.qwik.dev/docs/guides/serialization/","content":"# `$` Boundaries\n\n## Rules\n\n- Only serializable data can cross a `$` boundary.\n\n## Serialization Boundary\n\nA serialization boundary occurs whenever you cross a lexical scope of a function that is converted into lazy loadable form. It is always denoted by `$(...)` (or `____$(...)`) See example:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\n\nexport const topLevel = Promise.resolve('nonserializable data');\n\nexport class MyCustomClass {\n val: string;\n\n constructor(val: string) {\n this.val = val;\n }\n}\n\nexport const Greeter = component$(() => {\n // BEGIN component serialization boundary\n\n // Referring to top level symbols that are exported is always allowed.\n console.log(topLevel); // OK\n\n const captureSerializable = 'serializable data';\n const capturePromise = Promise.resolve('Qwik serializes promises');\n // Instances of custom classes are not serializable.\n const captureNonSerializable = new MyCustomClass('non serializable');\n\n return (\n <button\n onClick$={() => {\n // BEGIN onClick serialization boundary\n\n // Referring to top level symbols that are exported is always allowed,\n // even if the value is non-serializable.\n console.log(topLevel); // OK\n\n // Capturing a non-top-level variable is allowed only if:\n // - declared as `const`\n // - is serializable (runtime error)\n console.log(captureSerializable); // OK\n console.log(capturePromise); // OK\n\n // Referring to captureNonSerializable will pass static analysis but\n // will fail at runtime because Qwik does not know how to serialize it.\n console.log(captureNonSerializable); // RUNTIME ERROR\n\n // END onClick serialization boundary\n }}\n >\n click\n </button>\n );\n // END component serialization boundary\n});\n```\n"},{"id":"/docs/guides/static-site-generation/","title":"Static Site Generation (SSG) Overview | Guides","description":"Learn how static site generation (SSG) works in Qwik Router.","url":"https://next.qwik.dev/docs/guides/static-site-generation/","content":"# Static Site Generation (SSG) Overview\n\nStatic Site Generation, or commonly referred to as \"SSG\", is the process of pre-rendering site webpages into static HTML files. The benefit is that when a visitor requests the webpage, the response is a pre-generated HTML file (a static file), and doesn't require the webpage's HTML to \"rebuild\" on the visitor's browser, or dynamically created by your server (more on this later).\n\nAdditionally, due to Qwik's underlying architecture, page performance also benefits by not requiring a Javascript \"hydration\" step, which can significantly lower performance and slow down user interactivity. By pre-rendering static `index.html` files with SSG, and combined with Qwik's [resumability](/docs/concepts/resumable.md), static site generation offers many performance benefits over legacy solutions.\n\n## SSG vs. Server-Side Rendered (SSR)\n\nQwik Router is capable of taking a Qwik application, no matter if it's a \"webapp\" or \"website\", and generate static HTML. Once it's generated as HTML, Qwik is fundamentally able to skip rebuilding the app by using [resumability](/docs/concepts/resumable.md), since the app was already generated as HTML. Both Static Site Generation (SSG) and Server-Side Rendering (SSR) use the same process to generate the HTML. The main difference between the SSG and SSR however, is \"when\" the HTML is generated.\n\nIn a traditional setup, SSG pre-renders each webpage at build-time, while SSR render's each webpage on-demand for each HTTP request. SSG only needs to generate the HTML one time per build, which is great for webpages where multiple visitors should see the same content. In contrast, SSR is great when the webpage may be different for each visitor, and would need to render custom HTML for each individual HTTP request.\n\nFor example, SSG is ideal for a blog or docs site, where all the content should be the same for multiple visitors. While SSR may work fine for a blog, it may be an unnecessary strain for your HTTP servers to render the blog content for every visitor, even though they'd all end up seeing the same HTML.\n\nHowever, an account dashboard would commonly have different content for each signed-in user. In this setup, each user should get their own rendered HTML with their account information, rather than everyone seeing the exact same content. This is where SSR would be preferred.\n\nIdeally, the more you can do with static site generation the better, since that'll have less costs to your servers and faster response times.\n\nWith Qwik Router however, the decision to use SSG or SSR, does not have to be one or the other decision. Instead, your own implementation can choose to have some route paths use SSG, while some other pages use SSR. It's entirely up to you and your requirements.\n\n## Static Site Generation Config\n\nStatic site generation is created from the built in adapter, to create an adapter run:\n\n```shell\npnpm run qwik add static\n```\n\nSelect `Adapter: Static site (.html files)`. Done!\n\n### Changes\n\nRunning the above command will make the following changes to your project:\n\n- A `build.server` script will be automatically added to your `package.json` file.\n- A `adapters/ssg/vite.config.ts` file will be created.\n\nYour build files will be generated into the `dist` folder.\n\nYou can build your static site using:\n\n```shell\npnpm run build.server\n```\n\n### SSG Config\n\nThe `adapters/ssg/vite.config.ts` file also includes the SSG config, which would be custom for each implementation.\n\n#### `origin`\n\nThe URL `origin`, which is a combination of the scheme (protocol) and hostname (domain). For example, `https://qwik.dev` has the protocol `https://` and domain `qwik.dev`. However, the `origin` does _not_ include a `pathname`.\n\nThe `origin` is used to provide a full URL during Static Site Generation (SSG), and to simulate a complete URL rather than just the `pathname`. For example, in order to render a correct canonical tag URL or URLs within the `sitemap.xml`, the `origin` must be provided too.\n\nIf the site also starts with a pathname other than `/`, please use the `base` option in the Vite config options (the `basePathname` option in the Qwik Router config options is deprecated).\n\n#### `outDir`\n\nThe `outDir` is a file system output directory where the static files should be written. In the example above, it's using Node's [fileURLToPath](https://nodejs.org/api/url.html#urlfileurltopathurl) to create an absolute file system path to write the static HTML files to.\n\n#### Re-running SSG\n\nSSG is designed to be run at build time, but it can also be re-run at any time after the initial build. This can be useful when you want to update the static HTML files without having to rebuild the entire application.\n\nTo re-run SSG, you can run the `server/run-ssg.js` script. This script will re-run the SSG process and update the static HTML files in the `dist` folder. (or whatever `outDir` you have configured in your SSG config).\n\n## Dynamic SSG Routes\n\nSo far, we've only discussed how to generate static HTML files for a single route path. However, in most cases, you'll want to generate HTML files for multiple route paths that has dynamic params. For example, a product site may have a route path for each product, such as `/product/:id`. In this case, you'll want to generate HTML files for each product page, which would require generating HTML files for each product ID.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { useLocation, type StaticGenerateHandler } from '@qwik.dev/router';\nimport { loadProductIds } from './load-product-ids';\n\nexport default component$(() => {\n const { params } = useLocation();\n\n return <p>Example: {params.id}</p>;\n});\n\nexport const onStaticGenerate: StaticGenerateHandler = async ({ env }) => {\n // example of loading params for this use case\n // every implementation will be different\n const ids = await loadProductIds({\n apiKey: env.get('API_KEY'),\n });\n\n return {\n params: ids.map((id) => {\n return { id };\n }),\n };\n};\n```\n\nIn the above example, the `onStaticGenerate()` function is loading the product IDs from a `loadProductIds()` function by requesting an API behind an API key retrieved from an environment variable.\nThis function would be custom for each implementation, but the general idea is that you'll need to load the data for each product ID, and then generate HTML files for each product ID.\n\nThe `onStaticGenerate` function should be exported from the top-level of the module, and should return an object with a `params` property. The `params` property should be an array of objects, where each object is a set of params for the route path. For example, if the route path is `/product/:id`, then the `params` array should be an array of objects with an `id` property.\n\nThe directory structure for this example would be:\n\n```bash\nsrc/\n`-- routes/\n `-- product/\n `-- [id]/\n `-- index.tsx\n```\n\nNotice that the `index.tsx` file is inside a directory named `[id]`. This is a special directory name that tells Qwik Router to generate HTML files for each `id` param. The `index.tsx` file is the default file that Qwik Router will use when generating HTML files for a route path.\n"},{"id":"/docs/html-attributes/","title":"HTML attributes | Qwik Router","description":"Learn how to add attributes to the html tag, in order to add \"lang\" or other custom attributes.","url":"https://next.qwik.dev/docs/html-attributes/","content":"# HTML attributes\n\nOccasionally, it is necessary to add attributes to a website to enable specific functionalities, such as controlling the application's theme, determining text direction with the `dir` attribute, or setting the page language with the `lang` attribute. Typically, adding these attributes to the HTML tag is practical since it generally serves as the application's container.\n\nTo apply these attributes in Qwik router, add them to `containerAttributes` in the `src/entry.ssr.tsx` file:\n\n```tsx\nexport default function (opts: RenderToStreamOptions) {\n return renderToStream(<Root />, {\n manifest,\n ...opts,\n // Use container attributes to set attributes on the html tag.\n containerAttributes: {\n lang: \"en-us\",\n ...opts.containerAttributes,\n },\n });\n}\n```\n\nIn addition, the `opts.serverData` object and nested objects allow you to access information about the request, including `request headers`, `url`, `route params`, and more. Leveraging this information enables you to do the following:\n\n```tsx\nexport default function (opts: RenderToStreamOptions) {\n // With this route structure src/routes/[locale]/post/[id]/index.tsx\n const isRTL = opts.serverData?.qwikrouter.params.locale === 'ar';\n\n return renderToStream(<Root />, {\n manifest,\n ...opts,\n containerAttributes: {\n dir: isRTL ? 'rtl' : 'ltr'\n ...opts.containerAttributes,\n },\n });\n}\n```\n"},{"id":"/docs/layout/","title":"Layout & Middleware | Guides","description":"","url":"https://next.qwik.dev/docs/layout/","content":"# Nested Layouts\n\nLayouts provide **nested UI and request handling (middleware)** to a set of routes:\n\n- **Shared request handling**: Accomplished by adding an `onRequest` method.\n- **Shared UI**: Accomplished by `export default` a Qwik component.\n\n## Example\n\nNow, combine all the previously discussed concepts to build a full app.\n\nIn the proposed example, you will notice a site with 2 pages: `https://example.com` and `https://example.com/about`. The goal is to add a common header and footer to all the pages, the only difference between the pages is the content in the middle.\n\n```\n┌---------------------------------------------------┐\n| Header |\n|---------┬-----------------------------------------┤\n| Menu | <ROUTE_SPECIFIC_CONTENT> |\n| - home | |\n| - about | |\n| | |\n|---------┴-----------------------------------------┤\n| Footer |\n`---------------------------------------------------┘\n```\n\nFirst, create three components: `<Header>`, `<Footer>`, and `<Menu>`.\n\nThe developer could copy-paste these components manually into each page component, but that is repetitive and error-prone. Instead, use layouts to automatically reuse common parts.\n\n### Routes directory\n\n```bash\nsrc/\n|-- components/\n| |-- header.tsx # Header component implementation\n| |-- footer.tsx # Footer component implementation\n| `-- menu.tsx # Menu component implementation\n`-- routes/\n |-- layout.tsx # Layout implementation using: <Header>, <Footer>, and <Menu>\n |-- about/\n | `-- index.tsx # https://example.com/about\n `-- index.tsx # https://example.com\n```\n\n### `src/routes/layout.tsx`\n\nIt will be used for all routes under the `src/routes` directory. It will render the `Header`, `Menu`, and `Footer` components, and also render the nested routes under the `Slot` component.\n\n```tsx title=\"src/routes/layout.tsx\"\nimport { component$, Slot } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <>\n <Header />\n <Menu />\n <Slot /> {/* <== This is where the route will be inserted */}\n <Footer />\n </>\n );\n});\n```\n\n### `src/routes/index.tsx`\n\nThis is the main route for the site. It will be rendered within the `Slot` component in the `src/routes/layout.tsx` file. Even though the `Header`, `Menu`, or `Footer` components are not referenced, it will still be rendered with them.\n\n```tsx title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return <>Home</>;\n});\n```\n\n### `src/routes/about/index.tsx`\n\nSimilar to the `src/routes/index.tsx` file, the `about` route will also be rendered within the `Slot` component in the `src/routes/layout.tsx` file. Even though the `Header`, `Menu`, or `Footer` components are not referenced, it will still be rendered with them.\n\n```tsx title=\"src/routes/about/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return <>About</>;\n});\n```\n\nWhen you run the app, Qwik will render the `About` nested inside the `RootLayout`\n\n```tsx\n<RootLayout>\n <AboutPage />\n</RootLayout>\n```\n\n[Here](https://qwik.dev/docs/advanced/routing/#named-layout) you can read more about advanced routing scenarios like named layout.\n\n## Named Slots in Layouts\n\nA layout can define multiple named [`<Slot />`](/docs/components/slots/) areas (for example a sidebar, a breadcrumb bar, or a secondary action bar). Because the Qwik Router passes each page as a single component to its parent layout, using named slots requires a special technique: the page's `default export` must be an **inline component** (a plain function) instead of a `component$`.\n\n### Why inline components?\n\nWhen the router composes layouts and pages it builds a tree like:\n\n```tsx\n<Layout>\n <Page /> {/* single component$ — creates a component boundary */}\n</Layout>\n```\n\nQwik's slot system splits the children of a component by their `q:slot` attribute *before* rendering. For a `component$` child the boundary is opaque, so `q:slot` attributes inside the page's output are invisible to the layout. An **inline component** (a plain function) has no such boundary — Qwik calls it directly and its returned JSX elements are visible to the layout's slot system.\n\n### Example\n\n**Layout with named slots:**\n\n```tsx title=\"src/routes/layout.tsx\"\nimport { component$, Slot } from '@builder.io/qwik';\n\nexport default component$(() => {\n return (\n <div class=\"layout\">\n <nav>\n <Slot name=\"breadcrumb\" />\n </nav>\n <main>\n <Slot /> {/* default slot — receives the page body */}\n </main>\n <aside>\n <Slot name=\"sidebar\" />\n </aside>\n </div>\n );\n});\n```\n\n**Page that fills named slots (inline component as default export):**\n\n```tsx title=\"src/routes/index.tsx\"\n// Inline component — NOT component$, so no component boundary is created.\n// Qwik calls this function directly and its JSX output is split across\n// the layout's named slots based on the q:slot attributes.\nexport default () => (\n <>\n <nav q:slot=\"breadcrumb\">Home / Products</nav>\n <aside q:slot=\"sidebar\">\n <p>Filter by category</p>\n </aside>\n <div>\n <h1>Products</h1>\n <p>Main page content goes here.</p>\n </div>\n </>\n);\n```\n\nElements without a `q:slot` attribute go into the layout's default `<Slot />`, and elements with `q:slot=\"name\"` go into the matching named `<Slot name=\"name\" />`.\n\n### Using hooks inside an inline page\n\nInline components cannot use Qwik hooks (`useSignal`, `useStore`, `useTask$`, etc.) directly. If your page needs reactive state, extract that part into a `component$` and render it inside the inline component:\n\n```tsx title=\"src/routes/index.tsx\"\nimport { component$, useSignal } from '@builder.io/qwik';\n\n// component$ for the part that needs reactive state\nconst ProductList = component$(() => {\n const filter = useSignal('');\n return (\n <div>\n <input bind:value={filter} placeholder=\"Search…\" />\n <p>Showing results for: {filter.value}</p>\n </div>\n );\n});\n\n// Inline component as default export — routes content to the layout slots\nexport default () => (\n <>\n <nav q:slot=\"breadcrumb\">Home / Products</nav>\n <aside q:slot=\"sidebar\">\n <p>Static sidebar content</p>\n </aside>\n <ProductList /> {/* goes into the default slot */}\n </>\n);\n```\n\n> **Note:** The named-slot technique relies on inline components not creating a component boundary. Keep the inline default export as a thin routing shell and put all business logic inside `component$` children.\n\n### Nested layouts with named slots\n\nWhen there are nested layouts (an outer layout wrapping an inner layout wrapping a page), any **intermediate** layout that sits between the outer layout's named slots and the page must also be an inline component. It must render `{children}` directly inside a fragment — **not** wrapped in any HTML element — so that `q:slot` attributes propagate all the way up to the outer layout.\n\n```\nsrc/routes/\n|-- layout.tsx ← outer layout (component$ — defines named slots)\n|-- products/\n| |-- layout.tsx ← inner layout (inline — must pass {children} through a fragment)\n| `-- index.tsx ← page (inline — provides q:slot content)\n```\n\n**Outer layout** (`component$` with named slots — unchanged):\n\n```tsx title=\"src/routes/layout.tsx\"\nimport { component$, Slot } from '@builder.io/qwik';\n\nexport default component$(() => {\n return (\n <div class=\"layout\">\n <nav><Slot name=\"breadcrumb\" /></nav>\n <main><Slot /></main>\n <aside><Slot name=\"sidebar\" /></aside>\n </div>\n );\n});\n```\n\n**Inner layout** (inline component — passes `{children}` top-level in a fragment):\n\n```tsx title=\"src/routes/products/layout.tsx\"\n// Inline component — renders its own content alongside {children} in a fragment.\n// {children} MUST be top-level (not wrapped in any HTML element) so that\n// q:slot attributes from nested pages propagate to the outer layout.\nexport default ({ children }: any) => (\n <>\n {/* contributes to the outer layout's \"breadcrumb\" slot */}\n <nav q:slot=\"breadcrumb\">\n <a href=\"/\">Home</a> / <a href=\"/products\">Products</a>\n </nav>\n {children} {/* top-level — q:slot attributes inside are still visible to outer layout */}\n </>\n);\n```\n\n**Page** (inline component — provides its own named-slot content):\n\n```tsx title=\"src/routes/products/index.tsx\"\nexport default () => (\n <>\n <aside q:slot=\"sidebar\">\n <p>Category filters</p>\n </aside>\n <div>\n <h1>All Products</h1>\n </div>\n </>\n);\n```\n\nWhen the router composes these three layers the outer layout's `splitProjectedChildren` receives a flat list of JSX nodes:\n\n| Element | Source | Goes to |\n|---|---|---|\n| `<nav q:slot=\"breadcrumb\">…` | inner layout | outer `breadcrumb` slot |\n| `<aside q:slot=\"sidebar\">…` | page | outer `sidebar` slot |\n| `<div><h1>…` | page | outer default slot |\n\n**What breaks the propagation:**\n\nIf the inner layout wraps `{children}` in an HTML element, Qwik stops flattening at that element boundary and the inner `q:slot` attributes from the page are no longer visible to the outer layout:\n\n```tsx title=\"src/routes/products/layout.tsx — wrapping children hides q:slot attributes\"\n// WRONG — the <div> wrapper stops q:slot propagation to the outer layout\nexport default ({ children }: any) => (\n <div class=\"product-area\">\n {children} {/* q:slot attributes inside children are hidden from the outer layout */}\n </div>\n)\n```\n\nYou will either need to repeat the Slot structure, or move the wrapper div to the child component.\n"},{"id":"/docs/middleware/","title":"Middleware | Guides","description":"","url":"https://next.qwik.dev/docs/middleware/","content":"# Middleware\n\nQwik Router comes with server middleware that allows you to centralize and chain logic such as authentication, security, caching, redirects, and logging. Middleware can also be used to define endpoints. Endpoints are useful for returning data such as RESTful API, or GraphQL API.\n\nMiddleware consists of a set of functions that are called in a specific order defined by the route. A middleware which returns a response is called an [endpoint](/docs/endpoints.md).\n\n## Middleware Function\n\nMiddleware is defined by exporting a function called `onRequest` (or `onGet`, `onPost`, `onPut`, `onPatch`, and `onDelete`) in the `layout.tsx` or `index.tsx` file inside of `src/routes` folder.\n\nThis example shows a simple `onRequest` middleware function that logs all requests.\n\nFile: `src/routes/layout.tsx`\n```typescript\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onRequest: RequestHandler = async ({next, url}) => {\n console.log('Before request', url);\n await next();\n console.log('After request', url);\n};\n```\nIf you want to intercept a specific HTTP method you can use one of these variations. If you use both `onRequest` and `onGet` for example then both will execute but `onRequest` will execute before `onGet` in the chain.\n```typescript\n// Called only with a specific HTTP method\nexport const onGet: RequestHandler = async (requestEvent) => { ... }\nexport const onPost: RequestHandler = async (requestEvent) => { ... }\nexport const onPut: RequestHandler = async (requestEvent) => { ... }\nexport const onPatch: RequestHandler = async (requestEvent) => { ... }\nexport const onDelete: RequestHandler = async (requestEvent) => { ... }\n```\n\nEach middleware function is passed a [`RequestEvent`](#requestevent) object which allows the middleware to control the response.\n\n## Order of Invocation\n\nThe order of the middleware function chain is determined by their location. Starting from the topmost `layout.tsx` and ending at the `index.tsx` for a given route. (Same resolution logic as the order of layout and route component as defined by the route path.)\n\nFor example, if the request is `/api/greet/` in the following folder structure, the invocation order is as follows:\n\n```bash\nsrc/\n`-- routes/\n |-- layout.tsx # Invocation order: 1 (first)\n `-- api/\n |-- layout.tsx # Invocation order: 2\n `-- greet/\n `-- index.ts # Invocation order: 3 (last)\n```\n\nQwik Router looks into each file in order and checks to see if it has `onRequest` (or `onGet`, `onPost`, `onPut`, `onPatch`, and `onDelete`) exported functions. If found the function gets added into the middleware execution chain in that order.\n\n`routeLoader$` and `routeAction$` are also part of the middleware. They execute after the `on*` functions and before the default exported component.\n\n## Component as an HTML Endpoint\n\nYou can think of component rendering as an implicit HTML endpoint. Therefore if `index.tsx` has a default export component, then the component implicitly becomes an endpoint in the middleware chain. Because component rendering is part of the middleware chain this allows you to intercept component rendering, for example as part of authentication, logging or other cross-cutting concerns.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onRequest: RequestHandler = async ({ redirect }) => {\n if (!isLoggedIn()) {\n throw redirect(308, '/login');\n }\n};\n\nexport default component$(() => {\n return <div>You are logged in.</div>;\n});\n\nfunction isLoggedIn() {\n return true; // Mock login as true\n}\n```\n\n> **Security:** Route and layout middleware protects that route's loaders, actions, endpoints, and\n> rendered page. It does not run for [`server$` requests](/docs/server$.md#middleware-and-server).\n> Authorize each sensitive server function directly or use application-wide `plugin.ts` middleware.\n\n## `RequestEvent`\n\nAll middleware functions are passed a `RequestEvent` object which can be used to control the flow of HTTP response. For example, you can read/write cookies, headers, redirect, produce responses and exit the middleware chain early. Middleware functions are executed in the order as described above, from the topmost `layout.tsx` to the last `index.tsx`.\n\n### `next()`\n\nUse the `next()` function to execute the next middleware function in the chain. This is the default behavior when a middleware function returns normally, without an explicit call to `next()`. One can use the `next()` function to achieve a wrapping behavior around the next middleware function.\n\n```tsx /next()/\nimport { type RequestHandler } from '@qwik.dev/router';\n\n// Generic function `onRequest` is executed first\nexport const onRequest: RequestHandler = async ({ next, sharedMap, json }) => {\n const log: string[] = [];\n sharedMap.set('log', log);\n\n log.push('onRequest start');\n await next(); // Execute next middleware function (onGet)\n log.push('onRequest end');\n\n json(200, log);\n};\n\n// Specific functions such as `onGet` are executed next\nexport const onGet: RequestHandler = async ({ next, sharedMap }) => {\n const log = sharedMap.get('log') as string[];\n\n log.push('onGET start');\n // execute next middleware function\n // (in our case, there are no more middleware functions nor components.)\n await next();\n log.push('onGET end');\n};\n```\n\nIn general, a normal (non-exception) return of a function will execute the next function in the chain. However, throwing an error from the function will stop the execution chain. This is typically used for authentication or authorization and returning a `401` or `403` HTTP status code. Because the `next()` is implicit, it is necessary to `throw` an error to prevent calling the next middleware function in the chain.\n\n```tsx /next()/\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onRequest: RequestHandler = async ({ next, sharedMap, json }) => {\n const log: string[] = [];\n sharedMap.set('log', log);\n\n log.push('onRequest');\n if (isLoggedIn()) {\n // normal behavior call next middleware\n await next();\n } else {\n // If not logged in throw to prevent implicit call to the next middleware.\n throw json(404, log);\n }\n};\n\nexport const onGet: RequestHandler = async ({ sharedMap }) => {\n const log = sharedMap.get('log') as string[];\n log.push('onGET');\n};\n\nfunction isLoggedIn() {\n return false; // always return false as mock example\n}\n```\n\n### `sharedMap`\n\nUse `sharedMap` as a way to share data between middleware functions. The `sharedMap` is scoped to HTTP request. A common use case is to use `sharedMap` to store user details so that it can be used by other middleware functions, `routeLoader$()` or components.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport {\n routeLoader$,\n type RequestHandler,\n type Cookie,\n} from '@qwik.dev/router';\n\ninterface User {\n username: string;\n email: string;\n}\n\nexport const onRequest: RequestHandler = async ({\n sharedMap,\n cookie,\n send,\n}) => {\n const user = loadUserFromCookie(cookie);\n if (user) {\n sharedMap.set('user', user);\n } else {\n throw send(401, 'NOT_AUTHORIZED');\n }\n};\n\nfunction loadUserFromCookie(cookie: Cookie): User | null {\n // this is where you would check cookie for user.\n if (cookie) {\n // just return mock user for this demo.\n return {\n username: `Mock User`,\n email: `mock@users.com`,\n };\n } else {\n return null;\n }\n}\n\nexport const useUser = routeLoader$(({ sharedMap }) => {\n return sharedMap.get('user') as User;\n});\n\nexport default component$(() => {\n const log = useUser();\n return (\n <div>\n {log.value.username} ({log.value.email})\n </div>\n );\n});\n```\n\n### `headers`\n\nUse `headers` to set response headers associated with the current request.\n(For reading request headers see [`request.headers`](#request).) Middleware can manually add response headers to the response, using the `headers` property.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ headers, json }) => {\n headers.set('X-SRF-TOKEN', Math.random().toString(36).replace('0.', ''));\n const obj: Record<string, string> = {};\n headers.forEach((value, key) => (obj[key] = value));\n json(200, obj);\n};\n```\n\n### `cookie`\n\nUse `cookie` to set and retrieve cookie information for a request. Middleware can manually read and set cookies, using the `cookie` function. This might be useful for setting a session cookie, such as a JWT token, or a cookie to track a user.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ cookie, json }) => {\n let count = cookie.get('Qwik.demo.count')?.number() || 0;\n count++;\n cookie.set('Qwik.demo.count', count);\n json(200, { count });\n};\n```\n\n### `method`\n\nReturns current HTTP request method: `GET`, `POST`, `PATCH`, `PUT`, `DELETE`.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onRequest: RequestHandler = async ({ method, json }) => {\n json(200, { method });\n};\n```\n\n### `internalRequest`\n\nReturns `false` for normal page requests. Returns `'loader'` for route loader JSON requests and\n`'action'` for fetch-based action submissions.\n\nCheck `internalRequest` before applying broad middleware rewrites so Qwik Router's internal JSON\nrequests keep their routing behavior.\n\n### `url`\n\nReturns current HTTP request URL. (Use `useLocation()` if you need the current URL in a component. The `url` is meant for middleware functions.)\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ url, json }) => {\n json(200, { url: url.toString() });\n};\n```\n\n### `basePathname`\n\nReturns the current base pathname URL of where the application is mounted. Typically this is `/` but it can be different if the application is mounted in a sub-path. See vite `qwikRouter({root: '/my-sub-path-location'})`.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ basePathname, json }) => {\n json(200, { basePathname });\n};\n```\n\n### `params`\n\nRetrieve the \"params\" of the URL. For example `params.myId` will allow you to retrieve the `myId` from this route definition `/base/[myId]/something`.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ params, json }) => {\n json(200, { params });\n};\n```\n\n### `query`\n\nUse `query` to retrieve the URL query parameters. (This is a shorthand for `url.searchParams`.) It is provided for the middleware functions, and components should use `useLocation()` API.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ query, json }) => {\n const obj: Record<string, string> = {};\n query.forEach((v, k) => (obj[k] = v));\n json(200, obj);\n};\n```\n\n### `parseBody()`\n\nUse `parseBody()` to parse form data submitted to the URL.\n\nThis method will check the request headers for a `Content-Type` header and parse the body accordingly. It supports `application/json`, `application/x-www-form-urlencoded`, and `multipart/form-data` content types.\n\nIf the `Content-Type` header is not set, it will return `null`.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ html }) => {\n html(\n 200,\n `\n <form id=\"myForm\" method=\"POST\">\n <input type=\"text\" name=\"project\" value=\"Qwik\"/>\n <input type=\"text\" name=\"url\" value=\"http://qwik.dev\"/>\n </form>\n <script>myForm.submit()</script>`\n );\n};\n\nexport const onPost: RequestHandler = async ({ parseBody, json }) => {\n json(200, { body: await parseBody() });\n};\n```\n\n### `cacheControl`\n\nConvenience API for setting the cache header.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({\n cacheControl,\n headers,\n json,\n}) => {\n cacheControl({ maxAge: 42, public: true });\n const obj: Record<string, string> = {};\n headers.forEach((value, key) => (obj[key] = value));\n json(200, obj);\n};\n```\n\n### `platform`\n\nDeployment platform (Azure, Bun, Cloudflare, Deno, Google Cloud Run, Netlify, Node.js, Vercel, etc...) specific API.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ platform, json }) => {\n json(200, Object.keys(platform));\n};\n```\n\n### `locale()`\n\nSet or retrieve the current locale.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onRequest: RequestHandler = async ({ locale, request }) => {\n const acceptLanguage = request.headers.get('accept-language');\n const [languages] = acceptLanguage?.split(';') || ['?', '?'];\n const [preferredLanguage] = languages.split(',');\n locale(preferredLanguage);\n};\n\nexport const onGet: RequestHandler = async ({ locale, json }) => {\n json(200, { locale: locale() });\n};\n```\n\n### `status()`\n\nSet the status of the response independently of writing the response, useful for streaming. Endpoints can manually change the HTTP status code of the response, using the `status()` method.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ status, getWritableStream }) => {\n status(200);\n const stream = getWritableStream();\n const writer = stream.getWriter();\n writer.write(new TextEncoder().encode('Hello World!'));\n writer.close();\n};\n```\n\n### `redirect()`\n\nRedirect to a new URL. Notice the importance of throwing to prevent other middleware functions from running. The `redirect()` method will automatically set the `Location` header to the redirect URL.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ redirect, url }) => {\n throw redirect(\n 308,\n new URL('/demo/qwikrouter/middleware/status/', url).toString()\n );\n};\n```\n\n### `error()`\n\nSet an error response.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ error }) => {\n throw error(500, 'ERROR: Demonstration of an error response.');\n};\n```\n\n### `text()`\n\nSend a text-based response. Creating a text endpoint is as simple as calling the `text(status, string)` method. The `text()` method will automatically set the `Content-Type` header to `text/plain; charset=utf-8`.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ text }) => {\n text(200, 'Text based response.');\n};\n```\n\n### `html()`\n\nSend an HTML response.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ html }) => {\n html(\n 200,\n `\n <html>\n <body>\n <h1>HTML response</h1>\n </body>\n </html>`\n );\n};\n```\n\n### `json()`\n\nCreating a JSON endpoint is as simple as calling the `json(status, object)` method. The `json()` method will automatically set the `Content-Type` header to `application/json; charset=utf-8` and JSON stringify the data.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ json }) => {\n json(200, { hello: 'world' });\n};\n```\n\n### `send()`\n\nCreating a raw endpoint is as simple as calling the `send(Response)` method. The `send()` method takes a standard `Response` object, which can be created using the `Response` constructor.\n\n```tsx\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({send}) => {\n const response = new Response('Hello World', {\n status: 200,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n send(response);\n};\n```\n\n### `exit()`\n\nThrow to stop the execution of the middleware functions.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ exit }) => {\n throw exit();\n};\n```\n\n### `env`\n\nRetrieve environmental property in a platform-independent way.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ env, json }) => {\n json(200, {\n USER: env.get('USER'),\n MODE_ENV: env.get('MODE_ENV'),\n PATH: env.get('PATH'),\n SHELL: env.get('SHELL'),\n });\n};\n```\n\n### `getWritableStream()`\n\nSet stream response.\n\n```tsx\nimport type { RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async (requestEvent) => {\n requestEvent.headers.set('content-type','text/event-stream')\n const writableStream = requestEvent.getWritableStream();\n const writer = writableStream.getWriter();\n const encoder = new TextEncoder();\n\n writer.write(encoder.encode('Hello World\\n'));\n await wait(100);\n writer.write(encoder.encode('After 100ms\\n'));\n await wait(100);\n writer.write(encoder.encode('After 200ms\\n'));\n await wait(100);\n writer.write(encoder.encode('END'));\n writer.close();\n};\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n```\n\n### `headerSent`\n\nCheck to see if the header has been set.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ headersSent, json }) => {\n if (!headersSent) {\n json(200, { response: 'default response' });\n }\n};\n\nexport const onRequest: RequestHandler = async ({ status }) => {\n status(200);\n};\n```\n\n### `request`\n\nGet the HTTP request object. Useful for getting hold of the request data such as the headers.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\n\nexport const onGet: RequestHandler = async ({ json, request }) => {\n const obj: Record<string, string> = {};\n request.headers.forEach((v, k) => (obj[k] = v));\n json(200, { headers: obj });\n};\n```\n"},{"id":"/docs/pages/","title":"Pages | Qwik Router","description":"","url":"https://next.qwik.dev/docs/pages/","content":"# Pages\n\nPages are created by adding a new `index.tsx` file in the `src/routes` directory. Pages export a `default` Qwik component, which will be rendered as the content of the page.\n\n```tsx title=\"src/routes/some/path/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\n\n// Notice the default export\nexport default component$(() => {\n return <h1>Hello World!</h1>;\n});\n```\n\nThe only difference between a page and an endpoint is that an endpoint only exports an `onRequest`, `onGet`, `onPost`, `onPut`, `onDelete`, `onPatch`, or `onHead` function, which will be used to handle the incoming request.\n\n## `head` export\n\nEvery page can export a `head` property (or function) that returns a `DocumentHead` object. The `DocumentHead` object is used to resolve the `title` of the page, as well as the `meta`, `links`, `styles` and `scripts`.\n\nThis API allows you to set the title of the page, as well as the meta, open graph, twitter tags and links. This is useful for SEO and social sharing.\n\n```tsx {8} /head/ title=\"src/routes/about/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport type { DocumentHead } from '@qwik.dev/router';\n\nexport default component$(() => {\n return <h1>About page</h1>;\n});\n\nexport const head: DocumentHead = {\n // This will be used to resolve the <title> of the page\n title: 'About page',\n meta: [\n {\n name: 'description',\n content: 'This is the about page',\n },\n // Open graph\n {\n property: 'og:title',\n content: 'About page',\n },\n {\n property: 'og:description',\n content: 'This is the about page',\n },\n ],\n links: [\n {\n rel: 'canonical',\n href: 'https://example.com/about',\n },\n ],\n styles: [\n {\n style: '.error { background-color: red; }',\n },\n ],\n scripts: [\n {\n type: \"application/ld+json\",\n script: JSON.stringify({\n \"@context\": \"https://schema.org\",\n \"@type\": \"ItemList\",\n }),\n },\n ],\n};\n```\n\nThe example above sets the title, as well as some [Open Graph](https://ogp.me/) meta and the [canonical link](https://developers.google.com/search/docs/crawling-indexing/canonicalization).\n\nHTML places the `` tag as the first element within `` (at the very top of the HTML content). The `` section is not something that your route component renders directly because it would break the HTML streaming.\n\nLook into `useDocumentHead()` to read and consume the `DocumentHead` object from within your component; you can also use `<DocumentHeadTags />` to render the tags directly and correctly.\n\n### Dynamic Head\n\nYou can also export a function that returns a `DocumentHead` object, allowing you to programmatically set the `<title>`, `<meta>`, `<link>`, `<style>`, and `<script>` tags.\n\nThis allows you to configure the `<head>` using data from `routeLoader$()` or `routeAction$()`.\n\nWe can use the `resolveValue` method to get the value of a `routeLoader$()` or `routeAction$()` within the `head` function.\n\n```tsx title=\"src/routes/jokes/[jokeId]/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\nimport type { DocumentHead } from '@qwik.dev/router';\n\nexport const useJoke = routeLoader$(async (requestEvent) => {\n // Fetch a joke from a public API\n const jokeId = requestEvent.params.jokeId;\n const response = await fetch(`https://api.chucknorris.io/jokes/${jokeId}`);\n const joke = await response.json();\n return joke;\n});\n\n// Now we can export a function that returns a DocumentHead object\nexport const head: DocumentHead = ({resolveValue, params}) => {\n const joke = resolveValue(useJoke);\n return {\n title: `Joke \"${joke.title}\"`,\n meta: [\n {\n name: 'description',\n content: joke.text,\n },\n {\n name: 'id',\n content: params.jokeId,\n },\n ],\n };\n};\n```\n\n#### A note on ordering and merging\n\nThe `head` exports are merged in an outward-in manner. This means that values from `index.tsx` will override the layout's `head` export, and that in turn will override the root layout's `head` export.\n\nHowever, for dynamic `head()` exports (functions), the ordering is reversed. This allows to always add something to the title, for example, in a layout component.\n\n```ts\nexport const head: DocumentHead = ({ head }) => {\n return {\n title: `MySite - ${head.title}`,\n };\n};\n```\n\nSo first all plain object `head` exports are merged, and then the function `head` exports are called in reverse order.\n\nMerging (both from objects or functions) is done by concatenating arrays, or overriding.\nIf two values in arrays (like `meta` or `links`) have the same `key`, the last specified one wins. This allows you to override specific meta tags.\nOther than that, entries that don't have a `key`, or have a unique `key`, are always included.\n\n### Server-injected Head\n\nYou can also pass `documentHead` to `createRenderer()` as part of the `serverData` option.\n\nThe values passed will be used as the default values for `useDocumentHead()`, before the `head` exports are resolved. So layouts and pages can override the values set here.\n\n```tsx title=\"src/entry.ssr.tsx\" {10}\nimport { createRenderer } from \"@qwik.dev/router\";\nimport Root from \"./root\";\n\nexport default createRenderer((opts) => {\n return {\n app: <Root />,\n options: {\n ...opts,\n serverData: {\n ...opts.serverData,\n documentHead: {\n title: \"My App\",\n },\n },\n }\n});\n```\n\n### Nested Layouts and Head\n\nIn an advanced case, a [layout](/docs/layout.md) may want to modify the document title of an already resolved document head. In the example below, the page component returns the title of `Foo`. The containing layout component can read the value of the page's document head and modify it. In this example, the layout component is adding `MyCompany - ` to the title, so that when rendered, the title will be `MyCompany - Foo`. Every layout in the stack has the opportunity to return a new value.\n\n```bash\n--src/\n `-routes/\n |-index.tsx\n `-layout.tsx\n```\n\n```tsx title=\"src/routes/index.tsx\"\nexport const head: DocumentHead = {\n title: `Foo`,\n};\n```\n\n```tsx title=\"src/routes/layout.tsx\"\nexport const head: DocumentHead = ({ head }) => {\n return {\n title: `MyCompany - ${head.title}`,\n };\n};\n```\n\n### Google Structured Data\n\nThis example integrates [Google Structured Data](https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data)\nwhich helps by providing explicit clues about the meaning of a page to Google.\nIf you want to embed custom JavaScript code, it would be ideal to do it lazily with [Partytown](https://partytown.qwik.dev/).\nSometimes, however, you are forced to load them immediately. The following example illustrates this.\n\n```tsx {8} /head/ title=\"src/routes/about/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport type { DocumentHead } from '@qwik.dev/router';\n\nexport default component$(() => {\n return <h1>About page</h1>;\n});\n\nexport const head: DocumentHead = {\n scripts: [\n {\n props: {\n type: \"application/ld+json\",\n },\n script: JSON.stringify({\n \"@context\": \"https://schema.org\",\n \"@type\": \"ItemList\",\n }),\n },\n ],\n};\n```\nThe example above sets some [Structured Data Markup](https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data?hl=en).\n\nYou need to change `router-head` component to render `head.scripts`.\n\n```tsx {8} /head/ title=\"src\\components\\router-head\\router-head.tsx\"\nimport { component$ } from \"@qwik.dev/core\";\nimport { useDocumentHead, useLocation } from \"@qwik.dev/router\";\n\nexport const RouterHead = component$(() => {\n const head = useDocumentHead();\n const loc = useLocation();\n\n return (\n <>\n <title>{head.title}</title>\n\n {/* add this */}\n {head.scripts.map((s) => (\n <script key={s.key} {...s.props} dangerouslySetInnerHTML={s.script} />\n ))}\n </>\n );\n});\n\n```\n\n## `routeConfig` export\n\nThe `routeConfig` export is a unified alternative to the separate `head`, `eTag`, and `cacheKey` exports. It groups all page-level configuration into a single export and follows the same resolution rules as `head` -- it can be a static object or a function.\n\n```tsx title=\"src/routes/product/[id]/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\nimport type { RouteConfig } from '@qwik.dev/router';\n\nexport const useProduct = routeLoader$(async (requestEvent) => {\n const id = requestEvent.params.id;\n const product = await fetchProduct(id);\n return product;\n});\n\nexport default component$(() => {\n const product = useProduct();\n return <h1>{product.value.name}</h1>;\n});\n\n// Static routeConfig\nexport const routeConfig: RouteConfig = {\n head: {\n title: 'Product Page',\n meta: [{ name: 'description', content: 'View our product' }],\n },\n eTag: 'v1',\n cacheKey: true,\n};\n```\n\n### Dynamic `routeConfig`\n\nLike `head`, you can export a function that receives `DocumentHeadProps` and returns a `RouteConfigValue`:\n\n```tsx title=\"src/routes/product/[id]/index.tsx\"\nimport type { RouteConfig } from '@qwik.dev/router';\n\nexport const routeConfig: RouteConfig = ({ resolveValue }) => {\n const product = resolveValue(useProduct);\n return {\n head: {\n title: product.name,\n meta: [{ name: 'description', content: product.description }],\n },\n eTag: `product-${product.id}-${product.updatedAt}`,\n cacheKey: true,\n };\n};\n```\n\n### Layout-level `routeConfig`\n\nLayouts can also export `routeConfig`. This is useful for defining eTag or cacheKey behavior for an entire subtree of routes:\n\n```tsx title=\"src/routes/blog/layout.tsx\"\nimport type { RouteConfig } from '@qwik.dev/router';\n\nexport const routeConfig: RouteConfig = {\n head: {\n meta: [{ key: 'og:site', property: 'og:site_name', content: 'My Blog' }],\n },\n // All blog pages will use SSR caching by default\n cacheKey: true,\n};\n```\n\nPages under this layout inherit the `cacheKey` unless they override it in their own `routeConfig`.\n\n### Resolution rules\n\n`routeConfig` follows the same resolution rules as `head`:\n\n- **Static objects** are merged outward-in (page values override layout values)\n- **Functions** are executed inner-before-outer (page first, then layouts), receiving the accumulated state in `props.head`\n- For `head`: arrays (`meta`, `links`, etc.) are merged by `key`; `title` is overwritten\n- For `eTag` and `cacheKey`: the last defined value wins (page overrides layout)\n\nWhen a module exports `routeConfig`, the separate `head`, `eTag`, and `cacheKey` exports on that module are ignored. Modules can be mixed -- a layout can use a standalone `head` export while a page uses `routeConfig`.\n\nFor details on `eTag` and `cacheKey`, see [SSR Caching](/docs/caching.md#ssr-caching).\n"},{"id":"/docs/qwikrouter-deprecated-features/","title":"Deprecated Features | Qwik Router","description":"","url":"https://next.qwik.dev/docs/qwikrouter-deprecated-features/","content":"# Deprecated Features for Qwik Router (Formerly \"Qwik City\")\n\nThese features were deprecated in the preparation of Qwik for its stable release.\n\nIf you happened to come across one of them and don't know what its replacement is, we quickly mention them in this table with the link to their new documentation .\n\n#### Deprecated functions and their replacements\n----\n\n| Deprecated | Replacements\n| :-------- | :-------\n| `useEndpoint ` | [routeLoader$](https://qwik.dev/docs/route-loader/#routeloader)\n| `loader$` - `loaderQrl` | [routeLoader$](https://qwik.dev/docs/route-loader/#routeloader)\n| `action$` - `actionQrl` | [routeLoader$](https://qwik.dev/docs/route-loader/#routeloader)\n"},{"id":"/docs/qwikrouter/","title":"Overview | Qwik Router","description":"","url":"https://next.qwik.dev/docs/qwikrouter/","content":"# Qwik Router\n\nWhile Qwik focuses on the Component API, Qwik Router provides APIs that support components with common server-focused features, including the following:\n- [routing](/docs/routing.md): Define your application routes with directory based routing. (Supports both MPA and SPA routing models.)\n- [pages](/docs/pages.md): Render application pages, the main feature of an application.\n- [layouts](/docs/layout.md): Define common shared page layouts to be reused across pages.\n- [loaders](/docs/route-loader.md): Fetch data on the server to be used by the component.\n- [actions](/docs/action.md): Provide a way for the component to request the server to perform an action.\n- [validators](/docs/validator.md): Provide a way for validating actions and loaders.\n- [endpoints](/docs/endpoints.md): A way to define data endpoints for your RESTful API, GraphQL API, JSON, XML or reverse proxy.\n- [middleware](/docs/middleware.md): A centralized way to perform cross-cutting concerns such as authentication, security, caching, redirects, and logging.\n- [server$](/docs/server$.md): A simple way to execute logic on the server.\n- [cache](/docs/caching.md): Control caching of your content.\n- [env variables](/docs/guides/env-variables.md): API to manage reading environment variables, commonly used for keys, in a platform independent way.\n- Supports both Server Side Rendering (SSR) for fully dynamic sites as well as Static Site Generation (SSG) to be hosted on static web servers and CDNs.\n- [`vite`](/docs/advanced/vite.md#qwikrouter) - entry point & configuration for Qwik Router.\n\n**Qwik vs Router**\n\n[**Qwik**](/docs.md): Core framework, stable, primitives, component model.\n\n[**Router**](/docs/routing.md): Opinionated file-based router, middleware, endpoints, and data fetching and update.\n\n**Qwik** (core) and **Qwik Router** solve problems at two layers of abstraction. **Qwik**, focuses on component and state management primitives, while **Qwik Router** brings an **opinionated and performant way to build sites at scale**. We don't want to lock the ecosystem into a single correct way of building sites; in fact, we encourage the community to build alternative solutions on top of **Qwik**.\n\nWhile Qwik Router is full of useful functionality, thanks to Qwik's resumability and JavaScript streaming, there is no additional cost to the end user from Qwik Router. (zero JavaScript).\n\nUse Qwik Router to build an e-commerce website, blog site, or any other website that needs routing, layouts, or data retrieval/updates. Qwik Router is built on Qwik, and therefore Qwik Router sites are resumable and only download the minimal amount of JavaScript with fine-grained lazy loading.\n\n## Getting Started with Qwik Router\n\nVisit [Create an app using the CLI](/docs/getting-started.md#create-an-app-using-the-cli) to see how to create a new Qwik Router starter project. It is as simple as:\n\n```shell\npnpm create qwik@latest\n```\n\n## High Level API Overview\n\nThis table shows which file (`index.tsx` vs `layout.tsx`) the respective feature should be implemented in.\n\n## Partytown\n\nQwik Router also comes pre-integrated with [Partytown](https://partytown.qwik.dev) allowing you to execute your third-party code off the main thread.\n"},{"id":"/docs/re-exporting-loaders/","title":"Cookbook | Re-exporting loaders","description":"","url":"https://next.qwik.dev/docs/re-exporting-loaders/","content":"# Re-exporting loaders\n\n`routeAction$` and `routeLoader$` are typically declared in route boundary files such as layout.tsx, index.tsx and plugin.tsx inside the routesDir directory\n[here is docs](https://qwik.dev/docs/route-loader/).\n\nSometimes you would like to declare them outside of the route boundaries.\nThis may be useful when you want to create reusable logic or a library.\nIn such a case, it is essential that this function is re-exported from within the router boundary otherwise it will not run or throw exception.\n\n## Solution\n\nYou can define `routeAction$` and `routeLoader$` in your custom path and re-export them in your layout.tsx, index.tsx and plugin.tsx files.\n\n### Reusable logic example\n\nLet's imagine we have a `routeLoader$` that checks whether our user is logged in or not.\nIt wouldn't make sense to copy and paste the same code into many parts of our code to make it work.\nAs per good practices, the ideal method is to centralize the logic.\nHere in this example we declare `routeAction$` and `routeLoader$` in a centralized file so we can then reuse it in our files.\n\nExample with `./shared/loaders.ts`\n```tsx\nimport { routeAction$, routeLoader$ } from '@qwik.dev/router';\n\nexport const useCommonRouteAction = routeAction$(async () => {\n // ...\n return { success: true, data: ['Qwik', 'Partytown'] };\n});\n\nexport const useCommonRouteLoader = routeLoader$(async () => {\n // ...\n return ['Mitosis', 'Builder.io'];\n});\n```\n\nNow you can use your common `routeAction$` and `routeLoader$` in paths like this one `./src/routes/index.tsx`.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Form } from '@qwik.dev/router';\nimport { useCommonRouteAction, useCommonRouteLoader } from './shared/loaders';\n\n// As mentioned, here we are re-exporting them\nexport { useCommonRouteAction, useCommonRouteLoader };\n\nexport default component$(() => {\n const commonRouteAction = useCommonRouteAction();\n const commonRouteLoader = useCommonRouteLoader();\n\n return (\n <div class=\"flex justify-around text-xl\">\n <Form action={commonRouteAction}>\n <div class=\"mb-2\">CommonRouteAction</div>\n <div class=\"mb-4\">response:</div>\n <div class=\"text-lg font-bold mb-4\">\n {commonRouteAction.value?.data.join(' ') || ''}\n </div>\n <button type=\"submit\">Submit</button>\n </Form>\n <div>\n <div class=\"mb-2\">CommonRouteLoader</div>\n <div class=\"mb-4\">response:</div>\n <div class=\"text-lg font-bold mb-4\">{commonRouteLoader.value.join(' ')}</div>\n </div>\n </div>\n );\n});\n```\n\n### Preventing issues with <u>indirect</u> `routeLoader$` usage (Third-Party Libraries Example)\n\nIt may happen that we need to integrate third-party libraries over which we have no control over how it works.\nLet's think for example about integrating a payment method into our application.\nWe are provided with a component to integrate into the page, but we have no control over what happens under the hood of this component.\n\nIf these third-party components rely on `routeLoader$` or `routeAction$` functions, we must manually re-export and register those inside\na component that exists within the route boundary. This is necessary so the Qwik optimizer can detect and include them during the build.\n\n**Manual Registration Required Before v2.0**\n\nStarting in Qwik v2.0, manual registration will no longer be needed. However, until then, the optimizer may **miss** `routeLoader$` functions if they’re used inside components that are **conditionally rendered** (e.g., toggled with a signal).\n\nIf you don’t manually register the loader in these cases, you may encounter undefined behavior. <u>Avoid skipping this step</u>.\n\n#### Here is our code:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { ThirdPartyPaymentComponent, useThirdPartyPaymentLoader } from './third-party-library';\n\n// As mentioned, here we are re-exporting the third-party loader\nexport { useThirdPartyPaymentLoader } from './third-party-library';\n\nexport default component$(() => {\n\n // Manually register the loader so the optimizer sees it\n useThirdPartyPaymentLoader()\n\n return (\n <section>\n <ThirdPartyPaymentComponent />\n </section>\n );\n});\n```\n\n#### Here is the library code:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useThirdPartyPaymentLoader = routeLoader$(() => {\n return { name: 'John Doe' };\n});\n\nexport const ThirdPartyPaymentComponent = component$(() => {\n const thirdPartyPaymentLoader = useThirdPartyPaymentLoader();\n return (\n <div\n class={[\n 'w-96 h-56 m-auto rounded-xl relative text-white font-bold shadow-2xl',\n 'transition-transform transform hover:scale-110 bg-gray-600',\n ]}\n >\n <div class=\"w-full px-8 absolute top-8\">\n <div class=\"flex justify-between\">\n <div class=\"\">\n <p>Name</p>\n <p class=\"tracking-widest\">{thirdPartyPaymentLoader.value.name}</p>\n </div>\n\n </div>\n <div class=\"pt-1\">\n <p class=\"font-medium\">Card Number</p>\n <p class=\"tracking-wider\">4642 3489 9867 7632</p>\n </div>\n <div class=\"pt-6 pr-6\">\n <div class=\"flex justify-between text-xs\">\n <div>\n <p class=\"font-medium\">Valid</p>\n <p class=\"tracking-wider\">11/15</p>\n </div>\n <div>\n <p class=\"font-medium\">Expiry</p>\n <p class=\"tracking-wider\">03/25</p>\n </div>\n <div>\n <p class=\"font-medium\">CVV</p>\n <p class=\"tracking-wider\">···</p>\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n});\n```\n"},{"id":"/docs/troubleshooting/","title":"/docs/troubleshooting/","description":"","url":"https://next.qwik.dev/docs/troubleshooting/","content":"\n"},{"id":"/docs/validator/","title":"Validators | Qwik Router","description":"","url":"https://next.qwik.dev/docs/validator/","content":"# Data Validators\n\nData validators in Qwik Router are essential for validating request events and data for actions and loaders. These validations occur on the server-side before the execution of the associated action or loader. Similar to the `zod$()` function, Qwik provides a dedicated `validator$()` function for this purpose.\n\n```tsx {12-22} /validator$/#a\nimport {\n type RequestEvent,\n type RequestEventAction,\n routeAction$,\n validator$,\n} from \"@qwik.dev/router\";\n\nexport const useAction = routeAction$(\n async (data, requestEvent: RequestEventAction) => {\n return { foo: \"bar\" };\n },\n validator$(async (ev: RequestEvent, data) => {\n if (ev.query.get(\"secret\") === \"123\") {\n return { success: true };\n }\n return {\n success: false,\n error: {\n message: \"secret is not correct\",\n },\n };\n }),\n);\n```\n\nWhen submitting a request to a `routeAction()`, the request event and data undergo validation against the defined validator. If the validation fails, the action will place the validation error in the `routeAction.value` property.\n\n```tsx\nexport default component$(() => {\n const action = useAction();\n\n // action value is undefined before submitting\n if (action.value) {\n if (action.value.failed) {\n // action failed if query string has no secret\n action.value satisfies { failed: true; message: string };\n } else {\n action.value satisfies { searchResult: string };\n }\n }\n\n return (\n <button onClick$={() => action.submit({ search: \"foo\" })}>Submit</button>\n );\n});\n```\n\n## Multiple validators\n\nActions and loaders can have multiple validators, which are executed in reverse order. In the following example, validators execute in the order `validator3` -> `validator2` -> `validator1`.\n\n```tsx {9-11}\nconst validator1 = validator$(/*...*/)\nconst validator2 = validator$(/*...*/)\nconst validator3 = validator$(/*...*/)\n\nexport const useAction = routeAction$(\n async (data, requestEvent: RequestEventAction) => {\n return { foo: \"bar\" };\n },\n validator1,\n validator2,\n validator3, // will be executed first\n);\n```\n\nIf `validator3` has a `data` property in its success return object, this data will be passed to the next validator, `validator2`. If you don't want to override the original submitted data, avoid putting the `data` property in the success return object.\n\n```tsx /message: \"hi, I am validator3\"/#a /message: \"hi, I am validator2\"/#b /message: \"hi, I am validator1\"/#c\nexport const useAction = routeAction$(\n async (data, requestEvent: RequestEventAction) => {\n console.log(data); // { message: \"hi, I am validator1\" }\n return { foo: \"bar\" };\n },\n // validator1\n validator$((ev, data) => {\n console.log(data); // { message: \"hi, I am validator2\" }\n return {\n success: true,\n data: {\n message: \"hi, I am validator1\",\n },\n };\n }),\n // validator2\n validator$((ev, data) => {\n console.log(data); // { message: \"hi, I am validator3\" }\n return {\n success: true,\n data: {\n message: \"hi, I am validator2\",\n },\n };\n }),\n // validator3\n validator$((ev, data) => {\n console.log(data); // Your submitted data\n return {\n success: true,\n data: {\n message: \"hi, I am validator3\",\n },\n };\n }),\n);\n```\n\n## Return object\n\nData validators expect specific properties in their return objects.\n\n### Successful validation\n\nThe `success` property must be true for a successful validation.\n\n```ts\ninterface Success {\n success: true;\n data?: any;\n}\n```\n\n### Failed validation\n\n```ts\ninterface Fail {\n success: false;\n error: Record<string, any>;\n status?: number;\n}\n```\n\nValidator behaves like using the `fail()` method in the action or loader when it returns a failed object.\n\n```tsx /status/#a /errorObject/#b\nconst status = 500;\nconst errorObject = { message: \"123\" };\n\nexport const useAction = routeAction$(\n async (_, { fail }) => {\n return fail(status, errorObject);\n },\n validator$(async () => {\n return {\n success: false,\n status,\n errorObject,\n };\n }),\n);\n```\n\n## Use `validator$()` with `zod$()` together in actions\n\nFor actions, the typed data validator `zod$()` should be the second argument of `routeAction$`, followed by other data validators `validator$()`s.\n\n```tsx {5-7}\nexport const useAction = routeAction$(\n async (data, requestEvent: RequestEventAction) => {\n return { foo: \"bar\" };\n },\n zod$(/*...*/),\n validator$(/*...*/),\n validator$(/*...*/),\n);\n```\n"},{"id":"/docs/cookbook/algolia-search/","title":"Cookbook | Algolia Search","description":"","url":"https://next.qwik.dev/docs/cookbook/algolia-search/","content":"# Algolia Search\n\nAlgolia is a search platform that provides a set of features and APIs that make it easy to implement powerful search experiences for users.\nIn fact, out of the box it offers tools and infrastructure to integrate fast and relevant search functionality into our applications.\nThanks to the [Algolia](https://www.algolia.com/) APIs it is very simple to integrate it into your Qwik application.\n\n## Solution\n\nTo start using it you need to create a personal Algolia account and retrieve your API keys, which will be used to interact with Algolia.\n- **Index Name**: An index is where the data used by Algolia is stored. It's the equivalent of a table in a database but optimized for search and discovery operations.\n- **Application ID**: This is your unique application identifier. It's used to identify you when using Algolia's API.\n- **Search-Only API Key**: This is the public API key to use in your frontend code. This key is only usable for search queries and sending data to the Insights API.\n\nSo once you have this information you can define your environment variables by creating or editing the `.env` or `.env.local` file at the root of your project.\n\n```bash title=\".env\"\nVITE_ALGOLIA_INDEX=\nVITE_ALGOLIA_APP_ID=\nVITE_ALGOLIA_SEARCH_KEY=\n```\n\nBelow you can find a working example of a first usable implementation.\nThen obviously you can customize and create your graphical interface.\nMany times it makes sense to have a modal where you show the search and the results, such as the search you find in this Qwik documentation.\nYou can check what Algolia returns via the [official documentation](https://www.algolia.com/doc/).\n\n```tsx\nimport { $, component$, useSignal, useStylesScoped$ } from '@qwik.dev/core';\n\ntype AlgoliaResult = {\n hits: {\n type: string;\n anchor?: string;\n content?: string;\n url: string;\n }[];\n};\n\nexport default component$(() => {\n useStylesScoped$(`\n .search {\n font-size: 100%;\n width: calc(100% - 38px);\n border-radius: 0.5rem;\n border: 1px black solid;\n padding: 1rem;\n color: black;\n outline: none;\n }\n\n .search-button {\n border: none;\n padding: 6px 0px;\n cursor: pointer;\n background-color: transparent;\n position: absolute;\n right: 2.4rem;\n padding: 0.85rem 0.5rem 0.4rem 0.5rem;\n outline: none;\n }\n\n .list {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .list li {\n counter-increment: cardCount;\n display: flex;\n color: white;\n margin-top: 1rem;\n margin-bottom: 1rem;\n max-width: 500px;\n }\n\n .list li::before {\n content: counter(cardCount, decimal-leading-zero);\n background: white;\n color: var(--cardColor);\n font-size: 2em;\n font-weight: 700;\n transform: translateY(calc(-1 * 1rem));\n margin-right: calc(-1 * 1rem);\n z-index: 1;\n display: flex;\n align-items: center;\n padding-inline: 0.5em;\n border: 1px solid black;\n }\n\n .list li .content {\n background-color: var(--cardColor);\n display: grid;\n padding: 0.5em calc(1em + 1.5rem) 0.5em calc(1em + 1rem);\n grid-template-areas:\n \"icon title\"\n \"icon text\";\n gap: 0.25em;\n clip-path: polygon(\n 0 0,\n calc(100% - 1.5rem) 0,\n 100% 50%,\n calc(100% - 1.5rem) 100%,\n calc(100% - 1.5rem) calc(100% + 1rem),\n 0 calc(100% + 1rem)\n );\n }\n\n .list li .content .title {\n grid-area: title;\n font-size: 1.25em;\n }\n\n .list li .content .text {\n grid-area: text;\n color: black;\n }\n `);\n const termSignal = useSignal('');\n const hitsSig = useSignal<AlgoliaResult['hits']>([]);\n\n const onSearch = $(async (query: string) => {\n const algoliaURL = new URL(\n `/1/indexes/${import.meta.env.VITE_ALGOLIA_INDEX}/query`,\n `https://${import.meta.env.VITE_ALGOLIA_APP_ID}-dsn.algolia.net`\n );\n const response = await fetch(algoliaURL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Algolia-Application-Id': import.meta.env.VITE_ALGOLIA_APP_ID!,\n 'X-Algolia-API-Key': import.meta.env.VITE_ALGOLIA_SEARCH_KEY!,\n },\n body: JSON.stringify({ query }),\n });\n const algoliaResult: AlgoliaResult = await response.json();\n hitsSig.value = algoliaResult.hits;\n });\n\n return (\n <div>\n <div style=\"margin: 1rem;\">\n <div style=\"position: relative;\">\n <input\n class=\"search\"\n placeholder=\"Algolia search: type here and press enter\"\n bind:value={termSignal}\n onKeyDown$={(e) => {\n if (e.key === 'Enter') {\n onSearch(termSignal.value);\n }\n }}\n />\n <button\n type=\"submit\"\n class=\"search-button\"\n onClick$={() => onSearch(termSignal.value)}\n >\n\n\n </button>\n </div>\n </div>\n <div class=\"list\">\n {hitsSig.value.map(({ anchor, content, url }, key) => (\n <li\n key={key}\n style={`--cardColor:${key % 2 === 0 ? '#19b6f6' : '#ac7ef4'}`}\n >\n <div class=\"content\">\n <div class=\"title\">\n {(anchor || content || url || '').substring(0, 30)}\n </div>\n <a class=\"text\" href={url}>\n Documentation link\n </a>\n </div>\n </li>\n ))}\n </div>\n </div>\n );\n});\n```\n"},{"id":"/docs/cookbook/combine-request-handlers/","title":"Cookbook | Combine Request Handlers","description":"","url":"https://next.qwik.dev/docs/cookbook/combine-request-handlers/","content":"# Combine Request Handlers\n\n## Problem\n\nIn a Qwik application we often have several request handlers to perform [middleware functions](https://qwik.dev/docs/middleware/).\nIn fact, according to the principle of [single responsibility](https://en.wikipedia.org/wiki/Single_responsibility_principle) middleware functions are developed to perform only one task (e.g. to create a database connection).\nWith these premises, it can be complex to combine multiple request handlers while maintaining the order in which they are called.\nFor example, you have one request handler to connect to a database, and another to load the current user record, the latter depends on the former, so they must be called in order.\n\n## Solution\n\nIf you want to chain multiple request handlers together you can use this utility function.\n\n```tsx\nimport type { RequestHandler } from '@qwik.dev/router';\n\n/**\n * Combines multiple request handlers into a single request handler.\n *\n * The handlers will be called in order:\n *\n * 1. Handler1 before next()\n * 2. Handler2 before next()\n * 3. Handler3 before next()\n * 4. Next()\n * 5. Handler3 after next()\n * 6. Handler2 after next()\n * 7. Handler1 after next()\n *\n * @public\n */\n\nexport const combineRequestHandlers = (...handlers: RequestHandler[]): RequestHandler =>\n async (originalContext) => {\n let lastNext = originalContext.next;\n for (let i = handlers.length - 1; i >= 0; i--) {\n const currentHandler = handlers[i];\n const nextInChain = lastNext;\n lastNext = async () => {\n await currentHandler({ ...originalContext, next: nextInChain });\n };\n }\n\n await lastNext();\n };\n```\n"},{"id":"/docs/cookbook/debouncer/","title":"Cookbook | Debouncer","description":"","url":"https://next.qwik.dev/docs/cookbook/debouncer/","content":"# What is a debouncer and why it's important\n\nA debouncer is a programming pattern used to ensure that time-consuming tasks do not fire too frequently, thereby preventing performance issues or the overwhelming of servers with requests. This is particularly useful in scenarios such as search inputs where you may not want to trigger a search request with every keystroke, but rather after the user has paused typing.\n\nBy implementing a debouncer, you can enhance both user experience and application efficiency. This is achieved by delaying a function's execution until a specified amount of time has elapsed since its last invocation.\n\n## When to use debouncers\n\nDebouncers are best used in situations where you want to limit the frequency of function calls. Common use cases include:\n\n- User input validation: Delaying validation until the user stops typing to avoid unnecessary processing for every keystroke.\n- Search functionality: Waiting until a user finishes typing a search query to begin the search process, reducing the number of search requests sent to the server.\n- Window resizing: Limiting the number of recalculations or adjustments when the browser window is resized.\n\n## How to implement a debouncer in Qwik\n\nThe Qwik framework provides unique capabilities for managing state and effects in a way that is both serializable and efficient. Implementing a debouncer in Qwik involves using Qwik's primitives, such as `useSignal` for state management and `$` for marking functions that can capture state without breaking serialization. Below is a simple debouncer pattern. It behaves similarly to closure-based debouncers that execute a function when the timeout is reached.\n\n```tsx\nexport const useDebouncer = <A extends unknown[], R>(\n fn: QRL<(...args: A) => R>,\n delay: number,\n): QRL<(...args: A) => void> => {\n const timeoutId = useSignal<number>();\n\n return $((...args: A): void => {\n window.clearTimeout(timeoutId.value);\n timeoutId.value = window.setTimeout((): void => {\n void fn(...args);\n }, delay);\n });\n};\n```\n\nThis debouncer takes a function and a delay as arguments. It utilizes `useSignal` to track the `timeoutID`, ensuring compatibility with Qwik's resumability model and its use of [QRL's](https://qwik.dev/docs/advanced/qrl/). The returned function, when called, clears any existing timeout and sets a new one to invoke the provided function after the specified delay.\n\n## How to use the debouncer\n\nThe example below demonstrates using the debouncer in a component to efficiently manage user input. By debouncing the input, the application updates the state only after the user has stopped typing for 1-second, optimizing performance for operations such as API calls or data filtering.\n\n```tsx\nimport { $, useSignal, component$, type QRL } from \"@qwik.dev/core\";\nimport { useDebouncer } from \"~/utils/debouncer\";\n\nexport default component$(() => {\n const debouncedValue = useSignal(\"\");\n\n const debounce = useDebouncer(\n $((value: string) => {\n debouncedValue.value = value;\n }),\n 1000\n );\n\n return (\n <>\n <input\n onInput$={(_, target) => {\n debounce(target.value);\n }}\n />\n <p>{debouncedValue.value}</p>\n </>\n );\n});\n```\n\n## Live Demo\n\nIn the live demo below, `useDebouncer` is used to update the `debouncedValue` signal after a 1-second delay has elapsed since the last keystroke.\n\n## Bonus: `useDebouncer$`\n\nTo save our developers the extra \"wrapping with a $()\" action.\n\nWe can leverage Qwik's `implicit$FirstArg` function to create a `useDebouncer$` function that automatically wraps the provided function with `$()`.\n\nThis is how Qwik actually implements all of its built-in $ hooks.\n\n```tsx\nexport const useDebouncerQrl = <A extends unknown[], R>(\n fn: QRL<(...args: A) => R>,\n delay: number,\n): QRL<(...args: A) => void> => {\n const timeoutId = useSignal<number>();\n\n return $((...args: A): void => {\n window.clearTimeout(timeoutId.value);\n timeoutId.value = window.setTimeout((): void => {\n void fn(...args);\n }, delay);\n });\n};\n\nexport const useDebouncer$ = implicit$FirstArg(useDebouncerQrl);\n```\n\nAnd now we could do:\n\n```tsx\nconst debounce = useDebouncer$(\n (value: string) => {\n debouncedValue.value = value;\n },\n 1000\n);\n```\n\nPretty great, huh? :)\n"},{"id":"/docs/cookbook/detect-img-tag-onload/","title":"Cookbook | Detect img tag onLoad","description":"","url":"https://next.qwik.dev/docs/cookbook/detect-img-tag-onload/","content":"# Detect img tag onLoad even if it's cached\n\nWhen using the onLoad$ property on an \\ tag in a Qwik component, you might encounter an issue where the onLoad$ event doesn't fire when the image is already cached in the browser.\nIn that case the onLoad$ logic is not being triggered.\nThis behavior is observed during normal navigation, but not when browser caching is disabled, indicating the cache's impact on the event.\nThe key point here is to [get hold of a DOM element](https://qwik.dev/docs/core/overview/#getting-hold-of-dom-element) to detect onLoad correctly.\n\n### Basic example\n\n```tsx\nimport { component$, useSignal, useVisibleTask$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const imgRef = useSignal<HTMLImageElement>();\n useVisibleTask$(() => {\n imgRef.value!.decode().then(() => {\n alert('loaded and ready!');\n });\n });\n\n return (\n <section>\n\n </section>\n );\n});\n```\n"},{"id":"/docs/cookbook/drag&drop/","title":"Cookbook | Drag & Drop","description":"","url":"https://next.qwik.dev/docs/cookbook/drag&drop/","content":"# Drag & Drop\n\nBuilding drag-and-drop functionality is a pretty common task in web development. With Qwik, you can easily implement drag-and-drop functionality by using the `onDragStart$`, `onDragOver$`, `onDragLeave$`, and `onDrop$` APIs. You need to have in mind that Qwik processes events asynchronously. This means that some APIs such as `event.preventDefault()`, `e.dataTransfer.getData()` or `e.dataTransfer.setData()` do not work as expected.\n\nTo work around this limitations, Qwik provides a [sync$()](/docs/advanced/sync-events.md) API which allows you to process events synchronously. For preventing the default behavior,\nyou can use the `preventdefault:dragover` and `preventdefault:drop` attributes.\n\n### Basic example\n\n```tsx\nimport { component$, useSignal, sync$, $ } from '@qwik.dev/core';\n\nexport default component$(() => {\n const items1 = useSignal([\n { id: 1, content: 'Phone' },\n { id: 2, content: 'Laptop' },\n { id: 3, content: 'Headphones' },\n ]);\n\n const items2 = useSignal([\n { id: 4, content: 'Watch' },\n { id: 5, content: 'Mouse' },\n { id: 6, content: 'Keyboard' },\n ]);\n\n return (\n <div class=\"flex min-h-screen justify-center gap-8 bg-gray-50 p-8\">\n <div\n class=\"h-[25em] w-80 rounded-xl border-2 border-dashed border-gray-300 bg-white p-6 shadow-xs transition-all duration-300 hover:border-gray-400 [&[data-over]]:border-blue-300 [&[data-over]]:bg-blue-50\"\n preventdefault:dragover\n preventdefault:drop\n onDragOver$={sync$((_: DragEvent, currentTarget: HTMLDivElement) => {\n currentTarget.setAttribute('data-over', 'true');\n })}\n onDragLeave$={sync$((_: DragEvent, currentTarget: HTMLDivElement) => {\n currentTarget.removeAttribute('data-over');\n })}\n onDrop$={[\n sync$((e: DragEvent, currentTarget: HTMLDivElement) => {\n const id = e.dataTransfer?.getData('text');\n currentTarget.dataset.droppedId = id;\n currentTarget.removeAttribute('data-over');\n }),\n $((_, currentTarget) => {\n const id = currentTarget.dataset.droppedId;\n if (id) {\n const itemId = parseInt(id);\n const item = [...items2.value].find((i) => i.id === itemId);\n if (item) {\n items2.value = items2.value.filter((i) => i.id !== itemId);\n items1.value = [...items1.value, item];\n }\n }\n }),\n ]}\n >\n <h3 class=\"mb-4 text-lg font-semibold text-gray-700\">Container 1</h3>\n {items1.value.map((item) => (\n <div\n key={item.id}\n data-id={item.id}\n class=\"min-h-[62px] mb-3 cursor-move select-none rounded-lg border border-gray-200 bg-white p-4 transition-all duration-200 hover:-translate-y-1 hover:shadow-md active:scale-95\"\n draggable\n onDragStart$={sync$(\n (e: DragEvent, currentTarget: HTMLDivElement) => {\n const itemId = currentTarget.getAttribute('data-id');\n if (e.dataTransfer && itemId) {\n e.dataTransfer?.setData('text/plain', itemId);\n }\n }\n )}\n >\n <span class=\"text-lg text-gray-700\">{item.content}</span>\n </div>\n ))}\n </div>\n\n <div\n class=\"h-[25em] w-80 rounded-xl border-2 border-dashed border-gray-300 bg-white p-6 shadow-xs transition-all duration-300 hover:border-gray-400 [&[data-over]]:border-blue-300 [&[data-over]]:bg-blue-50\"\n preventdefault:dragover\n preventdefault:drop\n onDragOver$={sync$((_: DragEvent, currentTarget: HTMLDivElement) => {\n currentTarget.setAttribute('data-over', 'true');\n })}\n onDragLeave$={sync$((_: DragEvent, currentTarget: HTMLDivElement) => {\n currentTarget.removeAttribute('data-over');\n })}\n onDrop$={[\n sync$((e: DragEvent, currentTarget: HTMLDivElement) => {\n const id = e.dataTransfer?.getData('text');\n currentTarget.dataset.droppedId = id;\n currentTarget.removeAttribute('data-over');\n }),\n $((_, currentTarget) => {\n const id = currentTarget.dataset.droppedId;\n if (id) {\n const itemId = parseInt(id);\n const item = [...items1.value].find((i) => i.id === itemId);\n if (item) {\n items1.value = items1.value.filter((i) => i.id !== itemId);\n items2.value = [...items2.value, item];\n }\n }\n }),\n ]}\n >\n <h3 class=\"mb-4 text-lg font-semibold text-gray-700\">Container 2</h3>\n {items2.value.map((item) => (\n <div\n key={item.id}\n data-id={item.id}\n class=\"min-h-[62px] mb-3 cursor-move select-none rounded-lg border border-gray-200 bg-white p-4 transition-all duration-200 hover:-translate-y-1 hover:shadow-md active:scale-95\"\n draggable\n onDragStart$={sync$(\n (e: DragEvent, currentTarget: HTMLDivElement) => {\n const itemId = currentTarget.getAttribute('data-id');\n if (e.dataTransfer && itemId) {\n e.dataTransfer?.setData('text/plain', itemId);\n }\n }\n )}\n >\n <span class=\"text-lg text-gray-700\">{item.content}</span>\n </div>\n ))}\n </div>\n </div>\n );\n});\n```\n\n### Advanced example with sorting\n\n```tsx\nimport { component$, sync$, useSignal, $ } from '@qwik.dev/core';\n\ntype Item = {\n id: number;\n content: string;\n};\n\nexport default component$(() => {\n const items1 = useSignal<Item[]>([\n { id: 1, content: 'Phone' },\n { id: 2, content: 'Laptop' },\n { id: 3, content: 'Headphones' },\n ]);\n\n const items2 = useSignal<Item[]>([\n { id: 4, content: 'Watch' },\n { id: 5, content: 'Mouse' },\n { id: 6, content: 'Keyboard' },\n ]);\n\n return (\n <div class=\"flex min-h-screen justify-center gap-8 bg-gray-50 p-8\">\n <div\n data-dropzone\n class=\"h-[25em] w-80 rounded-xl border-2 border-dashed border-gray-300 bg-white p-6 shadow-xs transition-all duration-300 hover:border-gray-400 [&[data-over]]:border-blue-300 [&[data-over]]:bg-blue-50\"\n preventdefault:dragover\n preventdefault:drop\n onDragOver$={sync$((_: DragEvent, currentTarget: HTMLDivElement) => {\n currentTarget.setAttribute('data-over', 'true');\n })}\n onDragLeave$={sync$((_: DragEvent, currentTarget: HTMLDivElement) => {\n currentTarget.removeAttribute('data-over');\n })}\n onDrop$={[\n sync$((e: DragEvent, currentTarget: HTMLDivElement) => {\n const id = e.dataTransfer?.getData('text/plain');\n currentTarget.dataset.droppedId = id;\n currentTarget.removeAttribute('data-over');\n }),\n $((e, currentTarget) => {\n const draggedElementId = currentTarget.dataset.droppedId;\n const isDropZone = currentTarget.hasAttribute('data-dropzone');\n\n if (draggedElementId) {\n const itemId = parseInt(draggedElementId);\n const item = items2.value.find((i) => i.id === itemId);\n\n if (item && isDropZone) {\n items2.value = items2.value.filter((i) => i.id !== itemId);\n items1.value = [...items1.value, item];\n } else {\n const newItems = [...items1.value];\n const targetId = parseInt(\n (e.target as HTMLDivElement).dataset.id || '0'\n );\n if (targetId === 0) return;\n\n const targetIndex = items1.value.findIndex(\n (i) => i.id === targetId\n );\n const draggedIndex = items1.value.findIndex(\n (i) => i.id === itemId\n );\n\n if (draggedIndex !== -1) {\n // Sorting in the same container\n swapElements(newItems, draggedIndex, targetIndex);\n items1.value = newItems;\n } else {\n // Sorting between containers\n if (!item) return;\n items2.value = items2.value.filter((i) => i.id !== itemId);\n insertElement(newItems, targetIndex, item);\n items1.value = newItems;\n }\n }\n }\n }),\n ]}\n >\n <h3 class=\"mb-4 text-lg font-semibold text-gray-700\">Container 1</h3>\n {items1.value.map((item) => (\n <div\n key={item.id}\n data-id={item.id}\n class=\"min-h-[62px] mb-3 cursor-move select-none rounded-lg border border-gray-200 bg-white p-4 transition-all duration-200 hover:-translate-y-1 hover:shadow-md active:scale-95\"\n draggable\n onDragStart$={sync$(\n (e: DragEvent, currentTarget: HTMLDivElement) => {\n const itemId = currentTarget.getAttribute('data-id');\n if (e.dataTransfer && itemId) {\n e.dataTransfer.setData('text/plain', itemId);\n }\n }\n )}\n >\n <span class=\"text-lg text-gray-700\">{item.content}</span>\n </div>\n ))}\n </div>\n\n <div\n class=\"h-[25em] w-80 rounded-xl border-2 border-dashed border-gray-300 bg-white p-6 shadow-xs transition-all duration-300 hover:border-gray-400 [&[data-over]]:border-blue-300 [&[data-over]]:bg-blue-50\"\n data-dropzone\n preventdefault:dragover\n preventdefault:drop\n onDragOver$={(_: DragEvent, currentTarget: HTMLDivElement) => {\n currentTarget.setAttribute('data-over', 'true');\n }}\n onDragLeave$={[\n sync$((_: DragEvent, currentTarget: HTMLDivElement) => {\n currentTarget.removeAttribute('data-over');\n }),\n ]}\n onDrop$={[\n sync$((e: DragEvent, currentTarget: HTMLDivElement) => {\n const id = e.dataTransfer?.getData('text/plain');\n currentTarget.dataset.droppedId = id;\n currentTarget.removeAttribute('data-over');\n }),\n $((e, currentTarget) => {\n const draggedElementId = currentTarget.dataset.droppedId;\n const isDropZone = currentTarget.hasAttribute('data-dropzone');\n\n if (draggedElementId) {\n const itemId = parseInt(draggedElementId);\n const item = items1.value.find((i) => i.id === itemId);\n\n if (isDropZone && item) {\n items1.value = items1.value.filter((i) => i.id !== itemId);\n items2.value = [...items2.value, item];\n } else {\n const targetId = parseInt(\n (e.target as HTMLDivElement).dataset.id || '0'\n );\n if (targetId === 0) return;\n const newItems = [...items2.value];\n const draggedIndex = items2.value.findIndex(\n (i) => i.id === itemId\n );\n const targetIndex = items2.value.findIndex(\n (i) => i.id === targetId\n );\n if (draggedIndex !== -1) {\n // Sorting in the same container\n swapElements(newItems, targetIndex, draggedIndex);\n items2.value = newItems;\n } else {\n // Sorting between containers\n if (!item) return;\n items1.value = items1.value.filter((i) => i.id !== itemId);\n insertElement(newItems, targetIndex, item);\n items2.value = newItems;\n }\n }\n }\n }),\n ]}\n >\n <h3 class=\"mb-4 text-lg font-semibold text-gray-700\">Container 2</h3>\n {items2.value.map((item) => (\n <div\n key={item.id}\n data-id={item.id}\n class=\"min-h-[62px] mb-3 cursor-move select-none rounded-lg border border-gray-200 bg-white p-4 transition-all duration-200 hover:-translate-y-1 hover:shadow-md active:scale-95\"\n draggable\n onDragStart$={sync$(\n (e: DragEvent, currentTarget: HTMLDivElement) => {\n const itemId = currentTarget.getAttribute('data-id');\n if (e.dataTransfer && itemId) {\n e.dataTransfer.setData('text/plain', itemId);\n }\n }\n )}\n >\n <span class=\"text-lg text-gray-700\">{item.content}</span>\n </div>\n ))}\n </div>\n </div>\n );\n});\n\nfunction swapElements(arr: Item[], index1: number, index2: number) {\n arr[index1] = arr.splice(index2, 1, arr[index1])[0];\n\n return arr;\n}\n\nfunction insertElement(arr: Item[], index: number, item: Item) {\n arr.splice(index, 0, item);\n return arr;\n}\n\n```\n\nYou can find more information about drag-and-drop in the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API).\n"},{"id":"/docs/cookbook/fonts/","title":"Cookbook | Font optimization","description":"","url":"https://next.qwik.dev/docs/cookbook/fonts/","content":"# Fonts\n\nA memorable typeface can be a great way to make your site stand out. However, it's important to be mindful of the performance implications of using custom fonts.\n\nUnlike system fonts, that come pre-installed on a user's machine, custom fonts need to be downloaded.\n\n## FOIT vs. FOUT\n\nWhen a user visits a website, the browser will request the font files from the server. The browser will then use the font files to render the text on the page.\n\nThere are two main strategies:\n\n- Delay text display until the web font is downloaded (**FOIT** - Flash Of Invisible Text).\n- Use a locally installed \"fallback\" font until the web font is ready (**FOUT** - Flash Of Unstyled Text).\n\nBoth methods have drawbacks. FOIT withholds text from the user, while FOUT can cause a disruptive visual experiences. Both cause CLS issues. As long as web fonts need to be downloaded, these issues persist.\n\n### Font Display\n\nLuckily, we can make use of the [font-display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display) property to control how the browser handles font loading. This allows us to strike a balance between the two strategies.\n\nWe suggest playing around with the different loading strategies, as well as how the font display timeline works.\n\nThe two most common values for the `font-display` property are `swap` and `fallback`.\n\n## Google Fonts\n\nGoogle Fonts is a popular open source library, offering over 1500 font families.\n\nWhile they are easy to use, they involve downloading a CSS file and fonts from different domains, causing a noticeable delay and switch in font loading despite using `swap`.\n\nHere's what happens:\n\n1. The browser spots the `<link href=\"https://fonts.googleapis.com/css2\">` tag, which prompts it to request a CSS file.\n2. After analyzing the file, it realizes a web font from https://fonts.gstatic.com is needed, leading to another request.\n\nTo mitigate this, we can **self host** our fonts.\n\n## Self Hosting\n\nRather than using a third-party provider like Google Fonts, we can self-host our fonts. This means we download the font files and serve them from our own domain.\n\nSome benefits include:\n\n- Improved performance\n- More privacy as Google tracks font usage.\n- Self-hosted fonts load offline, useful for PWA's or low connectivity situations.\n\n### Fontsource\n\nSelf-hosting with fontsource is as easy as an npm install. It includes all of the google fonts, as well as [other open source fonts](https://github.com/fontsource/font-files/tree/main/fonts/other), without the hassle of managing the files yourself.\n\nThey also have a [Qwik guide](https://fontsource.org/docs/guides/qwik), on how to add fontsource to your project.\n\n### Manual\n\nSometimes we want to self host a font that is not included in Google fonts, or fontsource.\n\nIf we have a `ttf` or `otf` file, we want to convert it to a `woff` or `woff2` file. To do that, we can use Fontsquirrel's [Webfont Generator Tool](https://www.fontsquirrel.com/tools/webfont-generator).\n\nNext we need to create an `@font-face` rule in our CSS. We want to create a new rule for each font weight and style we want to use.\n\n```css\n@font-face {\n font-display: swap;\n font-family: \"Peace Sans\";\n font-style: normal;\n font-weight: 400;\n src: url(\"../assets/fonts/peace-sans.woff2\") format(\"woff2\");\n}\n```\n\nThe above is an example of an `@font-face` rule for the font \"Peace Sans\" with a font weight of 400, with a relative URL to our font file. We can then use the font in our CSS like so:\n\n```css\nbody {\n font-family: 'Peace Sans', sans-serif;\n}\n```\n\n#### Manually self-hosting Google Fonts\n\nThe [Google Webfonts Helper](https://gwfh.mranftl.com/fonts) is a tool that allows you to download the optimized google fonts.\n\nUnfortunately, this does not include variable fonts. To get around this, you can use the Google Fonts API, and then download the optimized variable font file in Chrome's `network` tab.\n\n### Reducing font size\n\nIf we are not using certain glyphs, we can reduce the font size by using the `unicode-range` property. [Glyphhanger](https://www.npmjs.com/package/glyphhanger) is a tool that allows us to grab a specific subset of a font.\n\nA common scenario, would be using only the latin subset of a font. This can reduce our font file size.\n\n## Fallback fonts\n\nIf you recall an earlier section, we mentioned that we can get CLS issues when our custom fonts load in.\n\nRecently, there has been an effort of \"font matching\", or adjusting typography properties to reduce the CLS impact of custom fonts. Let's take a look at how we can do that.\n\n### Fallback Font Generator\n\n[This tool](https://screenspan.net/fallback) generates a system fallback with special properties. Here's an over-exaggerated [demo](https://screenspan.net/prototypes/fallback-font/) of how it works\n\nYou can use the `size-adjust`, `ascent-override`, and `descent-override` properties to adjust the system fallback font to match the custom font.\n\n### Fontaine\n\n[Fontaine](https://github.com/unjs/fontaine) will automatically adjust the above properties to avoid CLS issues. They provide a vite plugin that you can add in your vite config.\n\n## System Fonts\n\nThe most performant option is system fonts. This is because the user already has the font installed on their machine, and the browser can render the text immediately.\n\nSystem fonts often are often called *\"font stacks\"*, which are a collection of system fonts that are similar enough to each other. If the first font is not available, the browser can use the next one in the stack.\n\nTailwind CSS also provides [utility classes](https://tailwindcss.com/docs/font-family) for common system fonts. [Modern Font Stacks](https://github.com/system-fonts/modern-font-stacks) is an example tool you can use to test out different font stacks, including a [Tailwind CSS plugin](https://github.com/BorisAnthony/mfs-tailwind) from a community member.\n\n## Font UX\n\n### Do not use the `ch` unit for body max-width\n\nIt's recommended to have a max-width of `75ch` or 75 characters so that the user does not have to move their head to read the text, as well as it's easier to follow.\n\nHowever, if we are using a custom font, we should be mindful of the `ch` unit. This is because the `ch` unit is based on the width of the `0` character, which can vary between fonts.\n\nThis can cause some very peculiar layout shifts. We want to set a max-width using `px` or `rem`.\n\n### Use `rem` with the `font-size` property.\n\nDifferent units each have their own [accessibility concerns](https://www.joshwcomeau.com/css/surprising-truth-about-pixels-and-accessibility/). We want to use `rem` with the `font-size` property, as it is based on the root font size. Otherwise, the user's chosen font size will not be respected.\n\n### Line height recommendations\n\nThe browser's default line height is not preferable for reading. With body fonts, we want to have a line height around 1.5. For headings, we want to have a line height around 1.2.\n"},{"id":"/docs/cookbook/glob-import/","title":"Cookbook | Glob Import with import.meta.glob","description":"","url":"https://next.qwik.dev/docs/cookbook/glob-import/","content":"# Glob Import & Dynamic Import\n\nAs you probably know, Qwik takes care of lazy-loading for you in order to make your app performant and scalable by default.\n\nAs a consequence of this automatic optimization, you don't need to and shouldn't use vite's [dynamic imports](https://vitejs.dev/guide/features#dynamic-import) feature as it conflicts with the [optimizer](<../../(qwik)/advanced/optimizer/index.mdx>).\n\nBut there are still some cases where you may need to import a lot of files from a directory and you may not want to type out all the file paths. For that kind of situation, you can use [`import.meta.glob`](https://vitejs.dev/guide/features#glob-import).\n\n## import.meta.glob\n\nThe goal of using `import.meta.glob` is to allow you to create a wrapper component to which you can pass a name prop to chose which component you want to import:\n\n```tsx\n<MetaGlobComponent name=\"file-name\" />\n<MetaGlobComponent name=\"another-file-name\" />\n<MetaGlobComponent name=\"etc.\" />\n```\n\nAs written in the Vite documentation, `import.meta.glob` comes with a few features that allow you to specify how to import your files.\n\nBy default you can simply use pattern matching to specify which files should be imported from which folder:\n\n```tsx\nconst metaGlobComponents: Record<string, any> = await import.meta.glob('/src/components/*');\n```\n\nBut you can also pass in additional options like [`import`](https://vitejs.dev/guide/features#named-imports), [`query`](https://vite.dev/guide/features.html#custom-queries):\n\n```tsx\nconst metaGlobComponents: Record<string, any> = await import.meta.glob('/src/components/*', {\n import: 'default',\n query: '?raw',\n});\n```\n\nDo **not** use `eager: true` when importing Qwik components. This makes Vite combine multiple Qwik outputs together in a way that breaks Qwik.\n\nSince Qwik doesn't support Promises as components, that means you need to `await` their import. To do so, you can simply throw the promise and make sure the result is stored somewhere. Qwik will catch the promise and wait for it to resolve before rendering the component again.\n\nIf you're using inline components or anything else, you can use `eager: true`, and the resulting object can be used as a normal object, keyed by the file path.\n\nAs a workaround for now, you can use the build time `isDev` boolean from `\"@qwik.dev/core\"`:\n\n```tsx\nimport { component$, type Component } from '@qwik.dev/core';\n\nconst metaGlobComponents = import.meta.glob<Component>(\n '/src/routes/demo/cookbook/glob-import/examples/*',\n { import: 'default' }\n);\n\nexport default component$(() => {\n return (\n <div>\n <MetaGlobExample name=\"example1\" />\n <MetaGlobExample name=\"example2\" />\n <MetaGlobExample name=\"example3\" />\n </div>\n );\n});\n\nconst loaded: Record<string, Component> = {};\nexport const MetaGlobExample = component$<{ name: string }>(({ name }) => {\n const Cmp = loaded[name];\n if (!Cmp) {\n const componentPath = `/src/routes/demo/cookbook/glob-import/examples/${name}.tsx`;\n const promise = metaGlobComponents[componentPath]();\n throw promise.then((c) => (loaded[name] = c));\n }\n\n return <Cmp />;\n});\n```\n"},{"id":"/docs/cookbook/","title":"Cookbook | Overview","description":"","url":"https://next.qwik.dev/docs/cookbook/","content":"# Cookbook\n\nA cookbook contains a collection of useful patterns for solving common problems in front-end development.\n\nExamples:\n\n- [Algolia search](./algolia-search/)\n- [Combine Request Handlers](./combine-request-handlers/)\n- [Debouncer](./debouncer/)\n- [Deploy with Node using Docker](./node-docker-deploy/)\n- [Font optimization](./fonts/)\n- [Glob Import with import.meta.glob](./glob-import/)\n- [Media Controller with iOS Support](./mediaController/)\n- [NavLink](./nav-link/)\n- [Portals](./portals/)\n- [Streaming/deferred loaders](./streaming-deferred-loaders)\n- [Theme Management](./theme-management/)\n- [Drag & Drop](./drag&drop/)\n- [View Transition](./view-transition/)\n- [Detect img tag onLoad](./detect-img-tag-onload/)\n"},{"id":"/docs/cookbook/mediaController/","title":"Cookbook | Media Controller with iOS Support","description":"","url":"https://next.qwik.dev/docs/cookbook/mediaController/","content":"# Media Controller\n\nDeveloping for a diverse range of browsers and devices often introduces unique challenges. One of the most notable challenges is ensuring consistent media playback, particularly on Apple's iOS devices.\n\n## iOS Media Playback Restrictions Explained\n\nApple's iOS has established specific rules for audio and video playback to enhance user experience and manage data consumption:\n\n1. **User Experience**: iOS prohibits media from auto-playing to prevent unexpected disturbances. This design choice ensures users aren't unexpectedly disrupted by sudden audio, especially in quiet settings.\n2. **Data Efficiency**: Given that streaming media can be data-intensive, iOS requires users to manually initiate media playback. This design is especially beneficial for users on limited or metered data plans.\n\n## Deciphering the iOS Playback Challenge\n\nAt the heart of the iOS challenge is the system's insistence on user-initiated media playback. For instance, starting a video must result directly from a user action, like a tap. However, asynchronous event handlers, such as `onClick$` (QRL), can create a disconnect between the user's action and the playback command. This often results in iOS blocking playback on the first tap, requiring a second, non-intuitive tap.\n\n## The `playsinline` Attribute\n\nOn iOS devices, especially iPhones, videos automatically play in fullscreen mode unless the `playsinline` attribute is present on the `<video>` tag. This attribute ensures that videos play within their designated container, providing a consistent experience across different devices and platforms. While primarily intended for iOS, including `playsinline` is harmless on other platforms and ensures broader compatibility.\n\n## Crafting a Universal Playback Solution\n\nTo achieve consistent media playback across various browsers and devices, a holistic approach is essential. This guide presents a solution that addresses the nuances of different platforms. To ensure immediate playback upon user interaction, the `.play()` method should be invoked synchronously. This can be accomplished by directly attaching the `click` handler within the `useVisibleTask$` function.\n\nBelow, you'll find a prototype of an audio and video controller, tailored to provide a consistent user experience across multiple platforms.\n\nUniversal media controller code compatible with iOS devices looks like this:\n\n```tsx\nimport {\n component$,\n useSignal,\n useStylesScoped$,\n useVisibleTask$,\n} from '@qwik.dev/core';\nimport { useLocation } from '@qwik.dev/router';\n\nconst AUDIO_SRC =\n 'https://cdn.builder.io/o/assets%2F5b8073f890b043be81574f96cfd1250b%2Fafe011812da146a5b2263196cb25f263?alt=media&token=c017cd87-0598-4af2-8afd-e9b5a3fba078&apiKey=5b8073f890b043be81574f96cfd1250b';\nconst VIDEO_SRC =\n 'https://cdn.builder.io/o/assets%2F5b8073f890b043be81574f96cfd1250b%2F8b210c56974440649a0a78d4a3a0ddc5%2Fcompressed?apiKey=5b8073f890b043be81574f96cfd1250b&token=8b210c56974440649a0a78d4a3a0ddc5&alt=media&optimized=true';\n\nexport default component$(() => {\n const audioElementSignal = useSignal<HTMLAudioElement | undefined>();\n const audioPlayButtonSignal = useSignal<HTMLButtonElement | undefined>();\n const audioIsPlayingSignal = useSignal(false);\n const videoElementSignal = useSignal<HTMLAudioElement | undefined>();\n const videoPlayButtonSignal = useSignal<HTMLButtonElement | undefined>();\n const videoIsPlayingSignal = useSignal(false);\n const playsInlineSignal = useSignal(true);\n const location = useLocation();\n\n const videoPoster =\n location.url.origin + '/sample-media/qwik-koi-poster.jpg';\n\n useStylesScoped$(`\n segment {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n width: 100%;\n padding: 20px;\n color: #1dacf2\n }\n .content {\n width: 60%;\n min-width: 250px;\n }\n button {\n padding: 20px;\n font-weight: bold;\n font-size: 1.2em;\n width: 100%;\n background: #1dacf2;\n color: white;\n }\n .checkbox-container {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .checkbox {\n width: 20px;\n height: 20px;\n margin-right: 8px;\n }\n .video-container {\n position: relative;\n width: 100%;\n height: 0;\n padding-bottom: calc(56.25% + 1px);\n }\n video {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n border: 1px solid gray;\n }\n `);\n\n useVisibleTask$(({ track }) => {\n track(() => audioPlayButtonSignal.value);\n track(() => audioElementSignal.value);\n\n const play = () =>\n audioIsPlayingSignal.value\n ? audioElementSignal.value?.pause()\n : audioElementSignal.value?.play();\n\n audioPlayButtonSignal.value?.removeEventListener('click', play);\n audioPlayButtonSignal.value?.addEventListener('click', play);\n\n return () =>\n audioPlayButtonSignal.value?.removeEventListener('click', play);\n });\n\n useVisibleTask$(({ track }) => {\n track(() => videoPlayButtonSignal.value);\n track(() => videoElementSignal.value);\n\n const play = () =>\n videoIsPlayingSignal.value\n ? videoElementSignal.value?.pause()\n : videoElementSignal.value?.play();\n\n videoPlayButtonSignal.value?.addEventListener('click', play);\n return () =>\n videoPlayButtonSignal.value?.removeEventListener('click', play);\n });\n\n return (\n <segment>\n <div class=\"content\">\n <h1>Media Controller</h1>\n <h3>\n <i>with iOS Support</i>\n </h3>\n <br />\n <div class=\"video-container\">\n <video\n ref={videoElementSignal}\n src={VIDEO_SRC}\n poster={videoPoster}\n playsInline={playsInlineSignal.value}\n onPlay$={() => (videoIsPlayingSignal.value = true)}\n onPause$={() => (videoIsPlayingSignal.value = false)}\n onEnded$={() => (videoIsPlayingSignal.value = false)}\n />\n </div>\n <audio\n ref={audioElementSignal}\n src={AUDIO_SRC}\n onPlay$={() => (audioIsPlayingSignal.value = true)}\n onPause$={() => (audioIsPlayingSignal.value = false)}\n onEnded$={() => (audioIsPlayingSignal.value = false)}\n />\n <br />\n <div class=\"checkbox-container\">\n <input\n type=\"checkbox\"\n id=\"playsInlineCheckbox\"\n class=\"checkbox\"\n checked={playsInlineSignal.value}\n onchange$={() => {\n videoElementSignal.value?.pause();\n playsInlineSignal.value = !playsInlineSignal.value;\n }}\n />\n <label for=\"playsInlineCheckbox\">playsInline (iOS)</label>\n </div>\n\n <br />\n <button ref={videoPlayButtonSignal}>\n {videoIsPlayingSignal.value ? 'Pause' : 'Play'} Video\n </button>\n <br />\n <br />\n <button ref={audioPlayButtonSignal}>\n {audioIsPlayingSignal.value ? 'Pause' : 'Play'} Audio\n </button>\n </div>\n </segment>\n );\n});\n```\n"},{"id":"/docs/cookbook/nav-link/","title":"Cookbook | Navbar link","description":"","url":"https://next.qwik.dev/docs/cookbook/nav-link/","content":"# NavLink Component\n\nIf you want to add `active` state to your links you can use this solution.\nThe NavLink component enhances Qwik `<Link>` component by adding:\n\n- **Active Status**: Apply a class when the link href matches the current URL pathname.\n\nThis allows styling the active state for navigation.\n\n## How it Works\n\nUnder the hood, NavLink uses the `useLocation` hook to get navigation status.\nIt checks if the link href matches the current URL pathname to set activeClass.\nThis allows NavLink to know the active state automatically based on navigation.\n\n```tsx\nimport { Slot, component$ } from '@qwik.dev/core';\nimport { Link, useLocation, type LinkProps } from '@qwik.dev/router';\n\ntype NavLinkProps = LinkProps & { activeClass?: string };\n\nexport const NavLink = component$(\n ({ activeClass, ...props }: NavLinkProps) => {\n const location = useLocation();\n const toPathname = props.href ?? '';\n const locationPathname = location.url.pathname;\n\n const startSlashPosition =\n toPathname !== '/' && toPathname.startsWith('/')\n ? toPathname.length - 1\n : toPathname.length;\n const endSlashPosition =\n toPathname !== '/' && toPathname.endsWith('/')\n ? toPathname.length - 1\n : toPathname.length;\n const isActive =\n locationPathname === toPathname ||\n (locationPathname.endsWith(toPathname) &&\n (locationPathname.charAt(endSlashPosition) === '/' ||\n locationPathname.charAt(startSlashPosition) === '/'));\n\n return (\n <Link\n {...props}\n class={[props.class, isActive && activeClass ? activeClass : \"\"]}\n\n >\n <Slot />\n </Link>\n );\n }\n);\n```\n\n## Usage\n\nYou can use NavLink with the addition of `activeClass` props:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { NavLink } from '..';\n\nexport default component$(() => {\n return (\n <>\n Links\n <div>\n <NavLink href=\"/docs\" activeClass=\"text-green-600\">\n /docs\n </NavLink>\n </div>\n <div>\n <NavLink\n href=\"/demo/cookbook/nav-link/example/\"\n activeClass=\"text-green-600\"\n >\n /demo/cookbook/nav-link/example/\n </NavLink>\n </div>\n </>\n );\n});\n```\n\n## Tailwind\nIf you are using Tailwind CSS make sure to edit your tailwind config file, and add `important=true` to your export, then add `!` before the CSS classes you're using `activeClass=\"!text-green-600\"` to make them important when the link is active.\n"},{"id":"/docs/cookbook/node-docker-deploy/","title":"Cookbook | Deploy with Node using Docker","description":"","url":"https://next.qwik.dev/docs/cookbook/node-docker-deploy/","content":"# Deploy with Node using Docker\n\nThis Dockerfile is used to build a Docker image for our Qwik Node.js application. You can edit it accordingly to use pnpm, npm, yarn or bun, by replacing yarn commands and `yarn.lock` file.\n\nWe are using the official Node.js Alpine image with Node version set to 18.18.2 (a long term support version). You are free to choose some other version based on your needs.\n\nWe then proceed to install dependencies, utilizing Docker caching mechanism by leveraging bind mounts for `package.json` and `yarn.lock` to avoid unnecessary reinstallation of dependencies.\n\nOnce the dependencies are installed, we proceed to build, setting the NODE_ENV and ORIGIN environment variables.\n\nWe finally specify the default command to run our Qwik application with `yarn serve`, exposing the port 3000: Please note that port number should match the one you chose on your entry adapter (e.g.: `src/entry.express.tsx`).\n\n ```docker\n ARG NODE_VERSION=18.18.2\n\n################################################################################\n# Use node image for base image for all stages.\nFROM node:${NODE_VERSION}-alpine as base\n\n# Set working directory for all build stages.\nWORKDIR /usr/src/app\n\n################################################################################\n# Create a stage for installing production dependencies.\nFROM base as deps\n\n# Download dependencies as a separate step to take advantage of Docker's caching.\n# Leverage a cache mount to /root/.yarn to speed up subsequent builds.\n# Leverage bind mounts to package.json and yarn.lock to avoid having to copy them\n# into this layer.\nRUN --mount=type=bind,source=package.json,target=package.json \\\n --mount=type=bind,source=yarn.lock,target=yarn.lock \\\n --mount=type=cache,target=/root/.yarn \\\n yarn install --frozen-lockfile\n\n################################################################################\n# Create a stage for building the application.\nFROM deps as build\n\n# Copy the rest of the source files into the image.\nCOPY . .\n\n# Run the build script.\nRUN yarn run build\n\n################################################################################\n# Create a new stage to run the application with minimal runtime dependencies\n# where the necessary files are copied from the build stage.\nFROM base as final\n\n# Use production node environment by default.\nENV NODE_ENV production\n\n# Pay attention to set the correct origin and port for the application.\n# This is used by the application to determine the origin of requests.\n# If you don't set this, the application will default to http://localhost:3000\n# If you set a wrong origin, the application may not work correctly, for example routeAction$ will not work\nENV ORIGIN https://example.com\n\n# Run the application as a non-root user.\nUSER node\n\n# Copy package.json so that package manager commands can be used.\nCOPY package.json .\n\n# Copy the production dependencies from the deps stage and also\n# the built application from the build stage into the image.\nCOPY --from=deps /usr/src/app/node_modules ./node_modules\nCOPY --from=build /usr/src/app/dist ./dist\nCOPY --from=build /usr/src/app/server ./server\n\n# Expose the port that the application listens on.\nEXPOSE 3000\n\n# Run the application.\nCMD yarn serve\n ```\n\n You can now build your docker image:\n\n ```shell\n docker build -t your-image .\n ```\n\nAnd start a Docker container:\n\n ```shell\ndocker run -dp 127.0.0.1:3000:3000 your-image\n ```\n"},{"id":"/docs/cookbook/portals/","title":"Cookbook | Portals","description":"","url":"https://next.qwik.dev/docs/cookbook/portals/","content":"# Portals\n\nIn front-end development, sometimes we need to display a component (like a modal or tooltip) in a different place from where it was triggered. The issue is that the UI element needs to be rendered in a different part of the DOM tree, and the component that triggers the element needs to have a way to affect the location of rendering.\n\nIn other frameworks, this is often solved by a dedicated API such as [`createPortal()`](https://react.dev/reference/react-dom/createPortal). However such APIs don't work well with server-side rendering and so an alternative approach is needed.\n\nLuckily, there is native behavior that handles this for us, called the [top layer](https://developer.chrome.com/blog/what-is-the-top-layer). It is supported in all major browsers.\n\n## Qwik UI\n\nThe Qwik UI team has done an awesome job of filling in the gaps, and allowing us to use this behavior in production across all browsers.\n\n### Modals\n\nWe use modals when we do not want the user to interact with the rest of the page. The rest of the content is inert, or unable to be interacted with.\n\n[Qwik UI's modal component](https://qwikui.com/docs/headless/modal/) uses the dialog element's [showModal](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal) method, which is well-supported in browsers and automatically handles placing UI outside of the HTML Document.\n\nIt also includes behavior such as focus and scroll locking, alert dialogs, automatic entry and exit animation support, and backdrop animations.\n\n### Popovers\n\nIf the UI element can interact with the rest of the page, then it is not modal.\n\nSome examples of non-modal components are:\n- Popovers\n- Overlays\n- Toasts\n- Tooltips\n- Dropdown menus\n- Selects\n- Comboboxes\n\n[MDN's popover API](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API) replaces the need for portals in non-modal components. Support is also in every major browser.\n\nQwik UI has taken it upon themselves by providing a polyfill with feature parity to the native spec. You can use the Popover API's behavior in production today with [Qwik UI's Popover](https://qwikui.com/docs/headless/popover/) component.\n\nIn the case of components like a select or combobox, Qwik UI also provides the ability to opt-in to \"floating\" behavior. For example, when a listbox anchors to an input element. You can do so by adding `floating={true}` to your Popover component. This will execute a bit of extra javascript needed for floating behavior.\n\nIt is intentionally opt-in, at some point the CSS Anchor API will provide a native solution, and so there should be an easy migration path when that receives more general support.\n\nBecause these solutions are built on top of the native specs, that also means there's less javascript we need to prefetch, and therefore less work that needs to be done!\n\nBoth Qwik UI's popover and modal components can be used regardless of meta-framework or microfrontend, as long as there is support for Qwik.\n"},{"id":"/docs/cookbook/streaming-deferred-loaders/","title":"Cookbook | Streaming/deferred loaders","description":"","url":"https://next.qwik.dev/docs/cookbook/streaming-deferred-loaders/","content":"# Streaming/deferred loaders\n\nWhen you use `routeLoader$` the default behavior is to wait for it to complete before rendering our component(s).\nHowever, there is a way to render the DOM up to the point where `routeLoader$` is used and wait for it to complete.\nBy returning an asynchronous function from our `routeLoader$` we can stream/defer the rendering to provide immediate visual feedback.\n\n```tsx\nimport { Resource, component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\n\nexport const useMyData = routeLoader$(async () => {\n return async () => {\n await delay(4_000);\n return 'MyData ' + Math.random();\n };\n});\n\nconst delay = (timeout: number) => {\n return new Promise((res) => setTimeout(res, timeout));\n};\n\nexport default component$(() => {\n const myData = useMyData();\n return (\n <>\n <div>BEFORE</div>\n <Resource\n value={myData}\n onResolved={(data) => <div>DATA: {data}</div>}\n />\n <div>AFTER</div>\n </>\n );\n});\n```\n"},{"id":"/docs/cookbook/theme-management/","title":"Cookbook | Dark and Light Theme","description":"","url":"https://next.qwik.dev/docs/cookbook/theme-management/","content":"# Theme management\n\nIn modern websites, dark and light theme support creates a better user experience. Users can change the theme according to their preferences or system settings.\n\nThis guide covers theme management with Tailwind CSS, including solutions for Static Site Generation (SSG) and Content Security Policy (CSP) considerations.\n\n## Setup Tailwind CSS\n\nFirst, install Tailwind CSS in your Qwik project:\n\n```shell\npnpm run qwik add tailwind\n```\n\nEnable dark mode in your `global.css`:\n\n```css\n@import \"tailwindcss\";\n\n/* Add the line below to enable dark mode */\n@custom-variant dark (&:where(.dark, .dark *));\n```\n\n## Basic Implementation\n\n### Step 1: Add the theme initialization script\n\nAdd this script to the `<head>` in your `root.tsx` file. This script runs before the page renders, preventing a flash of the wrong theme:\n\n```tsx\n// In root.tsx, inside the <head> tag\n<script\n dangerouslySetInnerHTML={`\n (function() {\n function setTheme(theme) {\n document.documentElement.classList.remove('light', 'dark');\n document.documentElement.classList.add(theme);\n localStorage.setItem('theme', theme);\n }\n const stored = localStorage.getItem('theme');\n if (stored) {\n setTheme(stored);\n } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {\n setTheme('dark');\n } else {\n setTheme('light');\n }\n })();\n `}\n/>\n```\n\n### Step 2: Create the theme toggle component\n\n```tsx\nimport { component$ } from \"@qwik.dev/core\";\n\nexport const ThemeToggle = component$(() => {\n return (\n <button\n type=\"button\"\n aria-label=\"Toggle dark mode\"\n onClick$={() => {\n const isDark = document.documentElement.classList.contains('dark');\n const newTheme = isDark ? 'light' : 'dark';\n document.documentElement.classList.remove('light', 'dark');\n document.documentElement.classList.add(newTheme);\n localStorage.setItem(\"theme\", newTheme);\n }}\n class=\"p-2 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700\"\n >\n {/* Sun icon for dark mode, Moon icon for light mode */}\n\n\n\n\n </button>\n );\n});\n```\n\n## SSG (Static Site Generation) Considerations\n\nWhen using Static Site Generation with adapters like Cloudflare Pages, Netlify, or the static adapter, your pages are pre-rendered at build time. This means:\n\n1. **No server-side request handling** - The `plugin@csp.ts` middleware won't run for static pages\n2. **Theme must be set before first paint** - To avoid the \"flash of wrong theme\" problem\n\n### Why the inline script approach works for SSG\n\nThe inline script in `<head>` executes synchronously before the browser renders any content. This is critical for SSG because:\n\n- `useVisibleTask$` runs **after** the component mounts (too late - causes flicker)\n- `useTask$` runs on the server during SSR, but for SSG the HTML is already static\n- The inline script runs immediately when the HTML is parsed, before any rendering\n\n## Content Security Policy (CSP) Considerations\n\nThe inline script approach using `dangerouslySetInnerHTML` requires CSP configuration. You have two options:\n\n### Option 1: Allow unsafe-inline (simpler, less secure)\n\nFor static sites deployed to platforms like Cloudflare Pages, add a `_headers` file in your `public/` folder:\n\n```\n/*\n Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; frame-ancestors 'none'; object-src 'none'\n```\n\n**Security**\nUsing `'unsafe-inline'` reduces CSP's protection against XSS attacks. CSP is often the last line of defense, and using `'unsafe-inline'` explicitly disables this protection for scripts. For production sites with sensitive data, consider Option 3 (script hashes) instead. You can consider this option if you are building a low-risk static site with no user input such as a portfolio or a blog and you prefer convenience over security.\n\n### Option 2: Use nonces (SSR only)\n\nFor SSR applications, you can use nonces as described in the [CSP documentation](/docs/advanced/content-security-policy.md). Note that nonces **do not work with SSG** because the nonce must be generated per-request.\n\n### Option 3: Use script hashes (advanced)\n\nYou can calculate a SHA-256 hash of your inline script and add it to CSP:\n\n```\nscript-src 'self' 'sha256-YOUR_SCRIPT_HASH_HERE'\n```\n\nGenerate the hash using:\n```shell\necho -n 'your inline script content' | openssl dgst -sha256 -binary | openssl base64\n```\n\n## Troubleshooting\n\n### Theme flickers on page load\n\nIf you see a flash of the wrong theme:\n1. Ensure the inline script is in `<head>`, not `<body>`\n2. Check that the script runs synchronously (no `async` or `defer`)\n3. Verify the script is setting the class on `document.documentElement`\n\n### Toggle button shows wrong state initially\n\nThe basic implementation uses CSS classes (`dark:hidden` and `dark:block`) to show the correct icon based on the theme. This approach avoids the need to sync state with JavaScript. If you need to conditionally render based on theme value (e.g., showing different content), you can use `useVisibleTask$` with `{ strategy: 'document-ready' }` to read the current theme after hydration.\n\n### CSP errors in console\n\nCheck your browser's console for CSP violation messages. You'll need to either:\n- Add `'unsafe-inline'` to `script-src`\n- Calculate and add the script's hash\n- Use nonces (SSR only)\n\n## Related\n\n- [Content Security Policy](/docs/advanced/content-security-policy.md) - For SSR applications using nonces\n- [Static Site Generation](/docs/guides/static-site-generation.md) - SSG configuration\n- [useVisibleTask$](/docs/components/tasks/#usevisibletask) - Client-side tasks\n"},{"id":"/docs/cookbook/view-transition/","title":"Cookbook | View Transition API","description":"","url":"https://next.qwik.dev/docs/cookbook/view-transition/","content":"# View Transition API\n\nView transitions on SPA navigation are opt-in. Enable them by passing `viewTransition` to `QwikRouterProvider`, then run animation with either CSS or WAAPI.\n\n```tsx\n// src/root.tsx\nexport default component$(() => {\n return (\n <QwikRouterProvider viewTransition={true}>{/* ... */}</QwikRouterProvider>\n );\n});\n```\n\n## CSS\n\n```tsx\nexport default component$(({ list }) => {\n return (\n <ul>\n {list.map((item) => (\n // Create a name per item\n <li key={item.id} class=\"item\" style={{ '--view-transition-name': `_${item.id}_` }}>\n ...\n </li>\n ))}\n </ul>\n );\n});\n```\n\n```css\n.item {\n view-transition-name: var(--view-transition-name);\n /* Alias to target all .item with a view-transition-name */\n view-transition-class: animated-item;\n}\n/* Animate when item didn't exist in the previous page */\n::view-transition-new(.animated-item):only-child {\n animation: fade-in 200ms;\n}\n/* Animate when item doesn't exist in the next page */\n::view-transition-old(.animated-item):only-child {\n animation: fade-out 200ms;\n}\n\n/* If view transition type is supported */\n@supports selector(html:active-view-transition-type(type)) {\n /* Remove view transition name when view transition is not \"qwik-navigation\" */\n html:not(:active-view-transition-type(qwik-navigation)) .items {\n view-transition-name: none;\n }\n}\n```\n\nQwik overrides the user agent default `view-transition-name: root` on `:root` and sets `view-transition-name: none`.\n\nIf you want to animate the whole page during SPA navigation, you need to explicitly give the `<html>` element a view transition name.\n\n```css\n/* global.css */\nhtml.transition {\n view-transition-name: root;\n}\n```\n\nThen add the `transition` class to the `<html>` element, so the browser can use `root` as the view transition name for the whole page.\n\n```typescript\n/* entry.ssr.tsx */\ncontainerAttributes: {\n class: \"transition\",\n}\n```\n\nAlternatively, you can also override the default rule globally by using `! important`\n\n```css\n:root {\n view-transition-name: root !important;\n}\n```\n\nSometime we need to have some specific logic before the animation start. In this case you can listen to the `qviewTransition` event.\n\nFor example if you want to only animate visible element:\n\n```tsx\nexport default component$(() => {\n // In this case we need the callback to be sync, else the transition might have already happened\n useOnDocument(\n 'qviewtransition',\n sync$((event: CustomEvent<ViewTransition>) => {\n const transition = event.detail;\n const items = document.querySelectorAll('.item');\n for (const item of items) {\n if (!item.checkVisibility()) continue;\n item.dataset.hasViewTransition = true;\n }\n })\n );\n return (\n <ul>\n {list.map((item) => (\n // Create a name per item\n <li key={item.id} class=\"item\" style={{ '--view-transition-name': `_${item.id}_` }}>\n ...\n </li>\n ))}\n </ul>\n );\n});\n```\n\n```css\n.item[data-has-view-transition='true'] {\n view-transition-name: var(--view-transition-name);\n view-transition-class: animated-item;\n}\n::view-transition-new(.animated-item):only-child {\n animation: fade-in 200ms;\n}\n::view-transition-old(.animated-item):only-child {\n animation: fade-out 200ms;\n}\n\n/* If view transition type is supported */\n@supports selector(html:active-view-transition-type(type)) {\n /* Remove view transition name when view transition is not \"qwik-navigation\" */\n html:not(:active-view-transition-type(qwik-navigation)) .items[data-has-view-transition='true'] {\n view-transition-name: none;\n }\n}\n```\n\n`ViewTransition` interface is available with Typescript >5.6.\n\n## WAAPI\n\nWith Web Animation API you can get more precise, but for that we need to wait for the ::view-transition pseudo-element to exist in the DOM. To achieve that you can wait the `transition.ready` promise.\n\nIn this example we add some delay for each item :\n\n```tsx\nexport default component$(() => {\n // Remove default style on the pseudo-element.\n useStyles$(`\n li {\n view-transition-class: items;\n }\n ::view-transition-old(.items) {\n animation: none;\n }\n `);\n useOnDocument(\n 'qviewtransition',\n $(async (event: CustomEvent<ViewTransition>) => {\n // Get visible item's viewTransitionName (should happen before transition is ready)\n const items = document.querySelectorAll<HTMLElement>('.item');\n const names = Array.from(items)\n .filter((item) => item.checkVisibility())\n .map((item) => item.style.viewTransitionName);\n\n // Wait for ::view-transition pseudo-element to exist\n const transition = event.detail;\n await transition.ready;\n\n // Animate each leaving item\n for (let i = 0; i < names.length; i++) {\n // Note: we animate the <html> element\n document.documentElement.animate(\n {\n opacity: 0,\n transform: 'scale(0.9)',\n },\n {\n // Target the pseudo-element inside the <html> element\n pseudoElement: `::view-transition-old(${names[i]})`,\n duration: 200,\n fill: 'forwards',\n delay: i * 50, // Add delay for each pseudo-element\n }\n );\n }\n })\n );\n return (\n <ul>\n {list.map((item) => (\n // Create a name per item\n <li key={item.id} class=\"item\" style={{ viewTransitionName: `_${item.id}_` }}>\n ...\n </li>\n ))}\n </ul>\n );\n});\n```\n\nWhen listening on the `qviewtransition` we know that\n\nFor it to work correctly, we need to **remove the default view transition** animation else it happens on top of the `.animate()`. I'm using `view-transition-class` which is only working with Chrome right now.\n\n## Root transition\n\nBy default Qwik disables root view transition inside the `@layer qwik`. If you want to enable it you need to reset it :\n\n```css\n:root {\n view-transition-name: root;\n}\n```\n\nor within a `@layer` :\n\n```css\n@layer qwik, reset;\n@layer reset {\n :root {\n view-transition-name: root;\n }\n}\n```\n"},{"id":"/docs/deployments/aws-lambda/","title":"AWS Lambda | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/aws-lambda/","content":"# AWS Adapter\n\nQwik Router AWS Adapter allows you to connect Qwik Router to [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html?icmpid=docs_lambda_hel).\n\n## Installation\n\nTo integrate the `aws-lambda` adapter, use the `add` command:\n\n```shell\npnpm run qwik add aws-lambda\n```\n\nThe adapter will add a new `vite.config.ts` within the `adapters/` directory, and a new entry file will be created, such as:\n\n```shell\n`-- adapters/\n `-- aws-lambda\n `-- vite.config.ts\n`-- src/\n `-- entry_aws-lambda.tsx\n```\n\nAdditionally, within the `package.json`, the `build.server` and `serverless:preview` scripts will be updated.\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n## Deploy to AWS\n\nBefore deployment, you need to set up your [AWS Credentials](https://www.serverless.com/framework/docs/providers/aws/guide/credentials). Under the hood,\nthe adapter uses [serverless](https://www.serverless.com/).\n\n```shell\nserverless deploy\n```\nDone!\n"},{"id":"/docs/deployments/azion/","title":"Azion Web Platform | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/azion/","content":"# Azion Web Platform\n\n[Azion](https://azion.com) is a web platform that allows you to deploy your Qwik applications globally. It provides a fast and secure way to serve your applications with low latency.\n\n## Installation\n\nCurrently, Azion only supports SSG Qwik applications. To deploy your Qwik application to Azion, you need to use the `static-site` adapter.\n\nTo integrate the `static-site` adapter, use the `add` command:\n\n```shell\npnpm run qwik add static\n```\n\nAbove command will create a directory at project root named `adapters/static/vite.config.ts` with the below code.\n\n```ts title=\"adapters/static/vite.config.ts\"\nimport { staticAdapter } from \"@qwik.dev/router/adapters/static/vite\";\nimport { extendConfig } from '@qwik.dev/router/vite';\nimport baseConfig from '../../vite.config';\n\nexport default extendConfig(baseConfig, () => {\n return {\n build: {\n ssr: true,\n },\n plugins: [\n staticAdapter({\n origin: 'https://yoursite.qwik.dev',\n }),\n ],\n };\n});\n```\n\nRemember to change the `origin` in this file to your domain.\n\nNow, you can generate static site while using `Qwik`'s rich ecosystem, file based routing and many more.\n\n## Deploy to Azion\n\nTo deploy your Qwik application to Azion, you need to install the Azion CLI. You can install it by following this [guide](https://www.azion.com/en/documentation/products/azion-cli/overview/#installing-azion-cli).\n\nOnce you have the Azion CLI installed, you can deploy your application by following these steps:\n\n1. Link your application. This will create a new project in Azion and link it to your local application.\n\n```shell\nazion link\n```\n\nConfirm the linking of the project to Azion:\n\n```shell\n? Do you want to link /[your-application-folder] to Azion? (y/N)\n```\n\nEnter the desired name for your **application**:\n\n```shell\n? (Hit enter to accept the suggested name in parenthesis) Your application's name: (nimble-tyrion)\n```\n\nChoose a **preset**, `Qwik` is the option you are looking for:\n\n```shell\n? Choose a preset: [Use arrows to move, type to filter]\n ...\n> Qwik\n ...\n```\n\nNow, the application will be linked to Azion. Different processes occur based on the selected preset, so you need to answer the interactions that are presented.\n\n2. Deploy your application. This will build your application and deploy it to Azion.\n\n```shell\nazion deploy\n```\n\n3. Wait while the project is built and deployed to the Azion Web Platform.\n\nOnce the deployment is triggered, Azion will open the browser and take you to a page on the Azion Console where the deployment logs and process can be monitored. If it doesn't open automatically, just click on the provided link.\n\nAfter the deployment is complete, you'll receive a domain to access your Qwik project on the Azion Platform.\n\nWait a few minutes for propagation to take place, and then access your application using the provided domain, which should be similar to `https://xxxxxxx.map.azionedge.net`.\n\nFor more information about the Azion Platform, check the [Azion documentation](https://www.azion.com/en/documentation/).\n"},{"id":"/docs/deployments/azure-swa/","title":"Azure Static Web Apps | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/azure-swa/","content":"# Azure Static Web Apps Middleware\n\nQwik Router Azure Static Web Apps middleware allows you to connect Qwik Router to [Azure Static Web Apps](https://learn.microsoft.com/azure/static-web-apps/).\n\n## Installation\n\nTo integrate the `azure-swa` adapter, use the `add` command:\n\n```shell\npnpm run qwik add azure-swa\n```\n\nThe adapter will add a new `vite.config.ts` within the `adapters/` directory, and a new entry file will be created, such as:\n\n```shell\n`-- adapters/\n `-- azure-swa/\n `-- vite.config.ts\n`-- src/\n `-- entry.azure-swa.tsx\n```\n\nAdditionally, within the `package.json`, the `build.server` and `deploy` scripts will be updated.\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n## Deploy to Azure\n\nAfter installing the integration the project is ready to be deployed to Azure Static Web Apps.\n\nThere are three ways to deploy:\n\n1. Deploy with [Static Web Apps CLI](https://azure.github.io/static-web-apps-cli/)\n\n You can deploy your application from your local environment with:\n\n ```shell\n pnpm dlx swa deploy\n ```\n\n This will start a wizard which will guide you through login and deployment to Azure.\n\n2. Deploy from GitHub\n\n You can deploy your application via GitHub. Create a Git repository, commit all your code and then publish your branch to GitHub.\n\n Create an Azure Static Webapp via the Azure Portal and choose the GitHub repository in the deployment details. When prompted for the build details choose \"Custom\" and set the following values:\n\n - App location: \".\"\n - Api location: \"./azure-functions\"\n - Output location: \"./dist\"\n\n This setup will establish a GitHub workflow in your repository. With this workflow, your application will automatically deploy whenever changes are pushed or merged into the main branch.\n\n The resulting workflow file has to be adapted by adding the following to the \"Repository/Build Configurations\" block:\n\n ```text /skip_api_build/#b /true/#c\n skip_api_build: true\n ```\n\n Checkout [Azure Static Web Apps quickstart](https://learn.microsoft.com/azure/static-web-apps/get-started-portal?pivots=github) for more information.\n\n3. Deploy from any CI system\n\n You can deploy to Azure Static Web Apps using any CI system. Set your Azure SWA deployment token as the `SWA_CLI_DEPLOYMENT_TOKEN` environment variable. Once that's done, you can run the following command in your pipeline:\n\n ```shell\n swa deploy ./dist --api-location ./azure-functions --env production\n ```\n\nNotice, that you will need an [Azure account](https://signup.azure.com/) in order to complete this step!\n"},{"id":"/docs/deployments/bun/","title":"Bun Middleware | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/bun/","content":"# Bun Middleware\n\nQwik Router Bun middleware allows you to hook up Qwik Router to a Bun server which uses the Bun Http API.\n\n## Installation\n\nTo install `bun` on Linux, OSX or WSL run the following command in your terminal\n\n```shell\ncurl -fsSL https://bun.sh/install | bash\n```\n\nFor other platforms or if you run into issues with installation, up to date `bun` installation instructions can be found [on the bun website](https://bun.sh/docs/installation).\n\nTo integrate the `bun` adapter, use the `add` command:\n\n- For the [integrated HTTP server](https://bun.sh/docs/api/http):\n\n```shell\nbun run qwik add bun\n```\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `bun run build.server` and `bun run build.client`:\n\n```shell\nbun run build\n```\n\n## Serve\n\nTo start the Bun server after a build:\n\n```shell\nbun run serve\n```\n\n## Production deploy\n\nSince you are choosing Bun, here you are in your own, after running `bun run build`:\n\n- The `dist` folder will be created including all the static files.\n- The `server` folder will be created including all bun server files.\n"},{"id":"/docs/deployments/cloudflare-pages/","title":"Cloudflare Pages Adapter and Middleware | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/cloudflare-pages/","content":"# Cloudflare Pages Adapter\n\nQwik Router Cloudflare Pages adapter allows you to connect Qwik Router to [Cloudflare Pages](https://pages.cloudflare.com/).\n\n## Installation\n\nTo integrate the `cloudflare-pages` adapter, use the `add` command:\n\n```shell\npnpm run qwik add cloudflare-pages\n```\n\nThe adapter will add a new `vite.config.ts` within the `adapters/` directory, and a new entry file will be created, such as:\n\n```shell\n`-- adapters/\n `-- cloudflare-pages/\n `-- vite.config.ts\n`-- src/\n `-- entry.cloudflare-pages.tsx\n```\n\nAdditionally, within the `package.json`, the `build.server` and `deploy` scripts will be updated.\n\nTake note of your nodejs version in your local environment by running the `node -v` command:\n```shell\nnode -v\nv20.11.1\n```\n\nWhen using\n\n```shell\npnpm create qwik@latest\n```\n\nto setup your Qwik app it will likely use a different nodejs version than what Cloudflare Pages uses by default (v16.20.2).\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n[Read the full guide here](https://github.com/QwikDev/qwik/tree/main/starters/adapters/cloudflare-pages/README.md)\n\n## Deploy to Cloudflare Pages\n\nAfter installing the integration the project is ready to be deployed to Cloudflare Pages.\n\nIf the nodejs version is different in your environment than Cloudflare Pages (v16.20.2) you'll need to add a `NODE_VERSION` environment variable and set the value to the version that you got from running the `node -v` command in your environment:\n\n```shell\nnode -v\nv20.11.1\n```\n\nTo do this in Cloudflare go to **Workers & Pages > YOUR_PROJECT > Settings > Environment variables > Production (and Preview) > Add variables > Save **\n\nPlease refer to the [Cloudflare Pages docs](https://developers.cloudflare.com/pages/framework-guides/deploy-a-qwik-site/) for more information on how to deploy your site.\n\nNote that you will need a [Cloudflare account](https://dash.cloudflare.com/sign-up?lang=en-US) in order to complete this step.\n\n## Static Site Generation (SSG)\n\nThe Cloudflare Pages adapter also supports Static Site Generation (SSG) by using the `ssg` property.\nThis allows you to generate static HTML files for your application at build time, instead of rendering them at runtime.\n\n```ts title=\"adapters/cloudflare-pages/vite.config.ts\"\nexport default extendConfig(baseConfig, () => {\n return {\n build: {\n ssr: true,\n rolldownOptions: {\n input: [\n 'src/entry.cloudflare-pages.tsx',\n // This ensures that the SSG can read the routes from the config\n '@qwik-router-config',\n ],\n }\n },\n plugins: [\n cloudflarePagesAdapter(\n // THIS IS WHAT YOU NEED TO ADD {\n ssg: {\n include: ['/*'],\n exclude: ['/shop/*'],\n origin: 'https://example.com',\n },\n }),\n ],\n };\n});\n\n```\n\n#### `include`\n\nThe `include` array is used to specify which paths should be statically generated. It accepts wildcard behavior.\n\n#### `exclude`\n\nThe `exclude` array defines routes that should not be static generated and accepts wildcard behavior.\n`exclude` always take priority over include.\n\n#### `origin`\n\nThe URL `origin`, which is a combination of the scheme (protocol) and hostname (domain). For example, `https://qwik.dev` has the protocol `https://` and domain `qwik.dev`. However, the `origin` does _not_ include a `pathname`.\n\nThe `origin` is used to provide a full URL during Static Site Generation (SSG), and to simulate a complete URL rather than just the `pathname`.\nFor example, in order to render a correct canonical tag URL or URLs within the `sitemap.xml`, the `origin` must be provided too.\n\nThis is important because if you don't set it, cloudflare will use the specific deployment url instead.\n\n## Advanced\n\n### Cloudflare Pages Entry Middleware\n\nWhen the `cloudflare-pages` adapter is added, a new entry file will be created at `src/entry.cloudflare-pages.tsx`. Below is an example of using the built-in middleware within the entry file.\n\n```tsx title=\"src/entry.cloudflare-pages.tsx\"\nimport {\n createQwikRouter,\n type PlatformCloudflarePages,\n} from '@qwik.dev/router/middleware/cloudflare-pages';\nimport render from './entry.ssr';\n\nconst fetch = createQwikRouter({ render });\n\nexport { fetch };\n```\n\nThe compiled middleware will be built in the `server/` directory. Such directory also contains a `_worker.js` file which implements the application's request handling as per the [Cloudflare Pages Advanced Mode](https://developers.cloudflare.com/pages/platform/functions/advanced-mode/#advanced-mode).\nThe file simply re-exports the produced `fetch` handler as shown below.\n\n```tsx title=\"/dist/_worker.js\"\nimport { fetch } from \"../server/entry.cloudflare-pages\";\nexport default { fetch };\n```\n\n- [Cloudflare Pages Middleware Source](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/middleware/cloudflare-pages/index.ts)\n- [Cloudflare Pages Advanced Mode](https://developers.cloudflare.com/pages/platform/functions/advanced-mode/)\n- [Function Invocation Route Config](https://developers.cloudflare.com/pages/platform/functions/routing/#functions-invocation-routes)\n\n### Cloudflare Pages Function Invocation Routes\n\nCloudflare Page's [function-invocation-routes config](https://developers.cloudflare.com/pages/platform/functions/routing/#functions-invocation-routes) can be used to include, or exclude, certain paths to be used by the worker functions. Having a `_routes.json` file gives developers more granular control over when your Function is invoked.\n\nThis is useful to determine if a page response should be Server-Side Rendered (SSR) or if the response should use a static-site generated (SSG) `index.html` file instead.\n\nBy default, the Cloudflare Pages adapter _does not_ include a `public/_routes.json` config, but rather it is auto-generated from the build by the Cloudflare adapter. An example of an auto-generated `dist/_routes.json` would be:\n\n```json\n{\n \"include\": [\"/*\"],\n \"exclude\": [\n \"/_headers\",\n \"/_redirects\",\n \"/build/*\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/service-worker.js\",\n \"/about\"\n ],\n \"version\": 1\n}\n```\n\nIn the above example, it's saying _all_ pages should be SSR'd. However, the root static files such as `/favicon.ico` and any static assets in `/build/*` should be excluded from the Functions, and instead treated as a static file.\n\nIn most cases the generated `dist/_routes.json` file is ideal. However, if you need more granular control over each path, you can instead provide your own `public/_routes.json` file. When the project provides its own `public/_routes.json` file, then the Cloudflare adapter will not auto-generate the routes config and instead use the committed one within the `public` directory.\n\n### Context\n\nYou may access Cloudflare Page's environment variables in the endpoint method's `platform` param:\n\n```ts\nexport const onRequest = async ({ platform }) => {\n const secret = platform.env['SUPER_SECRET_TOKEN'];\n};\n```\n\nAdditionally, you may import the `RequestHandler` and `PlatformCloudflarePages` types to have type completions in your editor.\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\nimport { type PlatformCloudflarePages } from '@qwik.dev/router/middleware/cloudflare-pages';\n\nexport const onGet: RequestHandler<PlatformCloudflarePages> = ({ platform }) => {\n //...\n};\n```\n"},{"id":"/docs/deployments/cloudflare-workers/","title":"Cloudflare Workers Adapter and Middleware | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/cloudflare-workers/","content":"# Cloudflare Workers Adapter\n\nQwik Router Cloudflare Workers adapter allows you to connect Qwik Router to [Cloudflare Workers](https://workers.cloudflare.com/).\n\n## Installation\n\nTo integrate the `cloudflare-workers` adapter, use the `add` command:\n\n```shell\npnpm run qwik add cloudflare-workers\n```\n\nThe adapter will add a new `vite.config.ts` within the `adapters/` directory, a new entry file, and a `wrangler.jsonc` configuration file:\n\n```shell\n`-- adapters/\n `-- cloudflare-workers/\n `-- vite.config.ts\n`-- src/\n `-- entry.cloudflare-pages.tsx\n`-- wrangler.jsonc\n`-- worker-configuration.d.ts\n```\n\nAdditionally, within the `package.json`, the following scripts will be added:\n\n- `\"cf-typegen\": \"wrangler types\"` - Generate TypeScript types for your Worker bindings\n- `\"serve\": \"wrangler dev\"` - Start a local development server\n- `\"deploy\": \"wrangler deploy\"` - Deploy your Worker to Cloudflare\n\n## Configuration\n\n### TypeScript Configuration\n\nAdd the Cloudflare Workers types to your `tsconfig.json`:\n\n```json title=\"tsconfig.json\"\n{\n \"compilerOptions\": {\n \"types\": [\n \"@cloudflare/workers-types/2023-07-01\",\n \"node\"\n ]\n }\n}\n```\n\nThis enables TypeScript autocompletion for Cloudflare Workers APIs and bindings.\n\n### Vite Configuration\n\nTo enable local development with access to your Worker's bindings (KV, R2, D1, etc.), update your `vite.config.ts`:\n\n```ts title=\"vite.config.ts\"\nimport { defineConfig, type UserConfig } from \"vite\";\nimport { qwikVite } from \"@qwik.dev/core/optimizer\";\nimport { qwikRouter } from \"@qwik.dev/router/vite\";\nimport tsconfigPaths from \"vite-tsconfig-paths\";\n\nlet platform = {};\n\nif (process.env.NODE_ENV === 'development') {\n const { getPlatformProxy } = await import('wrangler');\n platform = await getPlatformProxy();\n}\n\nexport default defineConfig(({ command, mode }): UserConfig => {\n return {\n plugins: [\n qwikRouter({\n platform\n }),\n// the rest of your code\n```\n\nThe `getPlatformProxy` function provides access to your Worker's bindings during local development, allowing you to test KV, R2, D1, and other Cloudflare resources locally.\n\n### Wrangler Configuration\n\nThe `wrangler.jsonc` file contains your Worker's configuration. Make sure to update the `name` field to match your project:\n\n```jsonc title=\"wrangler.jsonc\"\n{\n \"name\": \"my-qwik-app\", // Change this to your Worker's name\n \"main\": \"./dist/_worker.js\",\n \"compatibility_date\": \"2025-12-28\",\n // ... rest of configuration\n}\n```\n\nAfter adding any bindings (KV, R2, D1, etc.) to `wrangler.jsonc`, regenerate the TypeScript types:\n\n```shell\npnpm run cf-typegen\n```\n\nThis will update the `worker-configuration.d.ts` file with proper types for your bindings.\n\n## Local Development\n\nTo start a local development server with your Worker:\n\n```shell\npnpm run serve\n```\n\nThis will start Wrangler's development server, typically at `http://localhost:8787/`.\n\n## Production Build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n[Read the full guide here](https://github.com/QwikDev/qwik/tree/main/starters/adapters/cloudflare-workers/README.md)\n\n## Deploy to Cloudflare Workers\n\nAfter installing the integration the project is ready to be deployed to Cloudflare Workers.\n\nIf the nodejs version is different in your environment than Cloudflare Workers (v16.20.2) you'll need to add a `NODE_VERSION` environment variable and set the value to the version that you got from running the `node -v` command in your environment:\n\nThen deploy your Worker:\n\n```shell\npnpm run deploy\n```\n\nYour Worker will be deployed to `https://your-worker-name.your-subdomain.workers.dev`.\n\nNote that you will need a [Cloudflare account](https://dash.cloudflare.com/sign-up) in order to complete this step.\n\n## Environment Variables\n\nCloudflare Workers support two types of environment variables:\n\n### Build-Time Variables\n\nBuild-time variables are set in the Cloudflare Dashboard and are available during the build process. These are useful for configuration that doesn't change between deployments.\n\nTo set build-time variables:\n1. Go to **Workers & Pages** in your Cloudflare Dashboard\n2. Select your Worker\n3. Go to **Settings > Build**\n4. Add your variables under **Variables and secrets** (not to be confused by Variables and secrets thats right under domains section)\n\n### Runtime Variables\n\nRuntime variables are defined in your `wrangler.jsonc` file using the `vars` property:\n\n```jsonc title=\"wrangler.jsonc\"\n{\n \"name\": \"my-qwik-app\",\n \"vars\": {\n \"MY_VARIABLE\": \"production_value\",\n \"API_URL\": \"https://api.example.com\"\n }\n}\n```\n\n## Custom Domains\n\nYou can attach custom domains to your Worker for production use:\n\n1. Go to **Workers & Pages** in your Cloudflare Dashboard\n2. Select your Worker\n3. Go to **Settings > Triggers > Custom Domains**\n4. Click **Add Custom Domain**\n5. Enter your domain name (e.g., `app.example.com`)\n6. Follow the instructions to update your DNS settings\n\nFor more details, see the [Cloudflare Custom Domains documentation](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/).\n\n## Advanced\n\n### Cloudflare Workers Entry Middleware\n\nWhen the `cloudflare-workers` adapter is added, a new entry file will be created at `src/entry.cloudflare-pages.tsx`. Below is an example of using the built-in middleware within the entry file.\n\n```tsx title=\"src/entry.cloudflare-pages.tsx\"\nimport {\n createQwikRouter,\n type PlatformCloudflarePages as PlatformCloudflareWorkers,\n} from '@qwik.dev/router/middleware/cloudflare-pages';\nimport render from './entry.ssr';\n\nconst fetch = createQwikRouter({ render });\n\nexport { fetch };\n```\n\nThe compiled middleware will be built in the `server/` directory. The build process also creates a `_worker.js` file in the `dist/` directory, which is the entry point for your Cloudflare Worker.\n\n```tsx title=\"/dist/_worker.js\"\nimport { fetch } from \"../server/entry.cloudflare-pages\";\nexport default { fetch };\n```\n\nThis file exports the `fetch` handler that Cloudflare Workers uses to handle incoming requests.\n\n### Bindings\n\nCloudflare Workers can access various Cloudflare resources through bindings. These are configured in your `wrangler.jsonc` file:\n\n#### KV Namespace\n\n```jsonc title=\"wrangler.jsonc\"\n{\n \"kv_namespaces\": [\n {\n \"binding\": \"MY_KV\",\n \"id\": \"your-kv-namespace-id\"\n }\n ]\n}\n```\n\nAccess in your code:\n\n```ts\nexport const onGet = async ({ platform }) => {\n const value = await platform.env.MY_KV.get('key');\n};\n```\n\n#### R2 Bucket\n\n```jsonc title=\"wrangler.jsonc\"\n{\n \"r2_buckets\": [\n {\n \"binding\": \"MY_BUCKET\",\n \"bucket_name\": \"my-bucket\"\n }\n ]\n}\n```\n\n#### D1 Database\n\n```jsonc title=\"wrangler.jsonc\"\n{\n \"d1_databases\": [\n {\n \"binding\": \"DB\",\n \"database_name\": \"my-database\",\n \"database_id\": \"your-database-id\"\n }\n ]\n}\n```\n\nAfter adding any bindings, remember to regenerate types:\n\n```shell\npnpm run cf-typegen\n```\n\nFor more information on bindings, see the [Cloudflare Workers Bindings documentation](https://developers.cloudflare.com/workers/runtime-apis/bindings/).\n\n### Context and Platform Access\n\nYou can access Cloudflare Worker's environment variables, bindings, and context in your endpoint methods through the `platform` parameter:\n\n```ts\nexport const onRequest = async ({ platform }) => {\n // Access environment variables\n const secret = platform.env['SUPER_SECRET_TOKEN'];\n\n // Access KV namespace\n const value = await platform.env.MY_KV.get('key');\n\n // Access D1 databases\n const result = await platform.env.DB.prepare('SELECT * FROM users').all();\n};\n```\n\nFor better type safety, import the `RequestHandler` and `PlatformCloudflareWorkers` types:\n\n```tsx\nimport { type RequestHandler } from '@qwik.dev/router';\nimport { type PlatformCloudflarePages as PlatformCloudflareWorkers } from '@qwik.dev/router/middleware/cloudflare-pages';\n\nexport const onGet: RequestHandler<PlatformCloudflareWorkers> = async ({ platform }) => {\n // TypeScript will provide autocompletion for platform.env\n //...\n};\n```\n\nThe `platform` object provides access to:\n- `platform.env` - Environment variables, secrets, and bindings (KV, R2, D1, etc.)\n- Request context and metadata\n\nFor more information, see the [Cloudflare Workers Runtime APIs documentation](https://developers.cloudflare.com/workers/runtime-apis/).\n"},{"id":"/docs/deployments/deno/","title":"Deno Middleware | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/deno/","content":"# Deno Middleware\n\nQwik Router Deno middleware allows you to hook up Qwik Router to a Deno server which uses the standard Request/Response that's well supported by Deno. Some Deno server implementations include:\n\n- [Deno's integrated HTTP server](https://docs.deno.com/runtime/tutorials/http_server)\n- [Oak](https://oakserver.github.io/oak/)\n\n## Installation\n\nTo integrate the `deno` adapter, use the `add` command:\n\n- For the [integrated HTTP server](https://docs.deno.com/runtime/tutorials/http_server):\n\n```shell\npnpm run qwik add deno\n```\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n## Serve\n\nTo start the Deno server after a build:\n\n```shell\npnpm run serve\n```\n\n## Production deploy\n\nSince you are choosing Deno, here you are in your own, after running the `build` command:\n\n- The `dist` folder will be created including all the static files.\n- The `server` folder will be created including all node server files.\n\nBy default, `SSG` mode is activated. If you want to change this behavior, you can edit the `vite.config.ts` file inside the `adapters/deno` folder. In this file you can configure the behavior of the `SSG` or remove the SSG part to switch to a complete `SSR`.\n"},{"id":"/docs/deployments/deployhq/","title":"DeployHQ | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/deployhq/","content":"# DeployHQ\n\n[DeployHQ](https://www.deployhq.com) is a Git-based deployment platform that builds your Qwik Router application on its build pipeline and transfers the output to your own infrastructure over SSH, SFTP, or FTP. It also supports Amazon S3, Azure Blob Storage, and Rackspace Cloud Files as deployment targets.\n\nBecause DeployHQ deploys to a server you control, the recommended adapter is [Node](/docs/deployments/node.md) (Express or Fastify) for SSR apps, or the [Static Site](/docs/deployments/static.md) adapter for fully pre-rendered apps.\n\n## Installation\n\nInstall the Node adapter for SSR (Express shown here):\n\n```shell\npnpm run qwik add express\n```\n\nOr, for a fully static build:\n\n```shell\npnpm run qwik add static\n```\n\n## Production build\n\nDeployHQ runs your build command on its own build infrastructure. In your DeployHQ project's **Build Pipeline**, add a step that runs:\n\n```shell\npnpm install --frozen-lockfile && pnpm run build\n```\n\nThis produces the `dist/` directory (client assets) and, for SSR adapters, the `server/` directory containing `entry.express.js` or `entry.fastify.js`.\n\n## Production deploy\n\n1. Connect your Git repository (GitHub, GitLab, or Bitbucket) to a DeployHQ project.\n2. Configure one or more **servers** for the environments you want to deploy to (e.g. `staging`, `production`). Each server can deploy over SSH, SFTP, FTP, S3, Azure Blob, or Rackspace Cloud Files.\n3. Add the build command above to the project's build pipeline so the `dist/` and `server/` folders are produced before transfer.\n4. On the target server, install production dependencies and start the Node entry file. For Express:\n\n```shell\nORIGIN=https://your-domain.com node server/entry.express.js\n```\n\nIt's **very important to correctly configure the `ORIGIN` environment variable**, which is used to check against [CSRF attacks](https://owasp.org/www-community/attacks/csrf). The origin must match the origin of the client application. A process manager such as PM2 or a systemd unit is recommended for keeping the server running — see the [Self-Hosting guide](/docs/deployments/self-hosting.md) for examples.\n\nFor static builds, point the deployment target at the contents of `dist/` and serve it with any static web server.\n\n## Atomic releases, rollback, and environments\n\nEach deployment creates an immutable release on the target server, so a one-click rollback restores the previous build instantly. Separate DeployHQ projects (or separate servers within the same project) let you keep `staging` and `production` isolated, and config-file injection lets you keep environment-specific values like `ORIGIN` out of the repository.\n\nA free tier is available — sign up at [deployhq.com/signup](https://www.deployhq.com/signup) to get started.\n"},{"id":"/docs/deployments/firebase/","title":"Firebase | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/firebase/","content":"# Firebase Adapter\n\nQwik Router Firebase Adapter allows you to connect Qwik Router to [Firebase](https://firebase.google.com/docs/hosting).\n\n## Installation\n\nTo integrate the `firebase` adapter, use the `add` command:\n\n```shell\npnpm run qwik add firebase\n```\n\nThe adapter will add a new `vite.config.ts` within the `adapters/` directory, and a new entry file will be created, such as:\n\n```shell\n`-- adapters/\n `-- firebase\n `-- vite.config.ts\n`-- src/\n `-- entry-firebase.tsx\n```\n\nAdditionally, within the `package.json`, the `build.server` and `serve` scripts will be updated.\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n## Deploy to Firebase\n\nBefore deploy you need to setup your Firebase Credentials and add a Firebase project to the repository using these commands.\n\n```shell\nfirebase login\nfirebase use --add\npnpm run deploy\n```\n\nDone!\n"},{"id":"/docs/deployments/gcp-cloud-run/","title":"Cloud Run Middleware | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/gcp-cloud-run/","content":"# Google Cloud Run Middleware\n\nQwik Router Cloud Run middleware allows you to run a Qwik Router app on [Google Cloud Run](https://cloud.google.com/run)\n\n## Installation\n\nTo integrate the `Cloud Run` adapter, use the `add` command:\n\n```shell\npnpm run qwik add cloud-run\n```\n\n## Production deploy\n\nTo deploy your app, you need to:\n\n1. Have a [Google Cloud](https://cloud.google.com/) account\n\n2. Install the `gcloud` CLI\n\n If you don't have gcloud, follow [Google Cloud's official documentation](https://cloud.google.com/sdk/docs/install).\n\n3. Authenticate with the `gcloud` CLI\n\n To authenticate the `gcloud` CLI, run this command:\n\n ```shell\n gcloud auth login\n ```\n\n Grant the SDK access to the account you created in step 1.\n\n4. Change the name of the deploy script\n\n Update the name of your Cloud Run app in the deploy script in your package.json.\n\n ```json\n \"deploy\": \"gcloud run deploy my-cloud-run-app --source .\"\n ```\n\n5. Run deploy script\n\n Deploy to Google Cloud Run with:\n\n```shell\npnpm run deploy\n```\n"},{"id":"/docs/deployments/github-pages/","title":"GitHub Pages","description":"","url":"https://next.qwik.dev/docs/deployments/github-pages/","content":"# GitHub Pages With Static Site Adapter\n\nQwik's Static Site adapter helps to generate static html files which can be easily deployed to GitHub Pages.\n\n## Installation\n\nTo integrate the `static-site` adapter, use the `add` command:\n\n```shell\npnpm run qwik add static\n```\n\nAbove command will create a directory at project root named `adapters/static/vite.config.ts` with the below code.\n\n```ts title=\"adapters/static/vite.config.ts\"\nimport { staticAdapter } from \"@qwik.dev/router/adapters/static/vite\";\nimport { extendConfig } from '@qwik.dev/router/vite';\nimport baseConfig from '../../vite.config';\n\nexport default extendConfig(baseConfig, () => {\n return {\n build: {\n ssr: true,\n },\n plugins: [\n staticAdapter({\n origin: 'https://yoursite.qwik.dev',\n }),\n ],\n };\n});\n```\n\nRemember to change the `origin` in this file to your domain.\n\nIn the main `vite.config.ts` you should add the base property and set the value with the name of your repository.\n\n```ts\nexport default defineConfig(({ command, mode }): UserConfig => {\n return {\n base: '/github-repository-name/',\n [...]\n }\n});\n```\n\n## Automated Deployment to GitHub Pages with GitHub Actions\n\nGitHub Actions enables automated deployment of your site to GitHub Pages upon code changes.\nTo enable this feature, configure your repository settings as follows:\n- Navigate to GitHub Pages Settings: Access your repository's GitHub Pages settings by visiting the /settings/pages path within your repository.\nFor example: https://github.com/your-github-username/github-repository/settings/pages.\n- Configure Deployment Source: Under the \"Source\" section, select \"GitHub Actions\" as the deployment source.\nThis instructs GitHub Pages to use a GitHub Actions workflow for deployments.\n\n## Add The GitHub Action\n\nHere's an example:\n\n```yml\n# FILE: .github/workflows/deploy.yml\n# ==========================================\n\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@v5\n\n - name: Install pnpm\n uses: pnpm/action-setup@v4\n with:\n version: 10.15.0\n\n - name: Install Node.js\n uses: actions/setup-node@v5\n with:\n node-version: 24.7.0\n cache: 'pnpm'\n\n - run: corepack enable\n\n - name: Install dependencies\n run: pnpm install --frozen-lockfile\n\n - name: build\n run: |\n pnpm run build\n\n - name: Upload Artifacts\n uses: actions/upload-pages-artifact@v3\n with:\n path: 'dist/github-repository-name/'\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\nThis GitHub Actions workflow automates the process of building and deploying a website to GitHub Pages.\nIt triggers upon pushes to the main branch, ensuring the site is updated with the latest changes.\nThe workflow first builds the website using pnpm, then uploads the generated files as an artifact.\nFinally, it deploys the artifact to GitHub Pages, making the site live.\n"},{"id":"/docs/deployments/","title":"Deployments | Guides","description":"","url":"https://next.qwik.dev/docs/deployments/","content":"# Deployments\n\nWhen it's time to deploy your application, Qwik comes with ready-to-use integration that make this so easy!\n\n```shell\npnpm run qwik add\n```\n\n## Adapters and Middleware\n\nQwik Router middleware is a glue code that connects server rendering framework such as Cloudflare, Netlify, Vercel, Express etc.\n\n## Production build\n\nWhen a new integration is added to the project, a `build.server` script is added to the `package.json` file. This script is used to build the project for production.\n\nThe only thing you need to do is to run the following command:\n\n```shell\npnpm run build\n```\n\nUnder the hood, the `build` script will execute, `build.server` and `build.client` scripts.\n\n## Advanced\n\nThe `requestHandler()` utility is what each of the above middleware bundles uses in order to translate their request/response to a standard format for Qwik Router to use. This function can be used to provide middleware for specific server frameworks.\n\nIf there's middleware missing and you'd like it added, take a look at how the `requestHandler()` utility is used to handle requests for each of the middleware source-code above. Better yet, we'd love to have your middleware contributions! [PR's are welcome](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/middleware)!\n\n## Add A New Deployment\n\nThanks for your interest in adding a deployment integration to Qwik! We're more than happy to help you get started. Before we get too far, if there's already a deployment for what you're looking for, we'd [love to have you contribute to it](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/adapters). If the deployment is not already available, let's add it!\n\nTo start it's probably best to copy an existing adapters and middleware and modify it to fit your needs. A deployment is made up of a few different parts:\n\n### Add An Adapter\n\nAn adapter is the term used to summarize the Vite config that needed for the special build configuration. Each server, whether it's a cloud-service or a custom server, has its own unique build configuration for a specific output the server uses. For example, [Cloudflare](/docs/deployments/cloudflare-pages.md), [Netlify](/docs/deployments/netlify-edge.md) and [Node.js Server](/docs/deployments/node.md) each have their own build configurations.\n\nThe adapter is really a Vite config, that's extending the base config. The base config is the same for all adapters, and the adapter config is the unique part for each server.\n\n- [Adapters Source](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/adapters)\n\n### Add Middleware\n\nMiddleware is the glue code that connects the server rendering framework (such as Cloudflare, Netlify, Vercel, Express etc. Each middleware is responsible for handling the request and response from the server and translating it to a standard format for Qwik Router to use.\n\nLuckily Qwik Router uses the standardized [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) interfaces, so the middleware is usually pretty minimal.\n\nFor middleware, you'll notice that each one calls the common `@qwik.dev/router/middleware/request-handler` package. The job of each middleware is to translate the request and response to the standardized format that Qwik Router request handler package uses.\n\n- [Middleware Source](https://github.com/QwikDev/qwik/tree/main/packages/qwik-router/middleware)\n\n### Add To The Starter CLI\n\nThe next step is to add the new adapter to the Starter CLI. For this step it's probably best to ping the core team on [Discord](https://qwik.dev/chat) to help you get started. The CLI is a great place to add the new adapter, because it's a great way to test the new adapter and make sure it's working as expected.\n\n## Cache Headers\n\nTo assure proper caching of your built files, you need to serve them with the correct cache headers.\n\nBy default, files are generated under `dist/build` and `dist/assets`, and they get a content hash in the filename. This means that the name is unique for the contents of those files, and they can be cached indefinitely.\n\nTherefore, we recommend that you serve these files with the following header:\n\n```\nCache-Control: public, max-age=31536000, immutable\n```\n\nThe various deployment platforms have different ways of configuring this, and the starters should have the correct configuration already set (you can `npx qwik add` again to update the configuration). However, there is no one-size-fits-all solution, so verify that caching is working as expected.\n\nTo verify proper caching, you can visit your site and open the developer tools to inspect the network requests. When you reload the page, you should see that all requests for assets are coming from the browser cache and are not contacting the server. Even a `304 Not Modified` response is not good enough, because it means that the browser is still unsure that the content is cached.\n\n **Note**: If your app uses [`compiled-i18n`](https://github.com/wmertens/compiled-i18n) or [`qwik-speak`](https://github.com/robisim74/qwik-speak), then translated bundles (`build/[locale]/*.js`) can retain identical filenames between builds even when translations change. Consider how long you want to cache these files for so users get the latest translations.\n\n## Origin\n\nWe recommend setting the `ORIGIN` environment variable to the origin of your site (e.g. `https://example.com/`). This is used to resolve relative URLs and to validate the request origin when performing CSRF checks.\n\nHowever, if the origin of your application is not static because you're hosting multiple sites, the Node.js based middleware provides a `getOrigin()` callback option to reliably reconstruct the origin (scheme + host + optional port).\n\n### Examples\n\n1) Simple static origin from environment (recommended for production if you know the origin):\n\n```ts\n// Provide ORIGIN=https://example.com in your environment\ncreateQwikRouter({\n origin: process.env.ORIGIN,\n});\n```\n\n2) Compute origin using forwarded headers (common when behind proxies). Use the headers your proxy provides, e.g. `X-Forwarded-Proto` and `X-Forwarded-Host`:\n\n```ts\ncreateQwikRouter({\n getOrigin(req) {\n const proto = req.headers['x-forwarded-proto'] as string | undefined;\n const host = req.headers['x-forwarded-host'] as string | undefined || (req.headers.host as string | undefined);\n if (!host) return null;\n return `${proto ?? 'https'}://${host}`;\n }\n});\n```\n\n3) Example: Cloud Run adapter (reconstructs the origin from forwarded headers)\n\n```ts\n// starters/adapters/cloud-run entry (illustrative)\ncreateQwikRouter({\n getOrigin(req) {\n // Cloud Run sets X-Forwarded-Proto and Host headers\n const proto = req.headers['x-forwarded-proto'] as string | undefined;\n const host = (req.headers['host'] || req.headers['x-forwarded-host']) as string | undefined;\n if (!host) return null;\n return `${proto ?? 'https'}://${host}`;\n }\n});\n```\n\n### Notes and best practices\n\n- Prefer a static `ORIGIN` environment variable for production whenever possible. It is the most reliable and secure option.\n- When relying on forwarded headers, ensure your proxy/ALB sets them and consider locking the trusted proxy list so attackers cannot spoof them.\n- Return `null` from `getOrigin` when the origin cannot be determined; the middleware will fall back to deriving it from the request.\n"},{"id":"/docs/deployments/netlify-edge/","title":"Netlify Edge Adapter and Middleware | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/netlify-edge/","content":"# Netlify Edge Adapter\n\nQwik Router Netlify Edge adapter allows you to connect Qwik Router to [Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/).\n\n## Installation\n\nTo integrate the `netlify-edge` adapter, use the `add` command:\n\n```shell\npnpm run qwik add netlify-edge\n```\n\nIt will automatically install the required dependencies, including the [Netlify CLI](https://cli.netlify.com/).\n\nThe adapter will add a new `vite.config.ts` within the `adapters/` directory, and a new entry file will be created, such as:\n\n```shell\n`-- adapters/\n `-- netlify-edge/\n `-- vite.config.ts\n`-- src/\n `-- entry.netlify-edge.tsx\n```\n\nAdditionally, within the `package.json`, the `build.server` and `deploy` scripts will be updated.\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n[Read the full guide here](https://github.com/QwikDev/qwik/blob/main/starters/adapters/netlify-edge/README.md)\n\n## Dev deploy\n\nTo deploy the application for development:\n\n```shell\npnpm run deploy\n```\n\nNotice that you might need a [Netlify account](https://docs.netlify.com/get-started/) in order to complete this step!\n\n## Production deploy\n\nAfter installing the integration the project is ready to be deployed to Netlify. However, you will need to create a git repository and push the code to it.\n\nPlease refer to the Netlify docs for more information on how to deploy your site: [Netlify docs](https://docs.netlify.com/site-deploys/create-deploys/)\n\n## Advanced\n\n### Netlify Edge Entry Middleware\n\nWhen the `netlify-edge` adapter is added, a new entry file will be created at `src/entry.netlify-edge.tsx`. Below is an example of using the built-in middleware within the entry file.\n\n```tsx title=\"src/entry.netlify-edge.tsx\"\nimport { createQwikRouter } from '@qwik.dev/router/middleware/netlify-edge';\nimport render from './entry.ssr';\n\nexport default createQwikRouter({ render });\n```\n\nThe compiled middleware will be built in the `.netlify/edge-functions` directory.\n\n### Netlify Edge Functions Declarations\n\n[Netlify Edge Functions declarations](https://docs.netlify.com/edge-functions/declarations/) can be configured to run on specific URL patterns. Each edge function declaration associates one site path pattern with one function to execute on requests that match the path. A single request can execute a chain of edge functions from a series of declarations. A single edge function can be associated with multiple paths across various declarations.\n\nThis is useful to determine if a page response should be Server-Side Rendered (SSR) or if the response should use a static-site generated (SSG) `index.html` file instead.\n\nBy default, the Netlify Edge adapter will generate a `.netlify/edge-middleware/manifest.json` file, which is used by the Netlify deployment to determine which paths should, and should not, use edge functions.\n\nTo override the generated manifest, you can [add a declaration](https://docs.netlify.com/edge-functions/declarations/#add-a-declaration) to the `netlify.toml` using the `[[edge_functions]]` config. For example:\n\n```toml title=\"netlify.toml\"\n[[edge_functions]]\n path = \"/admin\"\n function = \"auth\"\n```\n\n### Netlify Request Context\n\n[Netlify context](https://docs.netlify.com/edge-functions/api/#netlify-specific-context-object) is available in endpoint method's `platform` param:\n\n```ts\nexport const onRequest = async ({ platform }) => {\n platform.log('requested ip:', platform.ip);\n};\n```\n\n### Environment variables\n\n```ts\nexport const onRequest = async ({ env }) => {\n platform.log('netlify serverless env read from Netlify UI or CLI', env.get('API_KEY'));\n};\n```\n\n- [Netlify Environment Variables](https://docs.netlify.com/environment-variables/overview/#environment-variable-options)\n- [Netlify Edge Middleware Source](https://github.com/QwikDev/qwik/blob/main/packages/qwik-router/src/middleware/netlify-edge/index.ts)\n"},{"id":"/docs/deployments/node/","title":"Node Middleware | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/node/","content":"# Node Middleware\n\nQwik Router Node middleware allows you to connect Qwik Router to a Node.js server which uses the common middleware functionality. Some Node servers include:\n\n- [Express](https://expressjs.com/)\n- [Fastify](https://fastify.dev/)\n- [Connect](https://www.npmjs.com/package/connect)\n- [Polka](https://www.npmjs.com/package/polka)\n\n## Installation\n\nTo integrate the `node` adapter, use the `add` command:\n\n- For [Express](https://expressjs.com/):\n\n```shell\npnpm run qwik add express\n```\n\n- For [Fastify](https://fastify.dev/)\n\n```shell\npnpm run qwik add fastify\n```\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n## Dev serve\n\nTo deploy the application for development:\n\n```shell\npnpm run serve\n```\n\n## Production deploy\n\nSince you are choosing Node, here you are in your own, after running the `build` command:\n\n- The `dist` folder will be created including all the static files.\n- The `server` folder will be created including all node server files.\n\nIn order to deploy the server, you need to run the `server/entry.[server].js` file in the server of your choice, where `[server]` can be [express](https://expressjs.com/) or [fastify](https://fastify.dev/).\n\nIt's **very important to correctly configure the `ORIGIN` env variable**, which is used to check against [CSRF attacks](https://owasp.org/www-community/attacks/csrf). The origin must match the origin of the client application.\n\n**Setting the ORIGIN Environment Variable**\n\nFor example, if you plan to deploy your application to `https://example.com/app`, then you need to set the `ORIGIN` environment variable to `https://example.com`.\n\n```shell\nORIGIN=https://example.com node server/entry.express\n```\n\nYou can check [how to deploy with Docker here](/docs/cookbook/node-docker-deploy.md).\n\n### CSRF Protection\n\nBy default, all Qwik Router applications are protected against [CSRF attacks](https://owasp.org/www-community/attacks/csrf) for all POST, PATCH, DELETE form submits.\n\nThis protection is enabled by default and it's the reason why you need to set the `ORIGIN` environment variable when deploying your application for production.\n\nIf you want to disable CSRF protection, you can set `checkOrigin: false` in the `createQwikRouter()` options in `src/entry.preview.tsx` or `src/entry.[server].tsx`:\n\n```tsx {6} /checkOrigin/ title=\"entry.preview.tsx\"\n// ...\nconst { router, staticFile } = createQwikRouter({\n render,\n checkOrigin: false,\n});\n// ...\n```\n"},{"id":"/docs/deployments/self-hosting/","title":"Self-Hosting","description":"","url":"https://next.qwik.dev/docs/deployments/self-hosting/","content":"# Self-Hosting Qwik Applications\n\nThis guide provides comprehensive instructions for self-hosting your Qwik application on your own infrastructure, whether it's a VPS, bare metal server, or container platform.\n\n## Prerequisites\n\n- Node.js >= 16.8.0 (18.x LTS or later recommended)\n- A web server like Nginx, Apache, or similar for production deployments\n- (Optional) Docker for containerized deployments\n- (Optional) PM2 or similar for process management\n\n## Build Options\n\nQwik provides several adapters suited for self-hosting scenarios. Choose the one that best fits your infrastructure:\n\n### Fastify (Node.js)\n\nFastify offers better performance than Express and is another good option for self-hosting:\n\n```shell\nnpx qwik add fastify\n```\n\n### Static Site\n\nFor simple applications without dynamic server functionality:\n\n```shell\nnpx qwik add static\n```\n\nWhen using the static adapter, make sure to update your `adapters/static/vite.config.ts` file with your actual domain:\n\n```ts\nstaticAdapter({\n origin: 'https://your-actual-domain.com',\n})\n```\n\n## Building for Production\n\nAfter adding the appropriate adapter, build your application. This will create a `dist/` directory with all the necessary files for deployment:\n\n```shell\npnpm run build\n```\n\nThe build process will generate:\n\n- `dist/` directory containing:\n - **Vite-generated files**:\n - `dist/build/` – JavaScript and CSS bundles (code-split and optimized)\n - `dist/assets/` – Fonts, images, and static assets processed by Vite\n - **Non-Vite files (copied as-is)**:\n - Everything from the `public/` folder (e.g., favicon, robots.txt, etc.)\n - **Static site generation output** (if SSG is used):\n - Pre-rendered `.html` pages\n - Route-specific `q-data.json` files\n - **Manifest files**:\n - `manifest.json` – For PWA support\n - `q-manifest.json` – Used during development, **can be omitted from production**\n\n- `server/` directory:\n - Contains server entrypoints like `entry.fastify.js` or `entry.express.js` depending on the adapter used.\n\n## Deployment Methods\n\n### Method 1: Node.js Server Deployment\n\nFor Express or Fastify adapters, the build process generates a server entry file at `server/entry.express.js` or `server/entry.fastify.js`.\n\n1. Transfer these files to your production server:\n - `dist/` (client assets)\n - `server/` (server code)\n - `package.json` (for dependencies)\n\n2. Install production dependencies on the server:\n\n```shell\npnpm install --prod\n```\n\n3. Set the required environment variables:\n\n```shell\n# Important: This is required for CSRF protection\nexport ORIGIN=https://your-domain.com\n\n# Set production mode\nexport NODE_ENV=production\n\n# Optional: Define a custom port (default is 3000)\nexport PORT=3000\n```\n\n4. Run the server:\n\n```shell\n# For Express\nnode server/entry.express.js\n\n# For Fastify\nnode server/entry.fastify.js\n```\n\n5. For production use, use a process manager like PM2:\n\n```shell\nnpm install -g pm2\n\n# For Express\npm2 start server/entry.express.js --name qwik-app\n\n# For Fastify\npm2 start server/entry.fastify.js --name qwik-app\n```\n\n### Using systemd\n\nCreate a systemd service file:\n\n```ini\n[Unit]\nDescription=Qwik Application\nAfter=network.target\n\n[Service]\nType=simple\nUser=qwikuser\nWorkingDirectory=/path/to/your/app\nExecStart=/usr/bin/node server/entry.express.js\nRestart=always\nEnvironment=NODE_ENV=production\n\n[Install]\nWantedBy=multi-user.target\n```\n\nEnable and start the service:\n```shell\nsudo systemctl enable qwik-app\nsudo systemctl start qwik-app\n```\n\n### Method 2: Docker Deployment\n\nUsing Docker is recommended for containerized deployments. Create a `Dockerfile` in your project root:\n\n```Dockerfile\nARG NODE_VERSION=18.18.2\n\n################################################################################\n# Use node image for base image for all stages.\nFROM node:${NODE_VERSION}-alpine as base\n\n# Set working directory for all build stages.\nWORKDIR /usr/src/app\n\n################################################################################\n# Create a stage for installing production dependencies.\nFROM base as deps\n\n# Download dependencies as a separate step to take advantage of Docker's caching.\n# Leverage a cache mount to /root/.yarn to speed up subsequent builds.\nRUN --mount=type=bind,source=package.json,target=package.json \\\n --mount=type=bind,source=yarn.lock,target=yarn.lock \\\n --mount=type=cache,target=/root/.yarn \\\n yarn install --frozen-lockfile\n\n################################################################################\n# Create a stage for building the application.\nFROM deps as build\n\n# Copy the rest of the source files into the image.\nCOPY . .\n\n# Run the build script.\nRUN yarn run build\n\n################################################################################\n# Create a new stage to run the application with minimal runtime dependencies\nFROM base as final\n\n# Use production node environment by default.\nENV NODE_ENV production\n\n# IMPORTANT: Set your actual domain for CSRF protection\nENV ORIGIN https://your-domain.com\n\n# Run the application as a non-root user.\nUSER node\n\n# Copy package.json so that package manager commands can be used.\nCOPY package.json .\n\n# Copy the production dependencies from the deps stage and also\n# the built application from the build stage into the image.\nCOPY --from=deps /usr/src/app/node_modules ./node_modules\nCOPY --from=build /usr/src/app/dist ./dist\nCOPY --from=build /usr/src/app/server ./server\n\n# Expose the port that the application listens on.\nEXPOSE 3000\n\n# Run the application.\nCMD yarn serve\n```\n\nBuild and run your Docker container:\n\n```shell\n# Build the image\ndocker build -t qwik-app .\n\n# Run the container\ndocker run -p 3000:3000 -e ORIGIN=https://your-domain.com qwik-app\n```\n\n### Method 3: Static Site Deployment\n\nIf using the static adapter, copy the contents of the `dist` directory to your web server's document root:\n\n```shell\n# Example using rsync\nrsync -avz dist/ user@your-server:/path/to/webroot/\n```\n\n## Web Server Configuration\n\n## Web Server Configurations\n\n### 1. Nginx for Node.js Applications\n\nFor Node.js deployments using Express or Fastify, use this Nginx configuration as a reverse proxy:\n\n```nginx\n# HTTP to HTTPS redirect\nserver {\n listen 80;\n server_name your-domain.com;\n return 301 https://$host$request_uri;\n}\n\n# Main server block\nserver {\n listen 443 ssl http2;\n server_name your-domain.com;\n\n # SSL configuration\n ssl_certificate /path/to/cert.pem;\n ssl_certificate_key /path/to/key.pem;\n ssl_protocols TLSv1.2 TLSv1.3;\n ssl_prefer_server_ciphers on;\n ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;\n ssl_session_timeout 1d;\n ssl_session_cache shared:SSL:10m;\n\n # Proxy to Node.js server\n location / {\n proxy_pass http://localhost:3000;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n }\n\n # Static assets handling (build and assets directories)\n location ~ ^/(build|assets)/ {\n root /path/to/your/app/dist;\n expires 1y;\n add_header Cache-Control \"public, max-age=31536000, immutable\";\n access_log off;\n }\n\n # Security headers\n add_header X-Content-Type-Options \"nosniff\" always;\n add_header X-Frame-Options \"SAMEORIGIN\" always;\n add_header X-XSS-Protection \"1; mode=block\" always;\n}\n```\n\n### 2. Nginx for Static Sites\n\nFor static site deployments, use this Nginx configuration:\n\n```nginx\n# HTTP to HTTPS redirect\nserver {\n listen 80;\n server_name your-domain.com;\n return 301 https://$host$request_uri;\n}\n\n# Main server block\nserver {\n listen 443 ssl http2;\n server_name your-domain.com;\n\n # SSL configuration\n ssl_certificate /path/to/cert.pem;\n ssl_certificate_key /path/to/key.pem;\n ssl_protocols TLSv1.2 TLSv1.3;\n ssl_prefer_server_ciphers on;\n\n # Document root\n root /path/to/your/app/dist;\n index index.html;\n\n # Security headers\n add_header X-Content-Type-Options \"nosniff\" always;\n add_header X-Frame-Options \"SAMEORIGIN\" always;\n add_header X-XSS-Protection \"1; mode=block\" always;\n\n # Main location block\n location / {\n try_files $uri $uri/ /index.html;\n }\n\n # Cache settings for static assets (build and assets directories)\n location ~ ^/(build|assets)/ {\n expires 1y;\n add_header Cache-Control \"public, max-age=31536000, immutable\";\n access_log off;\n try_files $uri =404;\n gzip_static on;\n brotli_static on;\n }\n\n # Route loader data caching\n location ~ /[^/]+/q-data\\.json$ {\n expires 30s;\n add_header Cache-Control \"public, must-revalidate\";\n try_files $uri =404;\n }\n\n # Security: Deny access to hidden files\n location ~ /\\. {\n deny all;\n access_log off;\n log_not_found off;\n }\n\n # Security: Deny access to .git directory\n location ^~ /.git/ {\n deny all;\n access_log off;\n log_not_found off;\n }\n}\n```\n\n### 3. Apache Configuration\n\nFor Apache with mod_proxy enabled, use this configuration:\n\n```apache\n# HTTP to HTTPS redirect\n<VirtualHost *:80>\n ServerName your-domain.com\n RewriteEngine On\n RewriteCond %{HTTPS} off\n RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</VirtualHost>\n\n# Main server block\n<VirtualHost *:443>\n ServerName your-domain.com\n\n # SSL Configuration\n SSLEngine on\n SSLCertificateFile /path/to/cert.pem\n SSLCertificateKeyFile /path/to/key.pem\n\n # Proxy to Node.js server\n ProxyPreserveHost On\n ProxyPass / http://localhost:3000/\n ProxyPassReverse / http://localhost:3000/\n\n # Serve static assets directly (build and assets directories)\n <Directory /path/to/your/app/dist/build>\n Options Indexes FollowSymLinks\n AllowOverride All\n Require all granted\n\n <IfModule mod_expires.c>\n ExpiresActive On\n ExpiresDefault \"access plus 1 year\"\n Header append Cache-Control \"public, immutable\"\n </IfModule>\n </Directory>\n\n # Alias for both build and assets directories\n AliasMatch ^/(build|assets)/(.*)$ /path/to/your/app/dist/$1/$2\n\n # Security headers\n Header always set X-Content-Type-Options \"nosniff\"\n Header always set X-Frame-Options \"SAMEORIGIN\"\n Header always set X-XSS-Protection \"1; mode=block\"\n\n # SPA fallback\n <IfModule mod_rewrite.c>\n RewriteEngine On\n RewriteBase /\n RewriteRule ^index\\.html$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.html [L]\n </IfModule>\n</VirtualHost>\n```\n\n## Security Best Practices\n\n### CSRF Protection\n\nQwik Router applications are protected against CSRF (Cross-Site Request Forgery) attacks by default for all state-mutating HTTP methods (POST, PATCH, DELETE). This protection is crucial for preventing unauthorized actions on behalf of authenticated users.\n\n#### How It Works\n\n1. **Default Protection**: Enabled by default for all non-idempotent requests\n2. **Origin Checking**: Validates the `Origin` and `Referer` headers against the `ORIGIN` environment variable\n3. **Configuration**: Controlled via the `checkOrigin` option in `createQwikRouter`\n\n#### Configuration Options\n\n##### 1. Basic Configuration (Recommended)\n\n```tsx\n// src/entry.express.tsx or src/entry.fastify.tsx\nconst { router } = createQwikRouter({\n render,\n // CSRF protection is enabled by default when ORIGIN is set\n checkOrigin: true\n});\n```\n\n##### 2. SSL Offload Proxy Setup\n\nWhen behind a reverse proxy (Nginx, CloudFront, etc.), use `'lax-proto'` to handle `X-Forwarded-Proto` headers:\n\n```tsx\nconst { router } = createQwikRouter({\n render,\n checkOrigin: 'lax-proto' // Required for proper proxy support\n});\n```\n\n##### 3. Disabling CSRF (Not Recommended)\n\n```tsx\nconst { router } = createQwikRouter({\n render,\n checkOrigin: false // Disables CSRF protection (not recommended for production)\n});\n```\n\n### Forwarded Headers\n\nBy default, `useLocation()` reports the URL the server received and ignores the `X-Forwarded-Host` and `X-Forwarded-Proto` request headers, since any client can send them. If your reverse proxy always overwrites these headers, enable `trustForwardedHeaders` so `useLocation()` reports the public URL:\n\n```tsx\nconst { router } = createQwikRouter({\n render,\n trustForwardedHeaders: true, // Only when a proxy overwrites X-Forwarded-* headers\n});\n```\n\n### Essential Security Headers\n\nConfigure these security headers in your web server:\n\n```nginx\n# Nginx example\nadd_header X-Content-Type-Options \"nosniff\" always;\nadd_header X-Frame-Options \"SAMEORIGIN\" always;\nadd_header X-XSS-Protection \"1; mode=block\" always;\nadd_header Referrer-Policy \"strict-origin-when-cross-origin\" always;\nadd_header Content-Security-Policy \"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;\" always;\n```\n\n### Additional Security Measures\n\n1. **User Privileges**\n - Run Node.js as a non-root user\n - Use process managers like PM2 with `--user` flag\n\n2. **Network Security**\n - Configure firewalls to expose only necessary ports (typically 80, 443)\n - Use fail2ban to protect against brute force attacks\n - Implement rate limiting for API endpoints\n\n3. **Dependencies**\n - Regularly update all dependencies\n - Use `npm audit` or `yarn audit` to identify vulnerabilities\n - Consider using Dependabot or similar tools\n\n4. **HTTPS**\n - Enforce HTTPS with HSTS header\n - Use modern TLS configurations (TLS 1.2/1.3)\n - Implement certificate auto-renewal (e.g., Certbot for Let's Encrypt)\n\n5. **Application Hardening**\n - Set appropriate file permissions\n - Disable directory listing\n - Protect sensitive files (e.g., `.env`, `.git`)\n - Implement proper CORS policies\n\n6. **Monitoring & Logging**\n - Monitor for suspicious activities\n - Implement centralized logging\n - Set up alerts for security events\n\n## Monitoring and Logging\n\n### Application Monitoring\n\n#### 1. Process Management with PM2\n\n```bash\n# Install PM2 globally\nnpm install -g pm2\n\n# Start application\npm2 start dist/server/entry.express.js --name qwik-app\n\n# Monitor application\npm2 monit\n\n# View logs\npm2 logs qwik-app\n\n# Set up PM2 to start on system boot\npm2 startup\npm2 save\n\n# Set up PM2 dashboard (optional)\nnpm install -g pm2-web\npm2-web --config pm2-webrc.json\n```\n\n#### 2. Web Server Logs\n\n**Nginx**\n```bash\n# Access logs\n/var/log/nginx/access.log\n/var/log/nginx/error.log\n\n# Enable JSON logging format in nginx.conf\nlog_format json_combined escape=json\n '{\"timestamp\":\"$time_iso8601\",'\n '\"remote_addr\":\"$remote_addr\",'\n '\"remote_user\":\"$remote_user\",'\n '\"request\":\"$request\",'\n '\"status\":\"$status\",'\n '\"body_bytes_sent\":\"$body_bytes_sent\",'\n '\"http_referer\":\"$http_referer\",'\n '\"http_user_agent\":\"$http_user_agent\"}';\n```\n\n### Performance Monitoring\n\n#### 1. System-Level Monitoring\n\n```bash\n# Basic system monitoring\ntop\nhtop\nnmon\n\n# Network monitoring\niftop\niotop\n\n# Disk I/O\niostat -x 1\n```\n\n#### 2. Application Performance Monitoring (APM)\n\n**Using Prometheus + Grafana**\n\n1. Set up Prometheus to collect metrics\n2. Configure Grafana for visualization\n3. Monitor key metrics:\n - Request rates\n - Error rates\n - Response times\n - Resource utilization\n\n**Alternative APM Solutions**\n- [New Relic](https://newrelic.com/)\n- [Datadog](https://www.datadoghq.com/)\n- [Sentry](https://sentry.io/)\n- [Elastic APM](https://www.elastic.co/observability/application-performance-monitoring)\n\n## Performance Optimization\n\n### Network Optimization\n\n1. **HTTP/2 and HTTP/3**\n - Enable HTTP/2 in Nginx/Apache\n - Consider HTTP/3 for modern browsers\n - Configure proper keep-alive settings\n\n2. **CDN Integration**\n - Use Cloudflare, CloudFront, or similar\n - Configure edge caching rules\n - Enable automatic image optimization\n\n3. **Compression**\n - Enable Brotli compression\n - Pre-compress static assets\n - Configure proper cache headers\n\n### Asset Optimization\n\n1. **Caching Strategy**\n ```nginx\n # Immutable assets (hashed filenames)\n location ~* \\.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot)$ {\n expires 1y;\n add_header Cache-Control \"public, max-age=31536000, immutable\";\n access_log off;\n }\n ```\n\n2. **Lazy Loading**\n - Use Qwik's built-in lazy loading\n - Split large components\n - Implement route-based code splitting\n\n3. **Image Optimization**\n - Use modern formats (WebP/AVIF)\n - Implement responsive images\n - Lazy load below-the-fold images\n\n### Server-Side Optimization\n\n1. **Node.js Tuning**\n - Set appropriate `NODE_ENV=production`\n - Tune V8 garbage collection\n - Use worker threads for CPU-intensive tasks\n\n2. **Database Optimization**\n - Implement connection pooling\n - Add appropriate indexes\n - Use query optimization techniques\n\n3. **Caching Layer**\n - Implement Redis/Memcached\n - Cache API responses\n - Use stale-while-revalidate patterns\n\n### Asset Compression\n\nEnable efficient compression for static assets:\n\n1. Pre-compress static files during build:\n```shell\n# Install compression tools\nnpm install -g brotli-cli gzip-cli\n\n# Compress build assets in parallel with maximum compression\nfind dist/build dist/assets -type f -regex '.*\\.\\(js\\|css\\|html\\|json\\)$' -print0 | xargs -0 gzip -9 -k &\nfind dist/build dist/assets -type f -regex '.*\\.\\(js\\|css\\|html\\|json\\)$' -print0 | xargs -0 brotli -15 -k &\nwait\n```\n\n2. Configure Nginx to serve pre-compressed files:\n```nginx\nlocation ~ ^/(build|assets)/ {\n root /path/to/your/app/dist;\n expires 1y;\n add_header Cache-Control \"public, max-age=31536000, immutable, no-transform\" always;\n access_log off;\n # Enable pre-compressed file serving\n gzip_static on;\n brotli_static on;\n try_files $uri =404;\n}\n```\n\n## Scaling Considerations\n\nFor high-traffic applications:\n\n1. Set up load balancing with multiple Node.js instances\n2. Use container orchestration (Kubernetes, Docker Swarm)\n3. Consider a microservices architecture for larger applications\n4. Implement Redis or similar for session management across instances\n5. Use a serverless approach for predictable scaling\n\n## Troubleshooting Common Issues\n\n1. **404 Not Found**:\n - Check your Nginx/Apache configuration paths\n - Verify that URL rewriting is properly configured\n - **Check file permissions**: Ensure the web server user has read access to all files and execute permission on all parent directories\n ```shell\n # Check permissions for a specific file\n sudo -u nginx ls -ld /path/to/static/file\n\n # Check directory permissions (go up the path to find where access is denied)\n sudo -u nginx ls -ld /path/to/static/\n sudo -u nginx ls -ld /path/to/\n sudo -u nginx ls -ld /path/\n\n # NixOS-specific: Web server users typically don't have access to /home by default\n # You may need to adjust the permissions or move the files to /var/www or similar\n ```\n\n2. **503 Service Unavailable**:\n - Verify the Node process is running (`pm2 list` or `ps aux | grep node`)\n - Check server logs for memory issues or crashes\n\n3. **CSRF Errors**:\n - Ensure the `ORIGIN` environment variable is correctly set\n - Check that form submissions include the correct CSRF token\n\n4. **Performance Issues**:\n - Enable compression in your web server\n - Check for memory leaks using Node.js profiling\n - Verify that static assets are served with proper cache headers\n\n5. **Missing Assets**:\n - Ensure your build process is complete\n - Check that the `/build/` and `/assets/` directories are correctly exposed\n"},{"id":"/docs/deployments/static/","title":"Static Site","description":"","url":"https://next.qwik.dev/docs/deployments/static/","content":"# Static Site Adapter\n\nQwik's Static Site adapter helps to generate static html files which can be easily deployed to any cloud providers.\n\n## Installation\n\nTo integrate the `ssg` adapter, use the `add` command:\n\n```shell\npnpm run qwik add ssg\n```\n\nAbove command will create a directory at project root named `adapters/ssg/vite.config.ts` with the below code.\n\n```ts title=\"adapters/ssg/vite.config.ts\"\nimport { ssgAdapter } from \"@qwik.dev/router/adapters/ssg/vite\";\nimport { extendConfig } from '@qwik.dev/router';\nimport baseConfig from '../../vite.config.ts';\n\nexport default extendConfig(baseConfig, () => {\n return {\n build: {\n ssr: true,\n rolldownOptions: {\n input: ['@qwik-router-config'],\n },\n },\n plugins: [\n ssgAdapter({\n origin: 'https://yoursite.qwik.dev',\n }),\n ],\n };\n});\n```\n\nRemember to change the `origin` in this file to your domain.\n\nNow, you can generate static site while using `Qwik`'s rich ecosystem, file based routing and many more.\n"},{"id":"/docs/deployments/vercel-edge/","title":"Vercel Edge Adapter and Middleware | Deployments","description":"","url":"https://next.qwik.dev/docs/deployments/vercel-edge/","content":"# Vercel Edge Adapter\n\nQwik Router Vercel Edge adapter allows you to connect Qwik Router to [Vercel Edge Functions](https://vercel.com/docs/concepts/functions/edge-functions).\n\n## Installation\n\nTo integrate the `vercel-edge` adapter, use the `add` command:\n\n```shell\npnpm run qwik add vercel-edge\n```\n\nIt will automatically install the required dependencies, including the [Vercel CLI](https://vercel.com/docs/cli).\n\nThe adapter will add a new `vite.config.ts` within the `adapters/` directory, and a new entry file will be created, such as:\n\n```shell\n`-- adapters/\n `-- vercel-edge/\n `-- vite.config.ts\n`-- src/\n `-- entry.vercel-edge.tsx\n```\n\nAdditionally, within the `package.json`, the `build.server` and `deploy` scripts will be updated.\n\n## Production build\n\nTo build the application for production, use the `build` command, this command will automatically run `build.server` and `build.client`:\n\n```shell\npnpm run build\n```\n\n[Read the full guide here](https://github.com/QwikDev/qwik/blob/main/starters/adapters/vercel-edge/README.md)\n\n## Dev deploy\n\nTo deploy the application for development:\n\n```shell\npnpm run deploy\n```\n\nNotice that you might need a [Vercel account](https://vercel.com/docs/concepts/get-started) in order to complete this step!\n\n## Production deploy\n\nAfter installing the integration the project is ready to be deployed to Vercel. However, you will need to create a git repository and push the code to it.\n\nPlease refer to the Vercel docs for more information on how to deploy your site: [Vercel docs](https://vercel.com/docs/concepts/deployments/overview)\n\n### Environment variables\n\nYou can access environment variables from Vercel like this `process.env['MY_ENV_VAR']`\n\n## Advanced\n\n### Vercel Edge Entry Middleware\n\nWhen the `vercel-edge` adapter is added, a new entry file will be created at `src/entry.vercel-edge.tsx`. Below is an example of using the built-in middleware within the entry file.\n\n```tsx title=\"src/entry.vercel-edge.tsx\"\nimport { createQwikRouter } from '@qwik.dev/router/middleware/vercel-edge';\nimport render from './entry.ssr';\n\nexport default createQwikRouter({ render });\n```\n\nThe compiled middleware will be built in the `.vercel/output` directory.\n\n### Vercel Edge Functions\n\n[Vercel Edge Functions](https://vercel.com/docs/concepts/functions/edge-functions) are deployed globally by default on Vercel's Edge Network and enable you to move server-side logic to the Edge, close to your visitor's origin.\n\nEdge Functions use the Vercel Edge Runtime, which is built on the same high-performance V8 JavaScript and WebAssembly engine that is used by the Chrome browser. By taking advantage of this small runtime, Edge Functions can have faster cold boots and higher scalability than Serverless Functions.\n\nEdge Functions run after the cache, and can both cache and return responses.\n\n### Drizzle with Vercel Edge Functions\n\nRunning Postgres on edge requires edge-compatible drivers since Postgres relies on Node.js APIs.\nWhen no adapter is used, the below errors might appear during the deployment process:\n```tsx\n`-- The Edge Function \"_qwik-router\" is referencing unsupported modules\n`-- Cannot bundle Node.js built-in \"node:events\" imported from \"node_modules\\postgres\\cf\\polyfills.js\"\n```\nLuckily, drizzle has a [section](https://orm.drizzle.team/learn/tutorials/drizzle-with-vercel-edge-functions#edge-compatible-driver) that can be followed to implement the right adapter of choice.\n"},{"id":"/docs/errors/","title":"Error Codes | Reference","description":"Reference for all Qwik internal error codes with descriptions and troubleshooting guidance.","url":"https://next.qwik.dev/docs/errors/","content":"# Qwik Error Codes\n\nIn production, Qwik logs compact error codes like `Code(Q8)` with a link to this page. Below is a description of every code, what triggers it, and how to fix it.\n\n## Q0\n\n**Error while serializing class or style attributes**\n\nQwik could not convert a `class` or `style` value to a string. Ensure you pass a string, an object, or an array — not a function or symbol.\n\n## Q1\n\n**Scheduler not found**\n\nInternal error: the Qwik scheduler was not available when an effect tried to run. This usually means the container was destroyed or never initialized. If you see this in application code, please file a bug.\n\n## Q2\n\n**track() received object, without prop to track**\n\nYou called `track(obj)` without specifying which property to track. Use `track(() => obj.prop)` or `track(signal)` instead.\n\n## Q3\n\n**Only primitive and object literals can be serialized**\n\nYou stored a value (class instance, function, DOM node, etc.) in state that Qwik needs to serialize. Move it behind a QRL (`$()`) or keep it in a non-serialized location. See [Serialization](</docs/(qwik)/concepts/resumable/#serialization>).\n\n## Q4\n\n**You can render over an existing q:container. Skipping render()**\n\n`render()` was called on an element that already hosts a Qwik container. Remove the existing container first, or render into a different element.\n\n## Q5\n\n**QRL is not a function**\n\nA QRL resolved to something other than a function. Make sure the `$`-suffixed expression exports a function, and that the optimizer is running.\n\n## Q6\n\n**Dynamic import not found**\n\nThe chunk file referenced by a QRL could not be loaded. This usually means a build artifact is missing or the base path is misconfigured. Rebuild your project and verify that all chunks are deployed.\n\n## Q7\n\n**Unknown type argument**\n\nInternal error: an unknown type was passed to a core utility. If you see this in application code, please file a bug.\n\n## Q8\n\n**Actual value for useContext() can not be found**\n\nYou called `useContext(id)` but no ancestor called `useContextProvider(id, value)`. Make sure the provider is above the consumer in the component tree, and that the context was used during SSR so its state was serialized.\n\n## Q9\n\n**Invoking 'use\\*()' method outside of invocation context**\n\nA `use*()` hook was called outside of a component or task scope. Hooks can only be called synchronously inside `component$`, `useTask$`, `useComputed$`, or similar Qwik entry points.\n\n## Q10\n\n**Calling a 'use\\*()' method outside 'component$(() => \\{ HERE \\})' is not allowed**\n\nSimilar to Q9 but more specific: you called a hook in a place that is not inside a `component$` body or another `use*` hook. Move the call into the component function. See [Use Method Rules](/docs/core/tasks.md#use-method-rules).\n\n## Q11\n\n**The provided Context reference is not a valid context created by createContextId()**\n\nThe value you passed to `useContext()` or `useContextProvider()` was not created with `createContextId()`. Make sure you are importing and passing the correct context object.\n\n## Q12\n\n**SsrError(tag)**\n\nAn error occurred during SSR while processing a specific JSX tag. Check the accompanying message for details about which element failed and why.\n\n## Q13\n\n**QRLs can not be resolved because it does not have an attached container**\n\nA QRL tried to resolve but has no container context. This happens when a QRL is used outside of a rendered Qwik tree. Ensure QRLs are created and used inside a Qwik container.\n\n## Q14\n\n**QRLs can not be dynamically resolved, because it does not have a chunk path**\n\nA QRL has no chunk information. This typically means the optimizer did not process the file. Ensure the Qwik Vite plugin is configured correctly.\n\n## Q15\n\n**The JSX ref attribute must be a Signal**\n\nYou passed a non-Signal value to the `ref` prop. Use `useSignal()` to create a ref: `const myRef = useSignal<Element>()`, then pass `ref={myRef}`.\n\n## Q16\n\n**Deserialization of data type is not implemented**\n\nInternal serialization error: an unknown type ID was encountered during deserialization. This may indicate a version mismatch between SSR and client code. Rebuild and redeploy.\n\n## Q17\n\n**Expected vnode for ref prop**\n\nInternal serialization error: a `ref` prop pointed to something other than a VNode during serialization. If you see this in application code, please file a bug.\n\n## Q18\n\n**Cannot allocate data type**\n\nInternal serialization error: an unknown type ID was encountered during allocation. This may indicate corrupted serialized state or a version mismatch. Rebuild and redeploy.\n\n## Q19\n\n**Missing root id**\n\nInternal serialization error: a root object has no assigned ID during serialization. If you see this in application code, please file a bug.\n\n## Q20\n\n**Serialization of data type is not implemented**\n\nAn object of an unsupported type was encountered during serialization. Only primitives, plain objects, arrays, Signals, Dates, URLs, RegExps, Maps, Sets, and explicitly serializable types can be serialized. See Q3 for guidance.\n\n## Q21\n\n**Serialization Error: Unvisited**\n\nInternal error: an object that should have been visited during the serialization walk was missed. If you see this in application code, please file a bug.\n\n## Q22\n\n**Missing QRL chunk**\n\nA QRL's chunk information was not available during serialization. This usually means the optimizer did not process the code correctly. Rebuild your project.\n\n## Q23\n\n**The value of the textarea must be a string**\n\nYou passed a non-string value to a `<textarea>`. Convert the value to a string, or use a signal that holds a string.\n\n## Q24\n\n**Unable to find q:container**\n\nQwik could not locate a `q:container` element. This happens when trying to resume or interact with a container that was not rendered or was removed from the DOM.\n\n## Q25\n\n**Element must have 'q:container' attribute**\n\nAn element was expected to have a `q:container` attribute but did not. This is an internal error — if you see it, please file a bug.\n\n## Q26\n\n**Unknown vnode type**\n\nInternal error: the VNode system encountered a node of an unknown type. If you see this in application code, please file a bug.\n\n## Q27\n\n**Materialize error: missing element**\n\nInternal error: the VNode system could not find an expected DOM element during materialization. This can happen if the DOM was modified externally (e.g., by a browser extension) between SSR and resumption.\n\n## Q28\n\n**Cannot coerce a Signal, use `.value` instead**\n\nYou used a Signal where a primitive was expected (e.g., string concatenation, comparison). Access the underlying value with `.value`: `mySignal.value` instead of `mySignal`.\n\n## Q29\n\n_This code is no longer used: `useComputed$` now supports async functions. See [Async computed values](/docs/core/state.md#async-computed-values)._\n\n## Q30\n\n**Qwik version already imported**\n\nTwo different versions or builds of Qwik were loaded on the server. Copies of the same version and build share their runtime state, but different ones cannot, which leads to subtle bugs. Make sure every Qwik library resolves to the same `@qwik.dev/core` version, for example with package manager overrides, and that a development build of your app does not load a library's production copy of Qwik.\n\n## Q31\n\n**WrappedSignal is read-only**\n\nYou tried to set `.value` on a signal that is derived (e.g., from a computed expression or a binding). Derived signals cannot be written to — write to the source signal instead.\n\n## Q32\n\n**Attribute value is unsafe for SSR**\n\nAn attribute value contained characters that are unsafe for server-side rendering (e.g., unescaped HTML). Sanitize the value before passing it as an attribute.\n\n## Q33\n\n**SerializerSymbol function returned rejected promise**\n\nA custom serializer (using `SerializerSymbol`) returned a rejected promise. Ensure your serializer's `serialize` function resolves successfully.\n\n## Q34\n\n**Cannot serialize function**\n\nA plain function (not wrapped in `$()`) was found in serializable state. Wrap it with `$()` to create a QRL, or move it out of serialized state and use a QRL reference instead.\n\n## Q35\n\n**Cannot read .value of a clientOnly async signal during SSR**\n\nYou accessed `.value` on an async signal with `clientOnly: true` during server-side rendering. Since `clientOnly` signals skip computation on the server, there is no value available. Provide an `initial` value in the options.\n\n## Q36\n\n**Invalid element name for SSR**\n\nAn element name contains characters that cannot be emitted safely during server-side rendering. Use a valid HTML, SVG, or custom element name.\n\n## Q37\n\n**Invalid serialized Promise dependency**\n\nA serialized Promise tried to resolve with another serialized Promise. Regenerate the state using Qwik's serializer instead of constructing the payload manually.\n\n## Q38\n\n**Invalid serialized Uint8Array payload**\n\nA serialized Uint8Array contained malformed base64 data. Regenerate the state using Qwik's serializer instead of constructing the payload manually.\n\n## Q39\n\n**Computed signal was disposed**\n\nA computation tried to track a dependency or resume execution after its signal was disposed. Check `abortSignal` after asynchronous work before tracking more dependencies.\n"},{"id":"/docs/glossary/","title":"Glossary","description":"Definitions of the key terms used in the Qwik documentation.","url":"https://next.qwik.dev/docs/glossary/","content":"# Glossary\n\n## Resumability\n\nQwik serializes application state and event listeners into the HTML during SSR, so the client continues exactly where the server stopped without re-running component code.\n\n## QRL\n\nA Qwik URL: a serializable, lazy reference to code — most commonly a `$`-wrapped function — that the browser preloads and runs only when it is actually needed.\n\n## VNode\n\nQwik's virtual node: a lightweight description of a rendered DOM node that the runtime uses to update output without re-running whole components.\n\n## Hydration\n\nThe step other frameworks run on the client to make server-rendered HTML interactive: they re-execute components and reattach listeners. Qwik avoids this by resuming from serialized state.\n\n## Hydration mismatch\n\nAn error in hydration-based frameworks when the client render produces different markup than the server sent, breaking listeners or layout. Qwik avoids it by resuming the existing DOM.\n\n## Serialization\n\nConverting application state, event listeners, and framework data structures into text embedded in the HTML, so the browser can resume from it instead of rebuilding everything in memory.\n\n## Lazy loading\n\nDownloading and running code only at the moment it is actually needed instead of up front. Qwik splits an app into many lazy-loadable chunks and the runtime fetches each one on demand.\n\n## SSR\n\nServer-side rendering: generating a page's HTML on the server so the user sees content immediately. Qwik serializes the app state into that HTML so the client can resume without re-rendering.\n\n## CSR\n\nClient-side rendering: building the page in the browser with JavaScript after load, so users wait on a blank shell until the bundle downloads and runs. The opposite trade-off from SSR.\n\n## Signal\n\nQwik's reactive state primitive, created with useSignal(). Reading a signal subscribes the surrounding code, so when its value changes only the exact DOM or task that depends on it updates.\n\n## Preloading\n\nFetching the JavaScript a user is likely to need next into the browser cache ahead of time, so it is already there when they interact. Qwik preloads bundles based on likely next interactions.\n\n## SSG\n\nStatic site generation: rendering pages to static HTML at build time rather than per request, so they can be served straight from a CDN with no running server. Qwik Router can prerender routes.\n\n## Optimizer\n\nQwik's build-time compiler (written in Rust) that splits components at every $ boundary into separate lazy-loadable chunks and generates the QRLs that reference them.\n\n## Streaming\n\nSending the HTML response to the browser in chunks as it is produced instead of waiting for the whole page. Qwik supports out-of-order streaming so slower sections don't block the rest.\n\n## Container\n\nA self-contained, independently resumable region of a Qwik app in the DOM. A single page can host several containers, each serialized and resumed on its own.\n\n## Reactivity\n\nHow Qwik tracks which signals and stores each piece of UI reads, so a state change updates only the exact DOM nodes or tasks that depend on it — with no whole-component re-render.\n\n## Content projection\n\nThe mechanism by which a component receives JSX content from its parent and projects it into designated Slot locations in its template, keeping parent and child rendering independent.\n\n## JSX\n\nA syntax for expressing component templates in Qwik by writing HTML-like markup directly in JavaScript, which the compiler transforms into function calls. JSX is just syntax — not a virtual DOM.\n\n## Immutable props\n\nThe constraint that props in Qwik components are shallowly immutable: primitive values cannot be reassigned once passed, though properties of objects and arrays can be modified.\n\n## Prop drilling\n\nThe pattern of passing data through a chain of intermediate components that don't use it themselves, only to reach a descendant that does. Context APIs solve this problem in Qwik.\n\n## Class binding\n\nThe ability to pass the class attribute an object mapping CSS class names to boolean conditions, so classes are applied only when their conditions are true.\n\n## dangerouslySetInnerHTML\n\nA Qwik prop for inserting raw HTML into the DOM (replacing innerHTML). Its deliberately alarming name warns that injecting untrusted HTML exposes the app to cross-site scripting (XSS).\n\n## Invalidate\n\nMarking a component or task to re-run or re-render because its tracked state changed. Qwik queues invalidated work and flushes it as a batch rather than synchronously.\n\n## Proxy\n\nA JavaScript Proxy object created by useStore() that wraps application state and automatically tracks which components and tasks read each property, creating fine-grained subscriptions.\n\n## Track\n\nA function passed to useTask$() and useVisibleTask$() that marks which signals, stores, or computed values should be watched. When tracked state changes, the task re-executes.\n\n## Subscription\n\nAn automatic relationship registered when a component or task reads a signal or store property, causing that component or task to re-execute or re-render when the property changes.\n\n## Scheduler\n\nQwik's internal system that queues and orders the execution of tasks, component renders, and DOM updates, batching related work for efficiency.\n\n## Paused state\n\nThe initial state of a Qwik container after server-side rendering, serialized with application state and event listeners ready to resume on the client. Marked by q:container=\"paused\" in HTML.\n\n## Resumed state\n\nThe active state of a Qwik container after the client deserializes the server-serialized state and listeners from the HTML and begins executing event handlers and tasks.\n\n## Qwikloader\n\nA tiny (~1 kb) inlined JavaScript runtime that sets up global event listeners and lazy-loads event handlers on demand by searching the DOM for QRL attributes and fetching the corresponding code chunks.\n\n## Out-of-order streaming segment\n\nA chunk of HTML sent independently during out-of-order streaming when a Pending boundary resolves asynchronously, allowing faster sections to reach the browser immediately without waiting for slower async content.\n\n## Serialization boundary\n\nA lexical scope boundary marked by a $ function wrapper where only serializable data can cross; trying to capture non-serializable values (like custom class instances) will cause a runtime error.\n\n## qwik/json script\n\nA script tag with type='qwik/json' that embeds the serialized application state, listeners, and component tree information into the HTML so the client can resume without re-running components.\n\n## DAG\n\nDirected acyclic graph: a tree structure with no circular references. JSON only serializes DAGs; Qwik overcomes this limitation by properly handling circular object references in application state.\n\n## Island architecture\n\nA technique where developers manually mark isolated interactive regions of an otherwise static page and choose when each island activates. Qwik avoids islands, resuming the whole app from serialized state.\n\n## Chunk\n\nA JavaScript file containing one or more lazy-loadable symbols. Qwik bundles related symbols together into chunks to balance download size and request overhead.\n\n## Bundle\n\nA compiled JavaScript file containing one or more symbols packaged together for delivery. Bundles are generated by Qwik's optimizer and downloaded by the browser on demand.\n\n## Entry point\n\nA file or location where the bundler begins processing code — typically the root component or library export. In Qwik, can refer to client entry, SSR entry, or bundler configuration entry.\n\n## Qwik Vite plugin\n\nThe Vite integration plugin (qwikVite()) that enables Qwik to automatically split components into lazy-loadable chunks and configure bundle optimization strategies.\n\n## Tree-shaking\n\nA bundler optimization that removes unreferenced code from the final bundle. Qwik's optimizer enables tree-shaking by breaking direct references between components into QRLs.\n\n## Library mode\n\nVite's build mode for creating reusable component libraries. Qwik libraries use it to export components as .qwik.mjs files that integrate with the Qwik optimizer.\n\n## Colocation\n\nPlacing related symbols together in the same bundle so they load together. Qwik's bundler groups symbols used together in the same chunk to minimize the number of download requests.\n\n## Service Worker\n\nA background JavaScript process that Qwik uses to prefetch bundles into the browser cache before user interactions, reducing latency when event handlers are needed.\n\n## Network Waterfall\n\nSequential, dependent requests where modules cannot start downloading until previous modules finish. Qwik reduces waterfalls via speculative prefetching and the manifest's import graph.\n\n## Eagerness\n\nThe timing strategy for when a qwikified React island or component should be downloaded and made interactive, such as on load, idle, visible, hover, or via a signal.\n\n## client: directives\n\nJSX attributes that control when a qwikified React component is downloaded and made interactive in the browser: client:load, client:idle, client:visible, client:hover, client:signal, client:event, or client:only.\n\n## Partytown\n\nA tool that moves third-party scripts like Google Analytics onto a web worker, preventing them from blocking the main thread during initial page load.\n\n## MPA\n\nMulti-page application: a traditional web app where each page navigation loads a fresh HTML page from the server. Qwik supports MPA navigation alongside SPA for maximum flexibility.\n\n## SPA\n\nSingle-page application: a web app that navigates without full page reloads by updating the DOM on the client. Qwik lets you choose SPA navigation per-link and maintains best-in-class scroll restoration.\n\n## SPA navigation\n\nClient-side page transition using the Link component or useNavigate() hook instead of a full page reload. In Qwik apps, users are automatically upgraded to SPA mode when using these methods.\n\n## Dynamic route\n\nA route with variable URL segments marked with square brackets, like [id] or [...slug], that match multiple URLs and extract values into params. Use dynamic routes for flexible patterns like /products/123.\n\n## Static route\n\nA route with a fixed URL path defined by directory names, like /docs/getting-started. Each static route matches only its exact pathname, unlike dynamic routes with variable segments.\n\n## Scroll restoration\n\nAutomatically returning the user to their previous scroll position when navigating back in history. Qwik provides best-in-class scroll restoration for SPA navigation based on browser history.\n\n## sharedMap\n\nA scoped Map available in request handlers that persists data across middleware functions and loaders for a single HTTP request. Useful for sharing authentication state or logging context between handlers.\n\n## cacheControl\n\nA convenience function in request handlers to set HTTP Cache-Control headers (maxAge, sMaxAge, staleWhileRevalidate, public/private). Controls how browsers and CDNs cache page responses.\n\n## Stale-while-revalidate\n\nA cache strategy that serves stale cached content to users immediately while revalidating it in the background. Enables instant page loads while keeping content fresh without the user waiting for revalidation.\n\n## XSS\n\nCross-site scripting: an attack where malicious code is injected into a webpage and runs in other users' browsers. CSP and output escaping help prevent XSS attacks.\n\n## CSRF\n\nCross-site request forgery: an attack that tricks a user into making an unintended request to a website where they're authenticated, often using hidden forms or image tags.\n\n## CSP\n\nContent Security Policy: an HTTP header that tells the browser which sources of scripts, styles, images, and other resources are trusted, helping prevent XSS and data injection attacks.\n\n## Nonce\n\nA random, unique token generated per request and added to CSP directives and inline scripts to allow only those specific scripts to run, blocking unauthorized inline code.\n\n## View Transition API\n\nA browser API that animates smooth visual transitions between page states, creating a native view-to-view animation without full page reloads.\n\n## FormData\n\nA built-in JavaScript interface for serializing form fields into key-value pairs, commonly used for multipart file uploads and programmatic form submission.\n\n## Popover\n\nAn HTML API that opens a floating box anchored to a trigger element in the top layer, supporting modal and non-modal popovers with automatic positioning and click-outside dismiss.\n\n## Top layer\n\nA special stacking context above all other page content where popovers, modals, and dialogs render to ensure they stay visible and receive focus without z-index conflicts.\n\n## prefers-color-scheme\n\nA CSS media query that detects whether the user prefers a dark or light color scheme at the OS level, enabling sites to match system appearance preferences.\n\n## AbortSignal\n\nA browser API that allows canceling asynchronous operations like fetch requests or timers, commonly used with AbortController to clean up in-flight requests on navigation or component unmount.\n\n## Adapter\n\nA Vite configuration plugin tailored to a specific hosting platform (Cloudflare, Netlify, Vercel, AWS Lambda, etc.) that handles build output format and server integration.\n\n## Edge functions\n\nCode that runs on a CDN's edge servers geographically close to visitors, enabling fast server-side logic execution without traditional server latency.\n\n## Serverless functions\n\nStateless, on-demand code execution (e.g. AWS Lambda) that scales automatically, where you pay only for the time code runs without managing servers.\n\n## Edge runtime\n\nA lightweight JavaScript execution environment (e.g. V8-based) running on edge servers that supports a subset of web APIs and prioritizes fast cold starts.\n\n## Cold start\n\nThe latency experienced when a serverless or edge function instance initializes for the first time, before executing user code.\n\n## Micro-frontend\n\nAn architecture pattern where multiple independent front-end applications run together in a single page, each managing its own functionality and lifecycle.\n\n## ORIGIN\n\nAn environment variable set to the site's origin (e.g. https://example.com/) for resolving relative URLs and validating request origins during CSRF protection.\n\n## Platform bindings\n\nNamed connections to cloud resources (KV stores, databases, buckets) configured on the hosting platform and accessed through the platform object in route handlers.\n"},{"id":"/docs/integrations/astro/","title":"Astro | Integrations","description":"Learn how to use Qwik inside an Astro project.","url":"https://next.qwik.dev/docs/integrations/astro/","content":"# Astro\n\n[Astro](https://astro.build/) is a flexible meta-framework that accommodates a wide range of tools and integrations, enabling you to leverage numerous ecosystems.\n\nIt also allows you to write components using your favorite UI framework (or no framework at all) and renders your pages to static HTML at build time, or dynamically on the server using Server-Side Rendering (SSR).\n\nThis results in a fast, SEO-friendly output that can be deployed to any static hosting environment or server.\n\nFor more details on the integration and to view the source code, check out the [QwikDev Astro Integration on GitHub](https://github.com/QwikDev/astro).\n\n## Astro instead of Qwik Router\n\nWhen integrating Astro with Qwik, it's important to note that Qwik Router APIs are not compatible with Astro.\n\nAstro is a meta-framework that provides its own set of APIs and features for handling these concerns.\nThese include but are not limited to:\n- routing\n- pages\n- layouts\n- data fetching\n\nWhen using Qwik with Astro, use Astro's APIs instead of Qwik Router's. This ensures your Qwik components work correctly in Astro. See the [Astro documentation](https://docs.astro.build) for more details.\n\n## @qwik.dev/astro This integration leverages the power of JavaScript Streaming inside of Astro, using Qwik components.\n\n## Installation\n\n### The `@qwik.dev/astro` CLI To start a new Qwik Astro project, you can run the following command:\n\n ```shell\n pnpm create @qwik.dev/astro\n ```\n\n For more advanced CLI configuration options, see the [@qwik.dev/astro CLI documentation](https://github.com/QwikDev/astro/blob/main/libs/create-qwikdev-astro/README.md).\n\n### Existing projects\n\nAstro comes with a command-line tool for incorporating built-in integrations: `astro add`. This command will:\n\n1. Optionally install all required dependencies and peer dependencies\n2. Optionally modify your `astro.config.*` file to apply the integration\n\nTo install `@qwik.dev/astro`, run the following from your project directory and follow the prompts:\n\n```shell\npnpm dlx astro add @qwik.dev/astro\n```\n\n### Setting up the TypeScript Config\n\nWhen using Astro's integration CLI or manually adding the integration, Qwik needs the following in `tsconfig.json` for typescript to recognize Qwik's JSX types.\n\n```ts\n\"compilerOptions\": {\n \"jsx\": \"react-jsx\",\n \"jsxImportSource\": \"@qwik.dev/core\"\n}\n```\n\nIf you face any issues, please [post them on Github](https://github.com/QwikDev/astro/issues) and attempt the manual installation below.\n\n### Manual Installation\n\nFirst, install the `@qwik.dev/astro` integration like so:\n\n```shell\npnpm install @qwik.dev/astro\n```\n\nTypically, package managers install peer dependencies. However, if you get a `Cannot find package '@qwik.dev/core'` warning when starting Astro, install Qwik.\n\n```shell\npnpm install @qwik.dev/core\n```\n\nNow, add the integration to your `astro.config.*` file using the `integrations` property:\n\n```diff lang=\"js\" \"qwikdev()\"\n // astro.config.mjs\n import { defineConfig } from 'astro/config';\n+ import qwikdev from '@qwik.dev/astro';\n\n export default defineConfig({\n // ...\n integrations: [qwikdev()],\n // ^^^^^\n });\n```\n\n### Learn More\n\nFor more documentation on using Qwik and Astro, the [integration README](https://github.com/QwikDev/astro) is a great place to start.\n"},{"id":"/docs/integrations/authjs/","title":"Auth.js | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/authjs/","content":"# Auth.js\n\n[Auth.js](https://authjs.dev/) is a well-known library for authentication used by various JS frameworks. With Auth.js, we benefit from reduced complexity. We also have access to a range of authentication providers, such as GitHub, Google, Facebook, among others. Moreover, it can be integrated into multiple frameworks including Qwik.\n\nAuth.js offers several features that enhance simplicity, productivity, flexibility, and provider diversity. Here are the main features of Auth.js:\n\n- **Providers**: Auth.js supports multiple providers, simplifying the authentication process in our applications (e.g., Github, Google, Facebook, Twitter). It also offers Single Sign-On (SSO) services as well as traditional authentication.\n- **Management**: Auth.js greatly assists us in concentrating on our business logic. It manages tokens, stores them, and refreshes them automatically.\n- **Configuration**: Configuring Auth.js is straightforward. It offers easy installation, error handling, custom forms for login and registration, and effortless integration with providers.\n- **Integrations**: Auth.js seamlessly integrates with JS frameworks, aided by its comprehensive documentation that provides a clear guide to follow.\n- **Security**: While Auth.js is developer-friendly, it's essential to recognize the underlying complexity that ensures a high level of security for our data.\n\nBe aware that the Auth.js library is still in a pre-1.0 stage and could have bugs.\n\n## Installation\n\nYou can add Auth.js easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add auth\n```\n\nThis command will add a new package:\n\n- `@auth/qwik`\n\nand create a new file named `plugin@auth.ts` with an example configuration.\n\n**Manual Deployments with Node**\n\nWhen deploying applications manually using Node.js, particularly with frameworks like Express, the server or Node process does not inherently know if it's being served under HTTP or HTTPS.\nUnlike hosting services like Vercel, Netlify, or Cloudflare, where the ORIGIN configuration is automatically managed, manual setups require explicit specification. To ensure that your Node.js application recognizes the correct protocol and host it is being served under, set the following **environment variables**:\n\n-\tORIGIN: Set this to the URL of your application. For example:\n\tORIGIN=https://your-app-name.example.com\n- PROTOCOL_HEADER: This is used to indicate the original protocol requested by the client. Commonly, this is specified in proxy configurations. Set this variable to:\n\tPROTOCOL_HEADER=X-Forwarded-Proto\n- HOST_HEADER: This header helps identify the original host requested by the client. It is particularly necessary when your Node environment is behind a proxy or load balancer. Set this variable to:\n\tHOST_HEADER=X-Forwarded-Host\n\n### Migrating from `@builder.io/qwik-auth`\n\nWhen migrating from `@builder.io/qwik-auth` to `@auth/qwik`, there are a couple changes that need to be made.\n\n1. The routes provided by the auth library are no longer prefixed with `/api`. If your are using previous guidance for protected routes or calling the auth routes directly, please be sure to update accordingly.\n\n ```diff\n export const onRequest: RequestHandler = (event) => {\n const session: Session | null = event.sharedMap.get('session');\n if (!session || new Date(session.expires) < new Date()) {\n - throw event.redirect(302, `/api/auth/signin?redirectTo=${event.url.pathname}`);\n + throw event.redirect(302, `/auth/signin?callbackUrl=${event.url.pathname}`);\n }\n };\n ```\n\n2. The setup function and methods exported by it have changed in `plugin@auth.ts`. Be sure to update the imports for the `useAuthSession`, `useAuthSignin`, and `useAuthSignout` methods anywhere you use them in your app.\n\n ```diff\n import Auth0Provider from \"@auth/core/providers/auth0\";\n -import { serverAuth$ } from \"@builder.io/qwik-auth\";\n +import { QwikAuth$ } from \"@auth/qwik\";\n\n -export const { onRequest, useAuthSession, useAuthSignin, useAuthSignout } =\n - serverAuth$(({ env }) => ({\n +export const { onRequest, useSession, useSignIn, useSignOut } =\n + QwikAuth$(({ env }) => ({\n ```\n3. Update your `vite.config.ts` to include `\"@auth/qwik\"` to avoid potentials import issues\n```diff\n export default defineConfig(({ command, mode }): UserConfig => {\n return {\n plugins: [qwikRouter(), qwikVite(), tsconfigPaths({ root: '.' })],\n // This tells Vite which dependencies to pre-build in dev mode.\n optimizeDeps: {\n include: [\"@auth/qwik\"],\n },\n```\n\n## Qwik API\n\n### useSession\n\nA [routeLoader$](/docs/route-loader.md) that returns a session object or an empty object if there is no session. The contents of the session object that is returned are configurable with the session callback. Session data can also be retrieved using the [session](#session) REST API.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { useSession } from '~/routes/plugin@auth';\n\nexport default component$(() => {\n const session = useSession();\n return <p>{session.value?.user?.email}</p>;\n});\n\n```\n\n### useSignIn\n\nA [routeAction$](/docs/action.md) used to initiate a signin flow or send the user to the signin page listing all possible providers. The CSRF token is handled internally when signing in using `useSignIn`.\n\n#### Parameters\n\n* `providerId`: An optional string parameter with the name of the provider. When supplied will initiate the Authorization Request to your Identity Provider. When omitted will redirect to the built-in/unbranded sign-in page.\n* `options`: An optional object of options.\n * `redirectTo`: An optional string specifying to which URL the user will be redirected after signing in. Defaults to the page URL the sign-in is initiated from.\n* `authorizationParams`: An optional object of additional parameters sent to the /authorize endpoint. See the Authorization Request OIDC spec for some ideas.\n\nYou can also set the `authorizationParams` through the provider.authorizationParams configuration\n\nExample using `useSignIn` with the [&lt;Form&gt;](/docs/action.md#using-actions-with-form) component and optional `providerId` and `options.redirectTo`:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Form } from '@qwik.dev/router';\nimport { useSignIn } from '~/routes/plugin@auth';\n\nexport default component$(() => {\n const signIn = useSignIn();\n return (\n <Form action={signIn}>\n <input type=\"hidden\" name=\"providerId\" value=\"github\" />\n <input type=\"hidden\" name=\"options.redirectTo\" value=\"http://qwik-auth-example.com/dashboard\" />\n <button>Sign In</button>\n </Form>\n );\n});\n```\n\nExample using `useSignIn` programmatically with optional `providerId` and `options.redirectTo`:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { useSignIn } from '~/routes/plugin@auth';\n\nexport default component$(() => {\n const signIn = useSignIn();\n return (\n <button onClick$={() => signIn.submit({ providerId: 'github', options: { redirectTo: 'http://qwik-auth-example.com/dashboard' } })}>Sign In</button>\n );\n});\n```\n\n### useSignOut\n\nA [routeAction$](/docs/action.md) used to initiate a signout flow. The user session will be invalidated/removed from the cookie/database, depending on the flow you chose to store sessions.\n\n#### Parameters\n\n* `redirectTo`: An optional string specifying to which URL the user will be redirected after signing out. Defaults to the page URL the sign-in is initiated from.\n\nThe 'redirectTo' must be considered valid by the redirect callback handler. By default, it requires the URL to be an absolute URL at the same host name, or you can also supply a relative URL starting with a slash. If it does not match it will redirect to the homepage. You can define your own redirect callback to allow other URLs.\n\nExample using `useSignOut` with the [&lt;Form&gt;](/docs/action.md#using-actions-with-form) component and optional `redirectTo`:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Form } from '@qwik.dev/router';\nimport { useSignOut } from '~/routes/plugin@auth';\n\nexport default component$(() => {\n const signOut = useSignOut();\n return (\n <Form action={signOut}>\n <input type=\"hidden\" name=\"redirectTo\" value=\"/signedout\" />\n <button>Sign Out</button>\n </Form>\n );\n});\n```\n\nExample using `useSignOut` programmatically with optional `redirectTo`:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { useSignOut } from '~/routes/plugin@auth';\n\nexport default component$(() => {\n const signOut = useSignOut();\n return <button onClick$={() => signOut.submit({ redirectTo: '/signedout' })}>Sign Out</button>;\n});\n```\n\n## REST API\n\nAll the same REST APIs as provided by Auth.js are available.\n\n### signin\n\n**GET /auth/signin**\n\nDisplays the built-in/unbranded sign-in page.\n\n**POST /auth/signin/:provider**\n\nStarts a provider-specific sign-in flow. In the case of an OAuth provider, calling this endpoint will initiate the Authorization Request to your Identity Provider. This endpoint is also used by the [useSignIn](#useSignIn) action internally.\n\n### callback\n\n**GET/POST /auth/callback/:provider**\n\n### signout\n\n**GET /auth/signout**\n\nDisplays the built-in/unbranded sign out page.\n\n**POST /auth/signout**\n\nHandles signing the user out - this is a POST submission to prevent malicious links from triggering signing a user out without their consent. The user session will be invalidated/removed from the cookie/database, depending on the flow you chose to store sessions. This endpoint is also used by the [useSignOut](#useSignOut) method internally.\n\n### session\n\n**GET /auth/session**\n\nReturns client-safe session object - or an empty object if there is no session. The contents of the session object that is returned are configurable with the session callback. Session data can also be retrieved using the [useSession](#useSession) routerLoader.\n\n### csrf\n\n**GET /auth/csrf**\n\nReturns object containing CSRF token. In NextAuth.js, CSRF protection is present on all authentication routes. It uses the \"double submit cookie method\", which uses a signed HttpOnly, host-only cookie. The CSRF token returned by this endpoint must be passed as form variable named csrfToken in all POST submissions to any API endpoint.\n\n### providers\n\n**GET /auth/providers**\n\nReturns a list of configured OAuth services and details (e.g. sign in and callback URLs) for each service. It is useful to dynamically generate custom sign up pages and to check what callback URLs are configured for each OAuth provider that is configured.\n\n## Examples\n\n### GitHub\n\n1. Follow the [GitHub OAuth Guide](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app) to get your `GitHub Client ID`, `GitHub Client Secrets` and generate `AUTH_SECRET` using `openssl rand -base64 32` or [Secret Generator](https://generate-secret.vercel.app/32).\n2. Since the default `plugin@auth.ts` uses GitHub as an example, we don't need to change anything there. However a provider other than GitHub could be used or additional provides could be added. Auth.js also supports many [additional options](https://next-auth.js.org/configuration/options#options) that can be set in this file.\n\n```ts title=\"src/routes/plugin@auth.ts\"\nimport { QwikAuth$ } from \"@auth/qwik\";\nimport GitHub from \"@auth/qwik/providers/github\";\n\nexport const { onRequest, useSession, useSignIn, useSignOut } = QwikAuth$(\n () => ({\n providers: [GitHub],\n }),\n);\n```\n\n**IMPORTANT**\nMake sure to keep the `onRequest` export as it is used to handle the OAuth flow redirects. Once the user finished OAuth flow, GitHub (or any other provider) will redirect the user back to the application to `/auth/callback/github` (or `/auth/callback/[otherProvider]`). The `onRequest` middleware function will handle requests to this endpoint and finish the OAuth flow.\n\n3. Create or edit the `.env.local` file at the root of your project to store secrets\n\n```bash title=\".env.local\"\nAUTH_GITHUB_ID=\nAUTH_GITHUB_SECRET=\nAUTH_SECRET=\n```\n\n**IMPORTANT**\nPlease read the Qwik documentation about [Environment Variables](/docs/guides/env-variables.md) to ensure you are using them safely. Many provider secrets should be kept secure and not exposed to the client/browser.\n\n4. The application is now ready to implement authentication using Auth.js.\n5. Enjoy!\n\n### Credentials\n\n**Warning: Credentials Authentication**\n\nThis functionality is discouraged by Auth.js.\n\nhttps://next-auth.js.org/providers/credentials\n\n- The functionality provided for credentials based authentication is intentionally limited to discourage use of passwords due to the inherent security risks associated with them and the additional complexity associated with supporting usernames and passwords.\n\n1. Since the default `plugin@auth.ts` uses GitHub as an example, we need to replace it with Credentials.\n\n```ts title=\"src/routes/plugin@auth.ts\"\nimport { QwikAuth$ } from \"@auth/qwik\";\nimport Credentials from \"@auth/qwik/providers/credentials\";\n\nexport const { onRequest, useSession, useSignIn, useSignOut } = QwikAuth$(\n () => ({\n providers: [\n Credentials({\n async authorize(credentials, req) {\n // Add logic here to look up the user from the credentials supplied\n const user = {\n id: 1,\n name: \"Mike\",\n email: \"mike@example.com\",\n };\n\n return user;\n },\n }),\n ],\n }),\n);\n```\n\n2. Create or edit the `.env.local` file at the root of your project to store secrets\n\n```bash title=\".env.local\"\nAUTH_SECRET=\n```\n\n**IMPORTANT**\nPlease read the Qwik documentation about [Environment Variables](/docs/guides/env-variables.md) to ensure you are using them safely. Many provider secrets should be kept secure and not exposed to the client/browser.\n\n3. The application is now ready to implement authentication using Auth.js.\n4. Enjoy!\n\n### Route Protection\n\nSession data can be accessed via the route `event.sharedMap`. So a route can be protected and redirect using something like this located in a `layout.tsx` or page `index.tsx`:\n\n```tsx\nexport const onRequest: RequestHandler = (event) => {\n const session: Session | null = event.sharedMap.get('session');\n if (!session || new Date(session.expires) < new Date()) {\n throw event.redirect(302, `/auth/signin?callbackUrl=${event.url.pathname}`);\n }\n};\n```\n\nIf placed in a layout.tsx ensure that the redirect destination does not share the same layout.tsx or a redirection loop could occur.\n"},{"id":"/docs/integrations/bootstrap/","title":"Bootstrap | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/bootstrap/","content":"# Bootstrap\n\nBootstrap is a robust, expandable, and feature-rich frontend toolkit that includes HTML, CSS, and JavaScript. You can build and customize using Sass, benefit from a predefined grid system and components, and enhance your projects with powerful JavaScript plugins.\n\nMore information at [https://getbootstrap.com/](https://getbootstrap.com/)\n\n## Usage\n\nYou can add Bootstrap easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add bootstrap\n```\n\nThe previous command updates your app with the necessary dependencies.\n\n- `bootstrap@5`\n- `@types/bootstrap@5`\n\nIt also adds new files inside to your project folder:\n\n- `src/models/bootstrap.ts`: Model to define Bootstrap components info to use in props.\n- `src/constants/data.ts`: Constant values information that we will use in the example to be created with this integration.\n- `src/components/bootstrap/button.tsx`: Button component feature with Bootstrap.\n- `src/components/bootstrap/alert.tsx`: Alert component feature with Bootstrap.\n- `src/components/bootstrap/spinner.tsx`: Spinner component feature with Bootstrap.\n- `src/components/bootstrap/index.ts`: Entry point where we will add the components of the elements that will be used, for easier and cleaner access to them.\n- `src/components/bootstrap/navbar.tsx`: Navbar component functionality with Bootstrap to demonstrate how to add and use JavaScript functionalities without encountering the 'document is not defined' error due to improper import declaration in the Qwik lifecycle.\n- `src/routes/bootstrap/layout.tsx`: Layout where we add Bootstrap styling configuration to ensure styles are applied to all routes nested within the main Bootstrap route.\n- `src/routes/bootstrap/index.tsx`: Bootstrap components option home page.\n- `src/routes/bootstrap/buttons/index.tsx`: Example to consume Button component with demo data.\n- `src/routes/bootstrap/alerts/index.tsx`: Example to consume Alert component with demo data.\n- `src/routes/bootstrap/spinners/index.tsx`: Example to consume Spinner component with demo data.\n\n## After integrating Bootstrap\n\nAfter integrating Bootstrap, you can access the /bootstrap/ route where you will find all the examples available for this integration.\n\n## Interesting info about Bootstrap\n\n### Official\n\n- `Examples`: Examples that we can use as inspiration and learn how to create interesting websites using Bootstrap. [Reference](https://getbootstrap.com/docs/5.3/examples/).\n- `Docs`: All necessary info to work with Bootstrap. [Reference](https://getbootstrap.com/docs/5.3/getting-started/introduction/)\n"},{"id":"/docs/integrations/builderio/","title":"Builder.io | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/builderio/","content":"# Builder.io\n\n[Builder.io](https://builder.io/) is a Visual Headless CMS. Think about it as a drag-and-drop CMS that integrates into your existing Qwik codebase, allowing you and your team to edit content without having to write code.\n\n## Setup\n\nYou can add builder.io easily by using the following `add` script:\n\n```shell\npnpm run qwik add builder.io\n```\n\nAfter running the command, `@builder.io/sdk-qwik` will be installed, and a new sample component and catchall route will be created in `src/components` and `src/routes` respectively.\n\nCreate a free [Builder.io account](https://builder.io/signup) (only takes a couple minutes), and paste your [public API key](https://www.builder.io/c/docs/using-your-api-key) into `.env`\n\n```diff\n- BUILDER_PUBLIC_API_KEY=YOUR_API_KEY\n+ BUILDER_PUBLIC_API_KEY=abc123\n```\n\nThen run the development server:\n\n```shell\npnpm run dev\n```\n\nNow, go set your [preview URL](https://www.builder.io/c/docs/guides/preview-url) to `http://localhost:5173/`\n\n1. Go to [https://builder.io/models](https://builder.io/models)\n2. Choose the `page` model\n3. Set the preview URL to `http://localhost:5173/` and click `save` in the top right\n\nNow, let's create a page in Builder.io and see it live in Qwik!\n\n1. Go to [https://builder.io/content](https://builder.io/content)\n2. Click `+ New` and choose `Page`\n3. Give it a name and click `Create`\n\nNow, try out the visual editor! You can find a custom Qwik components\nin the `Custom Components` section of the insert tab.\n\nYou may also limit visual editing to only your custom components with [components-only mode](https://www.builder.io/c/docs/guides/components-only-mode).\n\n## Register your components\n\nOne of the killer features of a Visual Headless CMS, is that you can [expose your components](https://www.builder.io/c/docs/custom-components-setup) to the CMS, ie, your Qwik components can be used as blocks in Builder.io.\n\n```tsx\nimport { MyFunComponent } from './fun/fun';\n\nexport const CUSTOM_COMPONENTS: RegisteredComponent[] = [\n {\n component: MyFunComponent,\n name: 'MyFunComponent',\n inputs: [\n {\n name: 'text',\n type: 'string',\n defaultValue: 'Hello world',\n },\n ],\n },\n];\n\nexport default component$(() => {\n const content = useBuilderContent();\n return (\n <RenderContent\n customComponents={CUSTOM_COMPONENTS}\n />\n );\n});\n```\n\n## Next Steps\n\nSee our full integration guides [here](https://www.builder.io/c/docs/developers)\n\nAlso, when you push your integration to production, go back and update your preview URL to your production URL so now anyone on your team can visually create content in your Qwik app!\n\nAlso, to integrate structured data, see [this guide](https://www.builder.io/c/docs/integrate-cms-data)\n"},{"id":"/docs/integrations/cypress/","title":"Cypress | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/cypress/","content":"# Cypress\n\nWith [Cypress](https://www.cypress.io), you can easily create tests for your modern web applications, debug them visually, and automatically run them in your continuous integration builds.\n\n## Component testing\n\nCypress enables you to test your Qwik components\nin isolation with the help of the [cypress-ct-qwik](https://github.com/qwikifiers/cypress-qwik) community plugin.\n\n## Usage\n\nYou can add Cypress easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add cypress\n```\n\nThis command adds `cypress` and `cypress-ct-qwik` to your dependencies, appends testing commands to your `package.json`\nscripts section and creates the configuration files needed to run component testing with Cypress.\n\nFor further reference, please check the [Cypress documentation](https://docs.cypress.io/guides/overview/why-cypress) and the [cypress-qwik documentation](https://github.com/qwikifiers/cypress-qwik).\n"},{"id":"/docs/integrations/drizzle/","title":"Drizzle | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/drizzle/","content":"# Drizzle\n\n[Drizzle ORM](https://orm.drizzle.team/) is a headless TypeScript ORM with a head Using Drizzle you can define & manage database schemas in TypeScript, access your data in a SQL-like or relational way, and take advantage of opt in tools to push your developer experience through the roof While also being usable in serverless environments\n\nDrizzle can be used in Qwik with `routeLoader$`, `routeAction$` and `server$` functions. These are Qwik APIs to allow code to execute only on the server-side.\n\nThe easiest way to add Drizzle to Qwik is using the Qwik CLI command. This will install the required dependencies and create a `db` folder with the drizzle schema.\n\n```shell\npnpm run qwik add drizzle\n```\n\nDrizzle is an ORM that embraces SQL. Unlike other ORMs, it doesn't deviate from SQL, eliminating the double learning curve of SQL and the framework's API. If you know SQL, you can easily use Drizzle to its full potential.\n\n## Listing all the users\n\nWe will use `routeLoader$` to query all users in the DB, using `db.query.users.findMany()`, and returning the result.\n\n```tsx {7} /Drizzle/ title=\"src/routes/users/index.tsx\"\nimport { component$ } from \"@qwik.dev/core\";\nimport { routeLoader$ } from \"@qwik.dev/router\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport { schema } from \"../../../drizzle/schema\";\n\nexport const useGetUsers = routeLoader$(async () => {\n const sqlite = new Database(\"./drizzle/db/db.sqlite\");\n const db = drizzle(sqlite, { schema });\n const users = await db.query.users.findMany();\n return users;\n});\n\nexport default component$(() => {\n const users = useGetUsers();\n return (\n <section>\n <h1>User's directory</h1>\n <ul>\n {users.value.map((user) => (\n <li key={user.id}>\n <a href={`/users/${user.id}`}>\n {user.name} ({user.email})\n </a>\n </li>\n ))}\n </ul>\n </section>\n );\n});\n\n```\n\n## Show user detail\n\nWe will use `routeLoader$` to query specific users based on the `userId` URL param, using `db.query.users.findFirst({ where: (users, { eq }) => eq(users.id, userId), })`, and returning the result.\n\n```tsx {8} /Drizzle/ title=\"src/routes/users/[userId]/index.tsx\"\nimport { component$ } from \"@qwik.dev/core\";\nimport { routeLoader$ } from \"@qwik.dev/router\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport { schema } from \"../../../../drizzle/schema\";\n\nexport const useGetUser = routeLoader$(async (requestEvent) => {\n const userId = parseInt(requestEvent.params[\"userId\"], 10);\n const sqlite = new Database(\"./drizzle/db/db.sqlite\");\n const db = drizzle(sqlite, { schema });\n const user = await db.query.users.findFirst({\n where: (users, { eq }) => eq(users.id, userId),\n });\n if (!user) {\n // Set the status to 404 if the user is not found\n requestEvent.status(404);\n }\n return user;\n});\n\nexport default component$(() => {\n const user = useGetUser();\n return (\n <section>\n <h1>User detail</h1>\n {user.value ? (\n <>\n <p>Name: {user.value.name}</p>\n <p>Email: {user.value.email}</p>\n </>\n ) : (\n <p>User not found</p>\n )}\n </section>\n );\n});\n\n```\n\n## Adding a user\n\nWe will use `routeAction$` and `Form` to create a progressive form to add a new user to the DB. We will use `db.insert(schema.users).values(data)` to create the user.\n\n```tsx {7-9} /Drizzle/ title=\"src/routes/create/index.tsx\"\nimport { component$ } from \"@qwik.dev/core\";\nimport { routeAction$, Form } from \"@qwik.dev/router\";\nimport { zod$, z } from \"@qwik.dev/utils\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport { schema } from \"../../../drizzle/schema\";\nexport const useCreateUser = routeAction$(\n async (data) => {\n const sqlite = new Database(\"./drizzle/db/db.sqlite\");\n const db = drizzle(sqlite, { schema });\n const user = await db.insert(schema.users).values(data);\n return user;\n },\n zod$({\n name: z.string(),\n email: z.string().email(),\n }),\n);\n\nexport default component$(() => {\n const createUserAction = useCreateUser();\n return (\n <section>\n <h1>Create User</h1>\n <Form action={createUserAction}>\n <label>\n Name\n <input name=\"name\" value={createUserAction.formData?.get(\"name\")} />\n </label>\n <label>\n Email\n <input name=\"email\" value={createUserAction.formData?.get(\"email\")} />\n </label>\n <button type=\"submit\">Create</button>\n </Form>\n {createUserAction.value && (\n <div>\n <h2>User created successfully!</h2>\n </div>\n )}\n </section>\n );\n});\n\n```\n"},{"id":"/docs/integrations/formisch/","title":"Formisch | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/formisch/","content":"# Formisch\n\n[Formisch](https://formisch.dev/) is a schema-based, headless form library for Qwik. It manages form state and validates your fields with a [Valibot](https://valibot.dev/) schema. The headless design gives you full control over the visual appearance of your form.\n\n> Formisch requires Qwik v2, which is currently in beta. If you are using Qwik v1, use [Modular Forms](/docs/integrations/modular-forms.md), its predecessor by the same author.\n\nTo get started, install the `@formisch/qwik` and `valibot` packages:\n\n```shell\npnpm install @formisch/qwik valibot\n```\n\n## Define your form\n\nInstead of a separate type definition, in Formisch your Valibot schema is the single source of truth. It defines the structure of your form, validates your fields and infers the TypeScript types of your input and output values.\n\n```ts\nimport * as v from 'valibot';\n\nconst LoginSchema = v.object({\n email: v.pipe(\n v.string(),\n v.nonEmpty('Please enter your email.'),\n v.email('The email address is badly formatted.'),\n ),\n password: v.pipe(\n v.string(),\n v.nonEmpty('Please enter your password.'),\n v.minLength(8, 'Your password must have 8 characters or more.'),\n ),\n});\n```\n\n## Create a form\n\nTo create a form, you use the [`useForm$`](https://formisch.dev/qwik/api/useForm$/) hook. It initializes and returns the store of your form, which you pass to the other Formisch components and methods.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { Field, Form, useForm$ } from '@formisch/qwik';\n\nexport default component$(() => {\n const loginForm = useForm$(() => ({\n schema: LoginSchema,\n }));\n\n return <Form of={loginForm}>…</Form>;\n});\n```\n\n## Add form fields\n\nWith the [`Field`](https://formisch.dev/qwik/api/Field/) component you connect a field to your form. It is headless and provides you direct access to its current state via the `render$` prop. The path to the field is type-safe and autocompleted based on your schema. Spread `field.props` onto an `<input />`, `<select />` or `<textarea />` element to connect it to your form.\n\n```tsx\n<Form of={loginForm}>\n <Field\n of={loginForm}\n path={['email']}\n render$={(field) => (\n <div>\n <input {...field.props} value={field.input.value} type=\"email\" />\n {field.errors.value && <div>{field.errors.value[0]}</div>}\n </div>\n )}\n />\n <Field\n of={loginForm}\n path={['password']}\n render$={(field) => (\n <div>\n <input {...field.props} value={field.input.value} type=\"password\" />\n {field.errors.value && <div>{field.errors.value[0]}</div>}\n </div>\n )}\n />\n <button type=\"submit\">Login</button>\n</Form>\n```\n\nThis API design results in a fully type-safe form. Furthermore, it gives you full control over the user interface. You can develop your own input components or connect a pre-built component library.\n\n## Handle submission\n\nTo process the values when the form is submitted, pass a function to the `onSubmit$` property of the [`Form`](https://formisch.dev/qwik/api/Form/) component. The first parameter contains the validated values, typed according to the output of your schema.\n\n```tsx\nimport { $, component$ } from '@qwik.dev/core';\nimport { Field, Form, type SubmitHandler, useForm$ } from '@formisch/qwik';\n\nexport default component$(() => {\n const loginForm = useForm$(() => ({\n schema: LoginSchema,\n }));\n\n const handleSubmit = $<SubmitHandler<typeof LoginSchema>>((output) => {\n // Process the validated values\n });\n\n return (\n <Form of={loginForm} onSubmit$={handleSubmit}>\n …\n </Form>\n );\n});\n```\n\nWhile the form is being submitted, you can use `loginForm.isSubmitting.value` to display a loading state and disable the submit button.\n\n## Summary\n\nYou now know the basic building blocks of Formisch. For more details on nested fields, field arrays and the available form methods, see the [documentation](https://formisch.dev/qwik/guides/introduction/). You can also try Formisch in the [playground](https://formisch.dev/playground/login/).\n"},{"id":"/docs/integrations/i18n/","title":"Internationalization | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/i18n/","content":"# Internationalization\n\nInternationalization is a complex problem. Qwik does not solve the internationalization problem directly instead it only provides low-level APIs to allow other libraries to solve it.\n\n## Runtime vs compile time translation\n\nAt a high level there are two ways in which the translation problem can be solved:\n\n- Runtime: load a translation map and look up the translations at runtime.\n- Compile time: Have a compile step inline the translations into the output string.\n\nBoth of the above approaches have trade-offs that one should take into consideration.\n\nThe advantages of runtime approaches are:\n\n- Simplicity. Does not require an additional build step.\n\nDisadvantages of the runtime approach are:\n\n- Each string is present in triplicate:\n 1. Once as the original string in the code.\n 2. Once as a key in a translation map.\n 3. Once as a translated value in the translation map.\n- The tools currently lack the capability to break up the translation map. The whole translation map must be loaded eagerly on application startup. This is a less than ideal situation because it works against Qwik's effort to break up and lazy load your codebase. Additionally, because translation maps are not broken up, the browser will download unnecessary translations. For example, translations for static components that will never re-render on the client.\n- There is a runtime cost to translation lookups.\n\nThe advantages of compile-time approaches are:\n\n- Qwik's lazy loading of code now extends to the lazy loading of translation strings. (No unnecessary translation text is loaded)\n- No runtime translation map means strings are not in triplicate.\n\nDisadvantages of compile time approaches are:\n\n- Extra build step.\n- Changing languages requires a page reload.\n\n## Recommendation\n\nWith the above in mind, Qwik recommends that you use a tool that best fits your constraints. To help you make a decision there are three different considerations: Browser, Server, and Development.\n\n### Browser\n\nQwik's goal is to deliver the best possible user experience. It achieves this by deferring the loading of code to later so that the initial startup performance is not overwhelmed. Because the runtime approach requires eager loading of all translations, we don't recommend this approach. We think that the compile-time approach is best for the browser.\n\n### Server\n\nThe server does not have the constraint of lazy loading. For this reason, the server can use either the runtime or compiled approach. The disadvantage of compile time approach on the server is that we need to have a separate deployment for each translation. This complicates the deployment process as well as puts greater demand on the number of servers. For this reason, we think the runtime approach is preferable on the server.\n\n### Development\n\nDuring development, fewer build steps will result in a faster turnaround. For this reason, runtime translation should result in a simpler development workflow.\n\n### Our Recommendation\n\nOur recommendation is to use a tool that would provide a runtime approach on the server, and runtime or compile time on the client depending on whether we are in development or production. This way it is possible to prove the best user experience and development experience, and use the least server resources.\n\n## Internationalization Libraries\n\n### Paraglide JS\n\n[Paraglide JS](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) is a compile-time translation library that generates type-safe translation functions from standard message format messages.\n\n#### Advantages\n- **Tiny Runtime Overhead**: Translations are compiled to trivial functions.\n- **Framework Agnostic**: Can be used with various frameworks, even within the same project.\n- **Type-Safe Translations**: Generates type-safe functions for translations, reducing runtime errors\n- **Lazy Loading**: Only the translations used by the application are bundled, optimizing bundle size.\n- **Standard Message Format**: Supports complex message formatting using the widely adopted ICU message format.\n- **Developed ecosystem**: Part of the inlang ecosystem, which provides additional tools and integrations for managing translations.\n#### Disadvantages\n- **Ships all languages**: The translations for all languages are included in the single build output, which may increase the overall bundle size.\n- **No runtime features**: Lacks the possibility to add messages at runtime.\n\n#### Installation\nThe easiest way to add Paraglide JS to Qwik is by following the [official guide for Vite](https://inlang.com/m/gerre34r/library-inlang-paraglideJs/vite).\n\nFor further features like language switching and automatic translations, check the [documentation](https://inlang.com/m/gerre34r/library-inlang-paraglideJs).\n\n#### Usage\nUse the generated functions in your code:\n\n```tsx\nimport * as m from './src/paraglide/messages'\nimport { component$ } from '@builder.io/qwik';\n\nexport default component$(() => {\n return <p>{m.hello({name: 'World'})}</p>\n})\n```\n\n### compiled-i18n\n\n[compiled-i18n](https://github.com/wmertens/compiled-i18n) is inspired by the $localize system from Angular. It only requires a plugin to be added to the Vite configuration.\n\nIt supports both runtime and compile-time translations.\n\n#### Advantages\n- **Zero Runtime Overhead (Compile-time mode)**: Translations are inlined at build time, resulting in no runtime cost for lookups.\n- **Simplicity**: Minimal setup. Simple template string function API.\n- **Framework Agnostic**: Can be used with various frameworks, even within the same project.\n- **Flexible Approach**: Supports both runtime and compile-time modes, allowing developers to choose based on their needs.\n- **Per-locale builds**: Compile-time mode inlines translations, eliminating runtime lookups. Server code includes all languages, simplifying deployment.\n- **Automatic extraction**: Automatically adds new keys to translation files during build, and warns about missing and/or unused translations.\n\n#### Disadvantages\n- **Per-locale builds**: Compile-time mode requires separate builds for each locale, complicating deployment.\n\n#### Installation\nRun `npx qwik add compiled-i18n` to add compiled-i18n to your Qwik app.\n\nSee the [Qwik-specific instructions](https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md) for more details.\n\nAutomatic translation is supported via [deepl-localize](https://github.com/tzdesign/deepl-localize).\n\nFor further explanation of the API and features like pluralization, check the [documentation](https://github.com/wmertens/compiled-i18n/blob/main/Readme.md).\n\n#### Usage\nUse the template string function anywhere in your code:\n\n```tsx\nimport {_} from 'compiled-i18n'\n\nconsole.log(_`Logenv ${process.env.NODE_ENV}`)\n\nexport const Count = ({count}) => (\n\t<div title={_`countTitle`}>{_`${count} items`}</div>\n)\n```\n\n### qwik-speak\n\n[qwik-speak](https://github.com/robisim74/qwik-speak) library to translate texts, dates and numbers in Qwik apps.\n\n#### Advantages\n- **Runtime Flexibility**: Allows dynamic language switching without page reloads, improving user experience.\n- **Qwik-Optimized**: Deep integration with Qwik's reactivity system and serialization.\n- **Rich Features**: Supports advanced formatting including dates, numbers, Pluralization, and ICU message format.\n\n#### Disadvantages\n- **Runtime Overhead**: Requires loading translation maps at runtime, which can increase bundle size and initial load time.\n- **Limited Compiler Benefits**: Doesn't provide the same compile-time optimizations and tree-shaking as pure compile-time solutions.\n\n#### Installation\n\nThe easiest way to add qwik-speak to Qwik is following the official [guide](https://github.com/robisim74/qwik-speak/blob/main/docs/quick-start.md).\n\n#### Usage\n\n```tsx\nimport { component$, useStore } from '@builder.io/qwik';\nimport { Speak, useSpeakContext } from 'qwik-speak';\n\nexport default component$(() => {\n const speak = useSpeakContext();\n const state = useStore({ count: 0 });\n\n return (\n <Speak>\n <div>\n <h1>{speak.t('helloWorld')}</h1>\n <p>{speak.t('itemCount', { count: state.count })}</p>\n <button onClick$={() => state.count++}>\n {speak.t('increment')}\n </button>\n </div>\n </Speak>\n );\n});\n```\n"},{"id":"/docs/integrations/icons/","title":"Icons | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/icons/","content":"# Icons\n\nIcons are an important part of any application. There are already more than 180.000 icons you can add to your Qwik app.\n\n## `qwikest/icons`\n\nThis package allows for a streamlined way to add icons to your Qwik app from a variety of icon sets.\n\n- `Bs`: Bootstrap Icons\n- `Go`: Octicons by GitHub\n- `Hi`: Heroicons by Tailwind\n- `In`: Iconoir\n- `Io`: Ionicons by Ionic\n- `Lu`: Lucide [superset of feather icons]\n- `Mo`: Mono Icons\n- `Si`: Simple Icons [icons for popular brands]\n- `Tb`: Tabler Icons\n\nSimply install the package with your package manager of choice:\n\n```shell\npnpm install @qwikest/icons\n```\n\n### Usage\n\n```tsx\nimport { LuRocket } from \"@qwikest/icons/lucide\";\n\nexport const MyComponent = component$(() => {\n // Icon size and color are inherited by default return (\n <div style={{ color: \"red\", fontSize: \"40px\" }}>\n <LuRocket />\n </div>\n );\n});\n```\n\nPlease refer to the [official docs for more details](https://github.com/qwikest/icons).\n\n## `icones.js.org`\n\n[icones.js.org](https://icones.js.org/) is a collection of icon collections. More than 180.000 public domain icons are available, ready to be used in your Qwik app.\n\nIcones is powered by [iconify](https://iconify.design/) which allows to easy add icons from Material Design, Phosphor, Remix, Carbon, Bootstrap, Tabler, Feather, Fluent, IconPark, Octicons and many other icon sets. Twitter Emoji, Fluent Emoji, EmojiOne, Noto Emoji... to any Qwik app.\n\nClick the `Qwik` button to copy the icon code to your clipboard, then paste it into your project.\n\n```tsx\nimport type { PropsOf } from '@qwik.dev/core'\n\nexport function OcticonAlertFill12(props: PropsOf<'svg'>, key: string) {\n return (\n\n\n )\n}\nexport default OcticonAlertFill12\n```\n"},{"id":"/docs/integrations/image-optimization/","title":"Image Optimization | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/image-optimization/","content":"# Image Optimization\n\nImage optimization is the process of reducing the number of bytes that represent an image. The smaller the image size, the faster it will load on a page. The smaller the image size, the less bandwidth it consumes. The less bandwidth it consumes, the better the experience for your users especially on mobile networks.\n\n## Responsive Images\n\nQwik supports responsive images.\n\nThis is a built-in feature that relies on the [`vite-imagetools`](https://www.npmjs.com/package/vite-imagetools) module, so no additional packages or components need to be installed.\n\n#### How it works\n\n* Import any image from the `src` folder\n* The image is converted in several webp images, one for each breakpoint (200px, 400px, 600px, 800px, 1200px)\n* The image is processed and optimized to reduce its size\n* An `` element is rendered, using the `srcset` attribute to set the image source for several resolutions\n* Now the browser will load the most suitable image for the resolution in use\n\n#### Key Points\nThe community and the Qwik team love this API for a number of reasons:\n\n* Zero runtime, zero JS\n* Zero props by default, simple API\n* Zero 404, strongly typed API\n* Zero layout reflows (Automatic width/height)\n* Hashed images, immutable cached\n* Automatic `.webp` / `.avif` format optimization\n* Automated `srcSet` generation\n* Extendable (use any `` attribute)\n* Loading lazy and async decoding by default\n* Lightweight, a single `` node in the HTML\n\n#### Usage\n\nAdd the `?jsx` suffix **at the end** of the import\n\n```tsx\nimport Image from '[IMAGE_PATH]?w=24&h=24&jsx';\n```\n\n**Warning**\nMake sure to put the `jsx` query parameter at the end of the import path, otherwise typescript might complain.\n\nUse the image in the template as a component:\n\n```tsx\n<Image />\n````\n\n#### Result\n\nThis script will generate the following `` element with the following optimizations:\n\n- Quality = 75\n- Format = .webp\n\n```tsx\n\n```\n\n**Image Attributes Explained**\n\n- `decoding=\"async\"`: indicates that the image will not block the rendering of the page while the image is being decoded. For further reference, please check the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/decoding).\n- `loading=\"lazy\"`: allows the browser to delay the loading of an image until it is visible in the viewport, which helps improve [page loading performance](https://web.dev/browser-level-image-lazy-loading/)\n- `srcset`: this attribute allows to choose the most appropriate image based on the device's screen size and resolution\n- `width` and `height`: setting `width` and `height` attributes prevents layout reflow, which hurts the [CLS](https://web.dev/cls/) score\n\nYou can also change the default behavior by manually setting the value of these properties: ``\n\nThanks to `srcset` attribute the browser will load the most suitable image for the device's resolution:\n\nThe original source size was 1.5Mb but its size is now just few kilobytes\n\n#### Example\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport Image from '~/media/your_image.png?jsx';\n\nexport default component$(() => {\n return (\n <div>\n <Image />\n </div>\n );\n});\n```\n#### Customize image format\nImages are automatically converted to `.webp` format, but you can also specify the format manually:\nAvailable formats:\n\n- `heic`\n- `heif`\n- `avif`\n- `jpeg`\n- `jpg`\n- `jpe`\n- `tile`\n- `dz`\n- `png`\n- `raw`\n- `tiff`\n- `tif`\n- `webp`\n- `gif`\n- `jp2`\n- `jpx`\n- `j2k`\n- `j2c`\n- `jxl`\n\nSupported file formats to be converted are:\n\n- `jpg`\n- `jpeg`\n- `png`\n- `webp`\n- `gif`\n- `tiff`\n- `avif`\n\nIn the below example, a `jpg` image is converted to a `png` format:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport Image from '~/media/your_image.jpg?format=png&jsx';\n\nexport default component$(() => {\n return (\n <div>\n <Image />\n </div>\n );\n});\n```\n\n#### Customize image quality\nAs noted above, the default quality is set to 75, but you can also specify the quality manually.\n\nQuality parameter is an integer between 1 and 100.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport Image from '~/media/your_image.png?quality=100&jsx';\n\nexport default component$(() => {\n return (\n <div>\n <Image />\n </div>\n );\n});\n\n```\n\n#### Customize image `width` and `height`\n\nYou may need to set a custom `width` to the image:\n\n```tsx\n<Image style={{ width: '300px'}} />\n```\n\nbut in that case you need to manually specify the `height` as well to avoid it being stretched:\n\n```tsx\n<Image style={{ width: '300px', height: '200px'}} />\n```\n\nBelow you can see a simple trick to avoid having to manually set the `height`, while also maintaining the aspect ratio:\n\n**TIP**\nYou should always specify `width` and `height` values to prevent layout reflow.\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport Image from '~/media/emote.png?jsx';\n\nexport default component$(() => {\n return (\n <>\n <h1>Image Example</h1>\n <div class=\"image-wrapper\" >\n <Image />\n </div>\n </>\n );\n});\n```\n\n```css\n.image-wrapper {\n width: 300px; /* Set the desired width of the wrapper */\n position: relative; /* Required for absolute positioning */\n}\n\n.image-wrapper img {\n width: 100%; /* Make the image fill the width of its container */\n height: auto; /* Let the browser calculate the height to maintain aspect ratio */\n display: block; /* Remove any extra white space below the image */\n}\n```\n\n#### Image Optimization for SVGs\n<abbr title=\"Scalable Vector Graphics\">SVGs</abbr> can be added directly to your JSX code, but you can also use the image optimization approach to optimize them:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport SvgImage from '~/media/your_image.svg?jsx';\n\nexport default component$(() => {\n return (\n <>\n <h1>Image Example</h1>\n <div class=\"image-wrapper\" >\n <SvgImage />\n </div>\n </>\n );\n});\n```\n## `@unpic/qwik`\n\n- Site with detailed instructions on usage: [@unpic/qwik](https://unpic.pics/img/qwik/)\n- Installation: add `@unpic/qwik` dependency\n\nUnpic is a third-party image optimization library that works with existing image optimization CDNs. It provides an `Image` component that can be used to optimize images.\n\n```tsx {6} /Slot/\nimport { component$ } from '@qwik.dev/core';\nimport { Image } from '@unpic/qwik';\n\nexport default component$(() => {\n return (\n <Image\n src=\"https://cdn.shopify.com/static/sample-images/bath_grande_crop_center.jpeg\"\n layout=\"constrained\"\n width={800}\n height={600}\n alt=\"A lovely bath\"\n />\n );\n});\n```\n\n**Supported Image CDNs**\n\nqwik-image and unpic are not a CDN and do not host your images. They work with existing image optimization CDNs. We suggest using some of the popular CDNs:\n- Cloudinary\n- Cloudflare\n- Bunny.net\n- Vercel / Next.js\n- Imgix, including Unsplash, DatoCMS, Sanity and Prismic\n- Shopify\n- Kontent.ai\n- Builder.io\n- Contentful\n- Storyblok\n- WordPress.com and Jetpack Site Accelerator\n\n## `qwik-image`\n\nPerformant images with automatic optimization.\n\n```shell\npnpm install qwik-image\n```\n\nThis is a pluggable component so devs could connect different image loaders to it (like builder.io or other CDNs)\n\nImages load lazily by default. Add the `priority` prop to an above-the-fold image so it loads eagerly with a high fetch priority.\n\n```tsx\nimport { $, component$ } from '@qwik.dev/core';\nimport {\n Image,\n type ImageTransformerProps,\n useImageProvider,\n} from 'qwik-image';\n\nexport default component$(() => {\n const imageTransformer$ = $(\n ({ src, width, height }: ImageTransformerProps): string => {\n // Here you can set your favorite image loaders service\n return `https://cdn.builder.io/api/v1/${src}?height=${height}&width=${width}&format=webp&fit=fill`;\n }\n );\n\n // Global Provider (required)\n useImageProvider({\n // You can set this prop to overwrite default values [3840, 1920, 1280, 960, 640]\n resolutions: [640],\n imageTransformer$,\n });\n\n return (\n <Image\n layout=\"constrained\"\n objectFit=\"fill\"\n width={400}\n height={500}\n alt=\"Tropical paradise\"\n placeholder=\"#e6e6e6\"\n src={\n 'image/assets%2FYJIGb4i01jvw0SRdL5Bt%2Fe5113e1c02db40e5bac75146fa46386f'\n }\n />\n );\n});\n```\n\nHere is the Github repository with detailed instructions on usage and customizations: [qwikifiers/qwik-image](https://github.com/qwikifiers/qwik-image)\n"},{"id":"/docs/integrations/","title":"Qwik Router Integrations | Guides","description":"","url":"https://next.qwik.dev/docs/integrations/","content":"# Integrations\n\nQwik CLI comes with integrations to make it easy to connect to your tooling and services.\n\nOnce you create a Qwik application, run the following command to add new integrations:\n\n```shell\npnpm run qwik add\n```\n\nThis command will prompt you to select the integration you want to add. Once selected, the integration will be added to your application and you can start using it.\n\nFor Monorepos: you can add integrations to a specific package by running the command with the `--projectDir=some/subDir` param.\n\n### List of possible integrations\n\n## Adding A New Integration\n\nThanks for your interest in adding an integration to Qwik! We're more than happy to help you get started. First, if you're looking to add a server deployment, please checkout the [Server Deployments](/docs/deployments.md#add-a-new-deployment) docs. If you'd like to add a Qwik library, please see the [Library](/docs/advanced/library.md) docs. If you'd like to add a new tooling or service integration, please read on.\n"},{"id":"/docs/integrations/leaflet-map/","title":"LeafletJS Map | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/leaflet-map/","content":"# LeafletJS Map\n\nLeaflet is the leading open-source JavaScript library for mobile-friendly interactive maps.\nWeighing just about 42 KB of JS, it has all the mapping features most developers ever need.\n\nLeaflet is designed with simplicity, performance and usability in mind.\nIt works efficiently across all major desktop and mobile platforms, can be extended with lots of plugins, has a beautiful, easy to use and well-documented API and a simple, readable source code that is a joy to contribute to. [LeafletJS Map Website](https://leafletjs.com/)\n\n## Usage\n\nYou can add LeafletJS Map easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add leaflet-map\n```\n\nThe previous command updates your app with the necessary dependencies.\n\n- `leaflet@1.9.4`\n- `@types/leaflet@1.9.4`\n\nIt also adds new files to your project folder:\n\n- `src/helpers/boundary-box.tsx`: Check map area boundaries function.\n- `src/models/location.ts`: Model to define locations info elements to use in props.\n- `src/models/map.ts`: Model to define map info to use in props.\n- `src/components/leaflet-map/index.tsx`: Leaflet map simple map features component.\n- `src/routes/basic-map/index.tsx`: Example to consume Leaflet Map component with demo data\n\n## Example\n\nThe main component configures the map, including the initial position and the group of markers to load.\nThis setup allows you to create a dynamic and interactive map that can be easily configured and extended with different locations and markers.\n\n### Here is an example:\n\n```tsx\nimport {\n component$,\n noSerialize,\n useSignal,\n useStyles$,\n useVisibleTask$,\n type Signal,\n} from '@qwik.dev/core';\nimport * as L from 'leaflet';\nimport leafletStyles from 'leaflet/dist/leaflet.css?inline';\n\n// Sample data json and geojson\n\nexport const fvg: any = {\n type: 'FeatureCollection',\n name: 'FVG_line_0_001',\n crs: { type: 'name', properties: { name: 'urn:ogc:def:crs:OGC:1.3:CRS84' } },\n features: [\n {\n type: 'Feature',\n properties: { ID_OGG: '08020060000', NAME: 'GEOJSON NAME' },\n geometry: {\n type: 'MultiLineString',\n coordinates: [\n [\n [12.4188, 46.3528],\n [12.4178, 46.3547],\n [12.4284, 46.3517],\n [12.4425, 46.3599],\n [12.4488, 46.3605],\n [12.4554, 46.3652],\n [12.4552, 46.3672],\n [12.4513, 46.3706],\n ],\n ],\n },\n },\n ],\n};\n\nconst markers: Record<string, MarkersProps[]> = {\n FDA: [\n {\n name: \"Terzo d'Aquileia\",\n label: 'TRZ',\n lat: '45.770946',\n lon: '13.31338',\n },\n {\n name: 'Musi',\n label: 'MUS',\n lat: '46.312663',\n lon: '13.274682',\n },\n ],\n FVG: [\n {\n name: 'Borgo Grotta Gigante',\n label: 'BGG',\n lat: '45.709385',\n lon: '13.764681',\n },\n {\n name: 'Muggia',\n label: 'MGG',\n lat: '45.610495',\n lon: '13.752682',\n },\n ],\n};\n\nexport default component$(() => {\n useStyles$(\n leafletStyles +\n `\n .marker-label {\n color: red;\n font-weight: 700;\n }\n `\n );\n\n const groupSig = useSignal('FDA');\n const currentLocation = useSignal<LocationsProps>({\n name: 'Udine',\n point: [46.06600881056668, 13.237724558490601],\n zoom: 10,\n marker: true,\n });\n\n return (\n <>\n Change markers:{' '}\n <select name=\"group\" class=\"leaflet-ctrl\" bind:value={groupSig}>\n <option value=\"FDA\">FDA</option>\n <option value=\"FVG\">FVG</option>\n </select>\n <LeafletMap\n location={currentLocation}\n markers={markers[groupSig.value]}\n group={groupSig}\n ></LeafletMap>\n </>\n );\n});\n\n// The properties (props) used in the `LeafletMap` component and other related components are defined as follows:\n\nexport interface MapProps {\n location: Signal<LocationsProps>;\n markers?: MarkersProps[];\n group?: Signal<string>;\n}\n\nexport interface LocationsProps {\n name: string;\n point: [number, number];\n zoom: number;\n marker: boolean;\n}\n\nexport interface MarkersProps {\n name: string;\n label: string;\n lat: string;\n lon: string;\n}\n\n/*\nThe `LeafletMap` component leverages the Leaflet library to render an interactive map.\nThis component can be configured with various properties (props) to set the central location, add markers, and draw boundaries.\nIn the `LeafletMap` component, both the location and the group signal are tracked.\nThis ensures that when the signal changes, the server function is called, and the map is updated with the new data.\n*/\n\nexport const LeafletMap = component$<MapProps>(\n ({ location, markers, group }) => {\n const mapContainerSig = useSignal<L.Map>();\n\n useVisibleTask$(async ({ track }) => {\n track(location);\n group && track(group);\n\n if (mapContainerSig.value) {\n mapContainerSig.value.remove();\n }\n\n // center location\n const { value: locationData } = location;\n const centerPosition = locationData.point;\n\n // layers\n const markersLayer = new L.LayerGroup();\n const bordersLayer = new L.LayerGroup();\n\n // map\n const map = L.map('map', {\n layers: [markersLayer, bordersLayer],\n }).setView(centerPosition, locationData.zoom || 14);\n L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {\n maxZoom: 19,\n attribution:\n '&copy; <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a>',\n }).addTo(map);\n\n // center position marker\n\n const qwikMarker = L.divIcon({\n html: `\n\n\n `,\n className: '',\n iconSize: [24, 40],\n });\n\n locationData.marker &&\n L.marker(centerPosition, { icon: qwikMarker })\n .bindPopup(`Udine`)\n .addTo(map);\n\n // add boundaries to map\n L.geoJSON(fvg, { style: { color: '#005DA4' } }).addTo(bordersLayer);\n\n // add markers to map\n const markersList = await markers;\n markersList &&\n markersList.map((m) => {\n const myIcon = L.divIcon({\n className: 'marker-point',\n html: `<div class=\"marker-label\" title=\"${m.name}\" >${m.label}</div>`,\n });\n L.marker([+m.lat, +m.lon], { icon: myIcon }).addTo(markersLayer);\n });\n\n mapContainerSig.value = noSerialize(map);\n });\n\n return <div id=\"map\" style={{ height: '25rem' }}></div>;\n }\n);\n```\n\n## Interesting info about LeafletJS Map:\n\n### Official\n\n- `Tutorials`: Examples step by step to reference to create new features using Documentation. [Reference](https://leafletjs.com/examples.html).\n- `Docs`: All necessary info to work with LeafletJS. [Reference](https://leafletjs.com/reference.html)\n"},{"id":"/docs/integrations/modular-forms/","title":"Modular Forms | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/modular-forms/","content":"# Modular Forms\n\n[Modular Forms](https://modularforms.dev/) is a type-safe form library built natively on Qwik. The headless design gives you full control over the visual appearance of your form. The library takes care of state management and input validation.\n\nTo get started, install the `@modular-forms/qwik` package:\n\n**Warning**\nMake sure to install @modular-forms/qwik as a devDependency, since it only runs at build/SSR time. Putting it in your regular dependencies will trigger Vite plugin errors.\n\n```shell\npnpm add -D @modular-forms/qwik\n```\n\n## Define your form\n\nBefore you start creating a form, you define the structure and data types of the fields. Besides strings, Modular Forms can also handle booleans, numbers, files, dates, objects and arrays.\n\n```ts\ntype LoginForm = {\n email: string;\n password: string;\n};\n```\n\nSince Modular Forms supports [Valibot](https://valibot.dev/) and [Zod](https://zod.dev/) for input validation, you can optionally derive the type definition from a schema.\n\n```ts\nimport * as v from 'valibot';\n\nconst LoginSchema = v.object({\n email: v.pipe(\n v.string(),\n v.nonEmpty('Please enter your email.'),\n v.email('The email address is badly formatted.'),\n ),\n password: v.pipe(\n v.string(),\n v.nonEmpty('Please enter your password.'),\n v.minLength(8, 'Your password must have 8 characters or more.'),\n ),\n});\n\ntype LoginForm = v.InferInput<typeof LoginSchema>;\n```\n\nIf you're wondering why this guide favors Valibot over Zod, I recommend reading this [announcement post](https://www.builder.io/blog/introducing-valibot).\n\n## Set initial values\n\nAfter you have created the type definition, continue with the initial values of your form. To do this, create a [`routeLoader$`](../../route-loader/) and use as generic your previously created type.\n\n```ts\nexport const useFormLoader = routeLoader$<InitialValues<LoginForm>>(() => ({\n email: '',\n password: '',\n}));\n```\n\nInstead of empty strings, in `routeLoader$` you can also query and pass values from your database. Based on the passed object, the store of your form will be initialized to enable Qwik to reliably pre-render your website on the server. The initial values are also used later to check if the value of a field has changed after user input.\n\n## Create a form\n\nTo create a form, you use the [`useForm`](https://modularforms.dev/qwik/api/useForm) hook. It returns the store of your form and an object with a `Form`, `Field` and `FieldArray` component. As a parameter you pass an object to `useForm`, with the previously created loader.\n\n```ts\nexport default component$(() => {\n const [loginForm, { Form, Field, FieldArray }] = useForm<LoginForm>({\n loader: useFormLoader(),\n });\n});\n```\n\nYou can use the `loginForm` object to access the current state of your form. Furthermore, you can pass it to various methods provided by the library, such as [`reset`](https://modularforms.dev/qwik/api/reset) or [`setValue`](https://modularforms.dev/qwik/api/setValue), to make manual changes to the state.\n\nIn the JSX part of your component you continue with the [`Form`](https://modularforms.dev/qwik/api/Form) component. It encloses the fields of your form and through its properties you can define what happens when the form is submitted.\n\n```tsx\nexport default component$(() => {\n const [loginForm, { Form, Field, FieldArray }] = useForm<LoginForm>({\n loader: useFormLoader(),\n });\n\n return <Form>…</Form>;\n});\n```\n\n## Add form fields\n\nNow you can proceed with the fields of your form. With the [`Field`](https://modularforms.dev/qwik/api/Field) and [`FieldArray`](https://modularforms.dev/qwik/api/FieldArray) component you register a field or field array. Both components are headless and provide you direct access to their current state. The second parameter of the render prop must be passed to an `<input />`, `<select />` or `<textarea />` element to connect it to your form.\n\n```tsx\n<Form>\n <Field name=\"email\">\n {(field, props) => (\n <input {...props} type=\"email\" value={field.value} />\n )}\n </Field>\n <Field name=\"password\">\n {(field, props) => (\n <input {...props} type=\"password\" value={field.value} />\n )}\n </Field>\n <button type=\"submit\">Login</button>\n</Form>\n```\n\nThis API design results in a fully type-safe form. Furthermore, it gives you full control over the user interface. You can develop your own [`TextInput`](https://modularforms.dev/qwik/guides/input-components) component or connect a pre-built component library.\n\n## Input validation\n\nOne of the core functionalities of Modular Forms is input validation. You can use a Valibot or Zod schema for this or our internal validation functions. To keep this guide simple, we use the Valibot schema we created earlier and pass it to the `useForm` hook.\n\n`valiForm$` is an adapter that converts Valibot's error messages to the format expected by Modular Forms. For Zod use `zodForm$` instead.\n\n```ts\nconst [loginForm, { Form, Field, FieldArray }] = useForm<LoginForm>({\n loader: useFormLoader(),\n validate: valiForm$(LoginSchema),\n});\n```\n\nNow you only need to display the error messages of your fields in case of an error.\n\n```tsx\n<Field name=\"email\">\n {(field, props) => (\n <div>\n <input {...props} type=\"email\" value={field.value} />\n {field.error && <div>{field.error}</div>}\n </div>\n )}\n</Field>\n```\n\n## Handle submission\n\nIn the last step you only have to access the values via a function when submitting the form to process and use them further. You can use [`formAction$`](https://modularforms.dev/qwik/api/formAction$) for this or the `onSubmit$` property of the `Form` component.\n\n```tsx\nexport const useFormAction = formAction$<LoginForm>((values) => {\n // Runs on server\n}, valiForm$(LoginSchema));\n\nexport default component$(() => {\n const [loginForm, { Form, Field }] = useForm<LoginForm>({\n loader: useFormLoader(),\n action: useFormAction(),\n validate: valiForm$(LoginSchema),\n });\n\n const handleSubmit = $<SubmitHandler<LoginForm>>((values, event) => {\n // Runs on client\n });\n\n return (\n <Form onSubmit$={handleSubmit}>\n …\n </Form>\n );\n});\n```\n\n## Final form\n\nIf we now put all the building blocks together, we get a working login form. Below you can see the assembled code and try it out in the attached sandbox.\n\n```tsx\n// @ts-nocheck\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { $, component$, type QRL } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\nimport type { InitialValues, SubmitHandler } from '@modular-forms/qwik';\nimport { formAction$, useForm, valiForm$ } from '@modular-forms/qwik';\nimport * as v from 'valibot';\n\nconst LoginSchema = v.object({\n email: v.pipe(\n v.string(),\n v.nonEmpty('Please enter your email.'),\n v.email('The email address is badly formatted.'),\n ),\n password: v.pipe(\n v.string(),\n v.nonEmpty('Please enter your password.'),\n v.minLength(8, 'Your password must have 8 characters or more.'),\n ),\n});\n\ntype LoginForm = v.InferInput<typeof LoginSchema>;\n\nexport const useFormLoader = routeLoader$<InitialValues<LoginForm>>(() => ({\n email: '',\n password: '',\n}));\n\nexport const useFormAction = formAction$<LoginForm>((values) => {\n // Runs on server\n}, valiForm$(LoginSchema));\n\nexport default component$(() => {\n const [loginForm, { Form, Field }] = useForm<LoginForm>({\n loader: useFormLoader(),\n action: useFormAction(),\n validate: valiForm$(LoginSchema),\n });\n\n const handleSubmit: QRL<SubmitHandler<LoginForm>> = $((values, event) => {\n // Runs on client\n console.log(values);\n });\n\n return (\n <Form onSubmit$={handleSubmit}>\n <Field name=\"email\">\n {(field, props) => (\n <div>\n <input {...props} type=\"email\" value={field.value} />\n {field.error && <div>{field.error}</div>}\n </div>\n )}\n </Field>\n <Field name=\"password\">\n {(field, props) => (\n <div>\n <input {...props} type=\"password\" value={field.value} />\n {field.error && <div>{field.error}</div>}\n </div>\n )}\n </Field>\n <button type=\"submit\">Login</button>\n </Form>\n );\n});\n```\n\n## Dealing With Props\n\nSometimes, you may need to initialize or update the state of your form from the parent component via props. In such cases, you can use the setValue function, as illustrated in the example below:\n\n```tsx\nimport { setValue, useForm } from \"@modular-forms/qwik\";\n\nexport interface FormProps {\n login?: LoginForm\n}\n\nexport default component$<FormProps>((props) => {\n const [loginForm, { Form, Field }] = useForm<LoginForm>({\n // rest of the code...\n });\n\n useTask$(({ track }) => {\n const login = track(() => props.login);\n if (!login) return;\n for (const [key,value] of Object.entries(login)) {\n setValue(loginForm, key, value);\n }\n });\n\n // rest of the code...\n});\n```\nBy tracking props.login with useTask$, the form fields are dynamically updated whenever the parent provides new values.\n\n## Dealing With Props\n\nSometimes, you may need to initialize or update the state of your form from the parent component via props. In such cases, you can use the setValue function, as illustrated in the example below:\n\n```tsx\nimport { setValue, useForm } from \"@modular-forms/qwik\";\n\nexport interface FormProps {\n login?: LoginForm\n}\n\nexport default component$<FormProps>((props) => {\n const [loginForm, { Form, Field }] = useForm<LoginForm>({\n // rest of the code...\n });\n\n useTask$(({ track }) => {\n const login = track(() => props.login);\n if (!login) return;\n for (const [key,value] of Object.entries(login)) {\n setValue(loginForm, key, value);\n }\n });\n\n // rest of the code...\n});\n```\nBy tracking props.login with useTask$, the form fields are dynamically updated whenever the parent provides new values.\n\n## Dealing With Props\n\nSometimes, you may need to initialize or update the state of your form from the parent component via props. In such cases, you can use the setValue function, as illustrated in the example below:\n\n```tsx\nimport { setValue, useForm } from \"@modular-forms/qwik\";\n\nexport interface FormProps {\n login?: LoginForm\n}\n\nexport default component$<FormProps>((props) => {\n const [loginForm, { Form, Field }] = useForm<LoginForm>({\n // rest of the code...\n });\n\n useTask$(({ track }) => {\n const login = track(() => props.login);\n if (!login) return;\n for (const [key,value] of Object.entries(login)) {\n setValue(loginForm, key, value);\n }\n });\n\n // rest of the code...\n});\n```\nBy tracking props.login with useTask$, the form fields are dynamically updated whenever the parent provides new values.\n\n## Summary\n\nYou have learned the basics of Modular Forms and are ready to create your first simple form. For more info and details you can find more guides and the API reference on our website: [modularforms.dev](https://modularforms.dev/)\n\nDo you like Modular Forms so far? It would be a great honor for us to get a star from you on [GitHub](https://github.com/fabian-hiller/modular-forms)!\n"},{"id":"/docs/integrations/nx/","title":"Nx Monorepos | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/nx/","content":"# Nx and enterprise scale monorepos\n\n[Nx](https://nx.dev/) is a robust and extensible development platform designed to simplify the management\nof large-scale monorepos containing multiple applications and libraries by offering powerful tools for code generation,\nbuild orchestration, dependency management, and code sharing.\n\nQwik integrates with nx beautifully by using the [qwik-nx](https://github.com/qwikifiers/qwik-nx) plugin.\n\n## Main features\n\n* Generate a new Nx workspace using a \"Qwik\" preset\n* Generate Qwik applications and libraries.\n* Generate Qwik components and routes.\n* Generate Storybook, React Qwikify, Cloudflare configuration and much more\n* Run executors that are built specifically for building Qwik applications.\n\n## Usage\n\nYou can generate a new workspace by running:\n\n```shell\npnpm dlx create-nx-workspace@latest org-workspace --preset=qwik-nx\n```\n\nOr add a new Qwik application to an existing workspace by running:\n\n```shell\npnpm install qwik-nx\n```\n\nand then\n\n```shell\nnx generate qwik-nx:app\n```\n\nFor further reference, please check the [qwik-nx documentation](https://github.com/qwikifiers/qwik-nx).\n"},{"id":"/docs/integrations/og-img/","title":"OG Image (og-img) | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/og-img/","content":"# OG Image (og-img)\n\nWith [`og-img`](https://github.com/fabian-hiller/og-img) you can easily add dynamic Open Graph images to your Qwik website. These are displayed, for example, when your website is shared on social media or via messenger services.\n\n`og-img` is a framework agnostic package for generating Open Graph images using [Satori](https://github.com/vercel/satori) and [resvg](https://github.com/RazrFalcon/resvg).\n\nTo get started, install the `og-img` package:\n\n```shell\npnpm install og-img\n```\n\n## How it works\n\nTo generate an image, all you need to do is return an `ImageResponse` via a server endpoint. To create one, add a new route to your Qwik website and export a function called `onGet` in the index file. To easily define the content of your image, you can use the `html` tagged template literal.\n\nTo get proper syntax highlighting for the tagged template literal in Visual Studio Code, you can install the [lit-html](https://marketplace.visualstudio.com/items?itemName=bierner.lit-html) extension.\n\n```ts title=\"src/routes/og-image/index.ts\"\nimport type { RequestHandler } from '@qwik.dev/router';\nimport { fetchFont, ImageResponse, html } from 'og-img';\n\nexport const onGet: RequestHandler = async ({ send }) => {\n send(\n new ImageResponse(\n // Use Tailwind CSS or style attribute\n html`\n <div tw=\"text-4xl text-green-700\" style=\"background-color: tan\">\n Hello, world!\n </div>\n `,\n {\n width: 1200,\n height: 600,\n fonts: [\n {\n name: 'Roboto',\n // Use `fs` (Node.js only) or `fetch` to read font file\n data: await fetchFont(\n 'https://www.example.com/fonts/roboto-400.ttf'\n ),\n weight: 400,\n style: 'normal',\n },\n ],\n }\n )\n );\n};\n```\n\nThen all you need to do is point to this API endpoint with a meta tag in the head of your Qwik website to embed the Open Graph image.\n\n```html\n<head>\n <title>Hello, world!</title>\n <meta property=\"og:image\" content=\"https://www.example.com/og-image\" />\n</head>\n```\n\nYou can also generate the meta tag dynamically by export a `head` object in your routes.\n\n```tsx title=\"src/routes/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport type { DocumentHead } from '@qwik.dev/router';\n\nexport default component$(() => {\n return <h1>Hello, world!</h1>;\n});\n\nexport const head: DocumentHead = {\n title: 'Hello, world!',\n meta: [\n {\n property: 'og:image',\n content: 'https://www.example.com/og-image',\n },\n ],\n};\n```\n\nYou can use URL parameters to dynamically change the content of your Open Graph image. Take a look at [Valibot's Open Graph image](https://valibot.dev/og-image/?title=Example%20Title&description=The%20content%20of%20this%20image%20was%20generated%20dynamically). You can find the source code [here](https://github.com/fabian-hiller/valibot/blob/main/website/src/routes/og-image/index.ts).\n"},{"id":"/docs/integrations/orama/","title":"Qwik Router and Orama","description":"","url":"https://next.qwik.dev/docs/integrations/orama/","content":"# Orama\n\n[Orama](https://oramasearch.com/) is a fast, batteries-included, full-text search engine entirely written in TypeScript, with zero dependencies.\n\nOrama could be used in Qwik on the client side or on the server side with `routeLoader$`, `routeAction$` and `server$` functions.\n\nThe easiest way to add Orama to Qwik is using the Qwik CLI command. This will install the required dependencies and create a new public route `/src/routes/orama` to showcase the Orama integration.\n\n```shell\npnpm run qwik add orama\n```\n\nOrama has been designed to work on any runtime and has no dependencies. A JavaScript runtime is the only requirement.\n\nFor further reference, please check the [Orama documentation](https://docs.oramasearch.com/).\n"},{"id":"/docs/integrations/panda-css/","title":"Panda CSS | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/panda-css/","content":"# Panda CSS\n\nPanda is a styling engine that generates styling primitives to author atomic CSS and recipes in a type-safe and readable manner.\n[Panda CSS Website](https://panda-css.com/)\n\n## Usage\n\nYou can add Panda easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add pandacss\n```\n\nThe previous command updates your app with the necessary dependencies.\n\nIt also adds new files to your project folder:\n\n- `postcss.config.js`\n- `panda.config.js`\n- `.vscode/settings.json`\n\nand modifies your `src/global.css` to include\n\n```css title=\"src/global.css\"\n\n# global.css file\n\n@layer reset, base, tokens, recipes, utilities;\n\n...stuff...\n\n```\n"},{"id":"/docs/integrations/partytown/","title":"Partytown | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/partytown/","content":"# Partytown\n\nThird party scripts slow down your initial page load substantially by blocking the main thread.\n\nPartytown is a tool that allows you to defer third party scripts like Google Analytics, Facebook Pixel, etc off the main thread by using a web worker.\nFor more information about this tool visit the [Partytown docs](https://partytown.qwik.dev/).\n\n## Usage\n\nYou can add Partytown easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add partytown\n```\n\nThe previous command updates your app and sets the correct configuration in `vite.config.ts`.\n\nIt also adds new files to your `components` folder.\n\n```tsx title=\"src/root.tsx\"\n// ...\nimport { QwikPartytown } from './components/partytown/partytown';\n\nexport default component$(() => {\n useQwikRouter();\n\n return (\n <>\n <head>\n <meta charSet=\"utf-8\" />\n <QwikPartytown forward={['gtag','dataLayer.push']} />\n <script\n async\n type=\"text/partytown\"\n src=\"https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX\"\n />\n <script\n type=\"text/partytown\"\n dangerouslySetInnerHTML={`\n window.dataLayer = window.dataLayer || [];\n window.gtag = function() {\n dataLayer.push(arguments);\n }\n gtag('js', new Date());\n gtag('config', 'G-XXXXXX');\n `}\n />\n {/* ... */}\n </head>\n <body>\n <RouterOutlet />\n </body>\n </>\n );\n});\n```\n\n## Advanced\n\nTo further configure Partytown with more options, please visit the [Partytown Documentation](https://partytown.qwik.dev/configuration)\n"},{"id":"/docs/integrations/playwright/","title":"Playwright | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/playwright/","content":"# Playwright\n\nPlaywright enables reliable end-to-end testing for modern web apps supporting all modern rendering engines and works cross-platform. [Playwright Website](https://playwright.dev/).\n\n## Usage\n\nYou can add Playwright easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add playwright\n```\n\nThe previous command adds playwright to your dependencies, appends a `test.e2e` command in your `package.json` scripts section and creates a default configuration within the `playwright.config.ts` file on the application root level.\nIt also adds a new file within a newly created `tests` folder called `example.spec.ts` which contains some simple test cases.\n\nFor further reference, please check the [Playwright documentation](https://playwright.dev/docs/intro).\n"},{"id":"/docs/integrations/postcss/","title":"PostCSS | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/postcss/","content":"# PostCSS\n\n[PostCSS](https://postcss.org/) allows developers to write modern CSS while still maintaining backwards compatibility and improving performance. It parses CSS code and passes it through a series of plugins that can modify, optimize, and extend the CSS before outputting the final result.\n\n## Usage\n\nYou can add PostCSS to your project by using the following Qwik starter script:\n\n```shell\npnpm run qwik add postcss\n```\n\nThis will create a new `postcss.config.js` file at the root of the project with following dependencies and configuration.\n\n- [Autoprefixer](https://github.com/postcss/autoprefixer)\n- [PostCSS Preset Env](https://preset-env.cssdb.org/)\n\n```ts title=\"postcss.config.js\"\nexport default {\n plugins: {\n autoprefixer: {},\n \"postcss-preset-env\": {\n stage: 3,\n features: {\n \"nesting-rules\": true,\n },\n },\n },\n};\n```\n\nIf you wish to add a new plugin like [CssNano](https://cssnano.co/) run the following command and update the `postcss.config.js`.\n\n```shell\npnpm install cssnano\n```\n\n```ts title=\"postcss.config.js\"\nmodule.exports = {\n plugins: {\n /* previous plugin configuration */\n \"cssnano\": {\n preset: \"default\"\n }\n },\n}\n```\n\nFor further documentation, checkout [PostCSS Docs](https://postcss.org/docs/)\n"},{"id":"/docs/integrations/prisma/","title":"Prisma | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/prisma/","content":"# Prisma\n\n[Prisma](https://www.prisma.io/) allows interaction with [MongoDB](https://www.prisma.io/docs/concepts/database-connectors/mongodb) or [SQL databases](https://www.prisma.io/docs/concepts/database-connectors/postgresql) in a fully type-safe manner.\n\nWith Prisma you define your DB schema in `.prisma` files, and their CLI automatically generates the DB migrations as well as the Typescript types.\n\nPrisma can be used in Qwik with `routeLoader$`, `routeAction$` and `server$` functions. These are Qwik APIs to allow code to execute only on the server-side.\n\nThe easiest way to add Prisma to Qwik is using the Qwik CLI command. This will install the required dependencies and create a `prisma` folder with the Prisma schema and the migrations.\n\n```shell\npnpm run qwik add prisma\n```\n\nPrisma makes it easy to use different databases such as Postgres, MySQL, SQLite and MongoDB.\n\n## Listing all the users\n\nWe will use `routeLoader$` to query all users in the DB, using `prisma.user.findMany()`, and returning the result.\n\n```tsx {7} /PrismaClient/ title=\"src/routes/users/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\nimport { PrismaClient } from '@prisma/client'\n\nexport const useGetUsers = routeLoader$(async () => {\n const prisma = new PrismaClient();\n // example read from SQLite\n const users = await prisma.user.findMany()\n return users;\n});\n\nexport default component$(() => {\n const users = useGetUsers();\n return (\n <section>\n <h1>User's directory</h1>\n <ul>\n {users.value.map(user => (\n <li key={user.id}>\n <a href={`/users/${user.id}`}>{user.name} ({user.email})</a>\n </li>\n ))}\n </ul>\n </section>\n )\n});\n```\n\n## Show user detail\n\nWe will use `routeLoader$` to query specific users based on the `userId` URL param, using `prisma.user.findUnique()`, and returning the result.\n\n```tsx {8} /PrismaClient/ title=\"src/routes/users/[userId]/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeLoader$ } from '@qwik.dev/router';\nimport { PrismaClient } from '@prisma/client'\n\nexport const useGetUser = routeLoader$(async ({params, status}) => {\n const userId = parseInt(params['userId'], 10);\n const prisma = new PrismaClient();\n const user = await prisma.user.findUnique({where: {id: userId}});\n if (!user) {\n // Set the status to 404 if the user is not found\n status(404);\n }\n return user;\n});\n\nexport default component$(() => {\n const user = useGetUser();\n return (\n <section>\n <h1>User detail</h1>\n {user.value ? (\n <>\n <p>Name: {user.value.name}</p>\n <p>Email: {user.value.email}</p>\n </>\n ) : (\n <p>User not found</p>\n )}\n </section>\n )\n});\n```\n\n## Adding a user\n\nWe will use `routeAction$` and `Form` to create a progressive form to add a new user to the DB. We will use `prisma.user.create()` to create the user.\n\n```tsx {7-9} /PrismaClient/ title=\"src/routes/create/index.tsx\"\nimport { component$ } from '@qwik.dev/core';\nimport { routeAction$, Form } from '@qwik.dev/router';\nimport { zod$, z } from '@qwik.dev/utils';\nimport { PrismaClient } from '@prisma/client'\n\nexport const useCreateUser = routeAction$(async (data) => {\n const prisma = new PrismaClient();\n const user = await prisma.user.create({\n data,\n });\n return user;\n}, zod$({\n name: z.string(),\n email: z.string().email(),\n}));\n\nexport default component$(() => {\n const createUserAction = useCreateUser();\n return (\n <section>\n <h1>Create User</h1>\n <Form action={createUserAction}>\n <label>Name\n <input name=\"name\" value={createUserAction.formData?.get('name')} />\n </label>\n <label>Email\n <input name=\"email\" value={createUserAction.formData?.get('email')} />\n </label>\n <button type=\"submit\">Create</button>\n </Form>\n {createUserAction.value && (\n <div>\n <h2>User created successfully!</h2>\n </div>\n )}\n </section>\n )\n});\n```\n"},{"id":"/docs/integrations/react/","title":"React | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/react/","content":"# Qwik React Qwik React allows you to use [React](https://react.dev/) within [Qwik](https://qwik.dev/). The advantage of using Qwik React is that you can use existing React components and libraries within Qwik. This allows you to take advantage of the large ecosystem of React components and libraries such as [Material UI](https://mui.com/), [Threejs](https://github.com/pmndrs/react-three-fiber) and [React Spring](https://react-spring.io/). It is also a good way to get the benefits of Qwik without having to rewrite your React application.\n\n## Basic Usage\n\nThe basic usage of Qwik React is to take existing React components and wrap them in a `qwikify$` function. This function will create a Qwik component that can be used within Qwik and which will turn the React component into an island allowing you the freedom to fine-tune when the React component should hydrate.\n\nThen, you can wrap Qwik components in React components using `reactify$` to allow React components to render Qwik components. This allows you to replace parts of your React application with Qwik components and take advantage of Qwik's performance benefits without having to rewrite your entire application.\n\nBasic usage\n```tsx\n// This pragma is required so that React JSX is used instead of Qwik JSX\n/** @jsxImportSource react */\nimport { qwikify$ } from '@qwik.dev/react';\n\n// An existing React component\nfunction Greetings() {\n return <div>Hello from React</div>;\n}\n\n// Qwik component wrapping the React component\nexport const QGreetings = qwikify$(Greetings);\n```\n\n## 0. Installation\n\nBefore you can use Qwik React you need to configure the Qwik project to use Qwik React. The simplest way is to run the following command:\n\nIf you don't have a Qwik app yet, then you need to [create one first](/docs/getting-started.md), then, follow the instructions and run the command add React to your app.\n\n```shell\npnpm run qwik add react\n```\n\nThe above command will perform the following:\n\n1. Install the required dependencies in `package.json`:\n ```json\n {\n ...,\n \"dependencies\": {\n ...,\n \"@qwik.dev/react\": \"0.5.0\",\n \"@types/react\": \"18.0.28\",\n \"@types/react-dom\": \"18.0.11\",\n \"react\": \"18.2.0\",\n \"react-dom\": \"18.2.0\",\n }\n }\n ```\nThis is not an emulation of React. We are using the actual React library.\n\n2. configure Vite to use the `@qwik.dev/react` plugin:\n ```ts\n // vite.config.ts\n import { qwikReact } from '@qwik.dev/react/vite';\n\n export default defineConfig(() => {\n return {\n ...,\n plugins: [\n ...,\n // The important part\n qwikReact()\n ],\n };\n });\n ```\n\n**Demo Route Configuration**\n\nThe `qwik add react` command will also configure a demo route showcasing the Qwik React integration. These are:\n- `package.json` `dependencies`:\n - `@emotion/react 11.10.6`\n - `@emotion/styled 11.10.6`\n - `@mui/material 5.11.9`\n - `@mui/x-data-grid 5.17.24`\n- `src/route`:\n - `/src/routes/react`: New public route showcasing react integration\n - `/src/integrations/react`: Here's where the react component lives\n\nWe will ignore these in this guide and instead take you through the process from the beginning.\n\n## 1. Hello World\n\nLet's start with a simple example. We will create a simple React component and then wrap it in a Qwik component. We will then use the Qwik component in a Qwik route.\n\n```tsx /qwikify$/ /QGreetings/\n/** @jsxImportSource react */\nimport { qwikify$ } from '@qwik.dev/react';\n\n// Create React component standard way\nfunction Greetings() {\n return <p>Hello from React</p>;\n}\n\n// Convert React component to Qwik component\nexport const QGreetings = qwikify$(Greetings);\n```\n\n```tsx /QGreetings/\nimport { component$ } from '@qwik.dev/core';\nimport { QGreetings } from './react';\n\nexport default component$(() => {\n return (\n <main>\n <p>Hello from Qwik</p>\n <QGreetings />\n </main>\n );\n});\n```\n\nThe `@qwik.dev/react` package exports the `qwikify$()` function that lets you convert React components into Qwik components, that you can use across your application.\n\nYou CAN NOT use React components in Qwik without converting them first, using `qwikify$()`. Even though [React and Qwik components look similar](/docs/guides/react-cheat-sheet.md), they are fundamentally very different.\n\nReact and Qwik components can not be mixed in the same file, if you check your project right after running the installation command, you will see a new folder `src/integrations/react/`, we recommend that you place your React components there.\n\n## 2. Hydrating react islands\n\nThe above example shows how to SSR static React content on the server. The benefit is that that component will never re-render in the browser and therefore its code never downloads to the client. But what if the component needs to be interactive, and therefore we need to download its behavior in the browser? Let's start with building a simple counter example in React.\n\n```tsx /qwikify$/ /QGreetings/\n/** @jsxImportSource react */\nimport { qwikify$ } from '@qwik.dev/react';\nimport { useState } from 'react';\n\n// Create React component standard way\nfunction Counter() {\n const [count, setCount] = useState(0);\n return (\n <button className=\"react\" onClick={() => setCount(count + 1)}>\n Count: {count}\n </button>\n );\n}\n\n// Convert React component to Qwik component\nexport const QCounter = qwikify$(Counter);\n```\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { QCounter } from './react';\n\nexport default component$(() => {\n return (\n <main>\n <QCounter />\n </main>\n );\n});\n```\n\nNotice that clicking on the `Count` button does nothing. This is because the React has not been downloaded and therefore the component was not hydrated. We need to tell Qwik to download the React component and hydrate it, but we need to specify the condition under which we want to do that. Doing it eagerly would lose all of the benefits of turning the React application into islands. In this case, we want to download the component when the user hovers over the button, we do so by adding `{: eagerness: 'hover' }` to `qwikify$()`.\n\n<CodeSandbox src=\"/src/routes/demo/react/counter-simple-hover/\" console={true}\n tabs={[\"react.tsx\",\"index.tsx\"]} style={{ height: '20em' }}>\n\n```tsx /qwikify$/ /{: eagerness: 'hover' }/\n/** @jsxImportSource react */\nimport { qwikify$ } from '@qwik.dev/react';\nimport { useState } from 'react';\n\n// Create React component standard way\nfunction Counter() {\n // Print to console to show when the component is rendered.\n console.log('React <Counter/> Render');\n const [count, setCount] = useState(0);\n return (\n <button className=\"react\" onClick={() => setCount(count + 1)}>\n Count: {count}\n </button>\n );\n}\n\n// Specify eagerness to hydrate component on hover event.\nexport const QCounter = qwikify$(Counter, { eagerness: 'hover' });\n```\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { QCounter } from './react';\n\nexport default component$(() => {\n console.log('Qwik Render');\n return (\n <main>\n <QCounter />\n </main>\n );\n});\n```\n\nIn this example, we have brought up the console to show what is going on behind the scene. When you hover over the button, you will see that the React component is rendered. This is because we asked Qwik to hydrate the component on `hover`. Now that the component is hydrated you can interact with it and it will correctly update the count.\n\nBy giving the `eagerness` property to `qwikify$()`, we are allowing you to fine-tune the conditions under which the component is hydrated which will impact the startup performance of your application.\n\n## 3. Inter-island communication\n\nIn the previous example, we had a single island that we delay-hydrated. But once you have multiple islands, there will be a need to communicate between them. This example shows how to do inter-island communication with Qwik.\n\n<CodeSandbox src=\"/src/routes/demo/react/counter-two-islands/\" console={true}\n tabs={[\"react.tsx\",\"index.tsx\"]} style={{ height: '20em' }}>\n\n```tsx /qwikify$/ /{: eagerness: 'hover' }/\n/** @jsxImportSource react */\nimport { qwikify$ } from '@qwik.dev/react';\n\nfunction Button({ onClick }: { onClick: () => void }) {\n console.log('React <Button/> Render');\n return <button onClick={onClick}>+1</button>;\n}\n\nfunction Display({ count }: { count: number }) {\n console.log('React <Display count=' + count + '/> Render');\n return <p className=\"react\">Count: {count}</p>;\n}\n\nexport const QButton = qwikify$(Button, { eagerness: 'hover' });\nexport const QDisplay = qwikify$(Display);\n```\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { QButton, QDisplay } from './react';\n\nexport default component$(() => {\n console.log('Qwik Render');\n const count = useSignal(0);\n return (\n <main>\n <QButton\n onClick$={() => {\n console.log('click', count.value);\n count.value++;\n }}\n />\n <QDisplay count={count.value}></QDisplay>\n </main>\n );\n});\n```\n\nIn the above example, we have two islands, one for the button (`QButton`) and one for the display (`QDisplay`). The button island is hydrated on `hover` and the display island is not hydrated on any event.\n\nThe `react.tsx` file has:\n- `QButton` - a button that increments the count when clicked. This island is hydrated on `hover`.\n- `QDisplay` - a display that shows the current count. This island is not hydrated on any event but will be hydrated by Qwik when its props change.\n- Both of the React components have `console.log` to show when the component is hydrated or re-rendered.\n\nThe `index.tsx` file has:\n- `count` - a signal that is used to track the current count.\n- Instantiates the `QButton` islands. The `onClick$` handler increments the `count` signal. Notice that Qwik automatically converts the `onClick` to `onClick$` prop allowing lazy loading of the event handlers.\n- Instantiates the `QDisplay` islands. The `count` signal is passed as a prop to the island.\n\nWhen you hover over the button, you will see that the `QButton` island is hydrated. When you click the button, you will see that the `QDisplay` island is hydrated and the count is updated. (The double execution of `QDisplay` is due to initial hydration first, and then updating the count second.)\n\nNotice that Qwik React only needs to eagerly hydrate components that have interactivity. Components that are dynamic, but don't have interactivity (such as `QDisplay` in this example) do not need to be eagerly hydrated instead they hydrate automatically when their props change.\n\nAlso notice that `console.log('Qwik Render');` never executes in the browser.\n\n## 4. `host:` Listeners\n\nIn the previous example, we had two islands. The `QButton` had to be eagerly hydrated so that React can set up the `onClick` event handler. This is a bit wasteful because the `QButton` island will never need to be re-rendered as its output is static. Clicking on the `QButton` will not cause the `QButton` island to re-render. In such a case, we can ask Qwik to register the `click` listener instead of hydrating the whole component in React just to attach a listener. This is done by using the `host:` prefix in the event name.\n\n<CodeSandbox src=\"/src/routes/demo/react/counter-two-islands-host/\" console={true}\n tabs={[\"index.tsx\",\"react.tsx\"]} style={{ height: '20em' }}>\n\n```tsx /host:onClick$/\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { QButton, QDisplay } from './react';\n\nexport default component$(() => {\n console.log('Qwik Render');\n const count = useSignal(0);\n return (\n <main>\n <QButton\n host:onClick$={() => {\n console.log('click', count.value);\n count.value++;\n }}\n >\n +1\n </QButton>\n <QDisplay count={count.value}></QDisplay>\n </main>\n );\n});\n```\n\n```tsx\n/** @jsxImportSource react */\nimport { qwikify$ } from '@qwik.dev/react';\nimport { type ReactNode } from 'react';\n\nfunction Button({ children }: { children?: ReactNode[] }) {\n console.log('React <Button/> Render');\n return <button>{children}</button>;\n}\n\nfunction Display({ count }: { count: number }) {\n console.log('React <Display count=' + count + '/> Render');\n return <div className=\"react\">Count: {count}</div>;\n}\n\nexport const QButton = qwikify$(Button);\nexport const QDisplay = qwikify$(Display);\n```\n\nNow hovering over the button will not do anything (no React hydration). Clicking on the button will cause Qwik to handle the event and update the signal which will in turn cause the hydration of the `QDisplay` island. Notice that the `QButton` island is never hydrated. Therefore this change allowed us to have an island that renders server side only and never needs to be hydrated in the browser, saving our user time.\n\n## 5. Projecting `children`\n\nA common use case is to pass content children to components. This works with Qwik React as well. In the React component just declare `children` in your props and use them as expected (See `react.tsx`).\n\n<CodeSandbox src=\"/src/routes/demo/react/children/\" console={true}\n tabs={[\"index.tsx\",\"react.tsx\"]} style={{ height: '20em' }}>\n\n```tsx /host:onClick$/\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { QFrame } from './react';\n\nexport default component$(() => {\n console.log('Qwik Render');\n const count = useSignal(0);\n return (\n <QFrame>\n <button\n onClick$={() => {\n console.log('click', count.value);\n count.value++;\n }}\n >\n +1\n </button>\n Count: {count}\n </QFrame>\n );\n});\n```\n\n```tsx\n/** @jsxImportSource react */\nimport { type ReactNode } from 'react';\nimport { qwikify$ } from '@qwik.dev/react';\n\nfunction Frame({ children }: { children?: ReactNode[] }) {\n console.log('React <Zippy/> Render');\n return (\n <div\n style={{\n display: 'inline-block',\n border: '1px solid black',\n borderRadius: '10px',\n padding: '5px',\n }}\n >\n {children}\n </div>\n );\n}\n\nexport const QFrame = qwikify$(Frame);\n```\n\nNotice that the `QFrame` island is never hydrated because it has no `eagerness` or any props which would trigger hydration. But also notice that the children do re-render when the signal changes and are correctly projected into the React `QFrame` island without the island being hydrated. This allows even more of the page to be rendered server-side and never rendered on the client.\n\n## 6. Using React libraries\n\nFinally, it is possible to use React libraries in your Qwik application. In this example [Material UI](https://mui.com/) and [Emotion](https://emotion.sh/docs/introduction) are used to render this React example.\n\n<CodeSandbox src=\"/src/routes/demo/react/mui/\"\n tabs={[\"react.tsx\", \"index.tsx\"]} style={{ height: '8em' }}>\n\n```tsx /host:onClick$/\n/** @jsxImportSource react */\nimport { qwikify$ } from '@qwik.dev/react';\nimport Tabs from '@mui/material/Tabs';\nimport Tab from '@mui/material/Tab';\nimport Box from '@mui/material/Box';\nimport { type ReactNode } from 'react';\n\nexport const Example = qwikify$(\n function Example({\n selected,\n onSelected,\n children,\n }: {\n selected: number;\n onSelected: (v: number) => any;\n children?: ReactNode[];\n }) {\n console.log('React <Example/> Render');\n return (\n <>\n <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>\n <Tabs\n value={selected}\n onChange={(e, v) => onSelected(v)}\n aria-label=\"basic tabs example\"\n >\n <Tab label=\"Item One\" />\n <Tab label=\"Item Two\" />\n <Tab label=\"Item Three\" />\n </Tabs>\n {children}\n </Box>\n </>\n );\n },\n { eagerness: 'hover' }\n);\n```\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { Example } from './react';\n\nexport default component$(() => {\n console.log('Qwik Render');\n const selected = useSignal(0);\n return (\n <Example\n selected={selected.value}\n onSelected$={(v) => (selected.value = v)}\n >\n Selected tab: {selected.value}\n </Example>\n );\n});\n```\n\nThe React example is hydrated on hover and works as you would expect.\n\n## 7. Using Qwik components inside React\n\nSo far we have seen how to use React components inside Qwik using `qwikify$()`. But what if you want to go the other direction — use a Qwik component inside a React tree?\n\nThe `reactify$()` function does exactly that. It wraps a Qwik `component$` so it can be rendered as a regular React component. This is useful when you have a `qwikify$()` island and want to embed Qwik components inside the React tree rendered by that island.\n\nThe Qwik component keeps its resumability benefits — it doesn't need hydration to become interactive.\n\n> **Note:** `reactify$()` components must be used inside a `qwikify$()` island. React trees only exist inside qwikify islands, so that's where reactified components live.\n\n```tsx /reactify$/ /qwikify$/\n/** @jsxImportSource react */\nimport { qwikify$, reactify$ } from '@qwik.dev/react';\nimport { QwikCounter } from './counter';\n\nconst Counter = reactify$(QwikCounter);\n\nfunction Card() {\n return (\n <div style={{ border: '2px solid #333', borderRadius: '8px', padding: '12px' }}>\n <h3>React Card</h3>\n <p>This Qwik counter resumes instantly:</p>\n <Counter label=\"Clicks\" />\n </div>\n );\n}\n\nexport const QCard = qwikify$(Card, { eagerness: 'idle' });\n```\n\n```tsx /component$/ /useSignal/\nimport { component$, useSignal } from '@qwik.dev/core';\n\nexport const QwikCounter = component$<{ label?: string }>((props) => {\n const count = useSignal(0);\n return (\n <button onClick$={() => count.value++}>\n {props.label}: {count.value}\n </button>\n );\n});\n```\n\n```tsx /QCard/\nimport { component$ } from '@qwik.dev/core';\nimport { QCard } from './react';\n\nexport default component$(() => {\n return (\n <main>\n <QCard />\n </main>\n );\n});\n```\n\nThe key pieces are:\n\n1. **`counter.tsx`** — A standard Qwik `component$` with `useSignal` for local state. Nothing special here.\n2. **`react.tsx`** — `reactify$(QwikCounter)` creates a React component (`Counter`) that renders the Qwik counter. A React `Card` component wraps it with some layout. The whole thing is wrapped in `qwikify$()` so it can be used from Qwik.\n3. **`index.tsx`** — A normal Qwik route that renders `<QCard />`.\n\nThe counter button is interactive immediately after the page loads — the Qwik component resumes from the serialized state without waiting for React hydration.\n\n# Rules\n\nLet's look at this example to better understand the rules of Qwik React.\n\n```tsx title=\"src/integrations/react/mui.tsx\"\n/** @jsxImportSource react */\n\nimport { qwikify$ } from '@qwik.dev/react';\nimport { Alert, Button, Slider } from '@mui/material';\nimport { DataGrid, GridColDef, GridValueGetterParams } from '@mui/x-data-grid';\n\nexport const MUIButton = qwikify$(Button);\nexport const MUIAlert = qwikify$(Alert);\nexport const MUISlider = qwikify$(Slider, { eagerness: 'hover' });\n```\n\n**Important**\nYou need to import `/** @jsxImportSource react */` at the top of your file, this is an instruction to the compiler to use React as the JSX factory.\n\nIn a nutshell, the rules are:\n\n1. Don't mix React and Qwik components in the same file.\n2. We recommend that you place all your react code inside the `src/integrations/react` folder.\n3. Add `/** @jsxImportSource react */` at the top of the files containing React code.\n4. Use `qwikify$()` to convert React components into Qwik components, that you can then import from Qwik modules.\n\nNow your Qwik can import `MUIButton` and use it as any other Qwik component:\n\n```tsx\nimport { component$ } from '@qwik.dev/core';\nimport { MUIAlert, MUIButton } from '~/integrations/react/mui';\n\nexport default component$(() => {\n return (\n <>\n <MUIButton client:hover>Hello this is a button</MUIButton>\n\n <MUIAlert severity=\"warning\">This is a warning from Qwik</MUIAlert>\n </>\n );\n});\n```\n\n## `qwikify$()`\n\nThe `qwikify$(ReactCmp, options?): QwikCmp` allows to implement partial hydration of React components. It works by wrapping the SSR and hydration logic of React into a Qwik component that can execute React's `renderToString()` during SSR and dynamically call `hydrateRoot()` when specified.\n\nNotice that by default no React code will run in the browser, meaning that React component will NOT be interactive by default, for example, in the following example, we _qwikify_ the [Slider](https://mui.com/material-ui/react-slider/) component from MUI, but it will not be interactive (it is missing an `eagerness` property to tell Qwik when the React component should be hydrated in the browser.)\n\n<CodeSandbox src=\"/src/routes/demo/react/slider/\" console={true}\n tabs={[\"react.tsx\",\"index.tsx\"]} style={{ height: '20em' }}>\n\n```tsx /host:onClick$/\n/** @jsxImportSource react */\nimport { qwikify$ } from '@qwik.dev/react';\nimport { Slider } from '@mui/material';\nexport const MUISlider = qwikify$<typeof Slider>(\n Slider\n // Uncomment next line to make component interactive in browser\n // { eagerness: 'hover' }\n);\n```\n\n```tsx\nimport { component$, useSignal } from '@qwik.dev/core';\nimport { QFrame } from './react';\n\nexport default component$(() => {\n console.log('Qwik Render');\n const count = useSignal(0);\n return (\n <QFrame>\n <button\n onClick$={() => {\n console.log('click', count.value);\n count.value++;\n }}\n >\n +1\n </button>\n Count: {count}\n </QFrame>\n );\n});\n```\n\n## Limitations\n\n### Every qwikified react component is isolated\n\nEach instance of a qwikified react component becomes an independent React app. Fully isolated.\n\n```tsx\nexport const MUISlider = qwikify$(Slider);\n\n<MUISlider></MUISlider>\n<MUISlider></MUISlider>\n```\n\n- Each `MUISlider` is a fully isolated React application, with its own state, lifecycle, etc.\n- Styles will be duplicated\n- State will not be shared\n- [Context](https://react.dev/learn/passing-data-deeply-with-context) will not be inherited.\n- Islands will [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot) independently\n\n### By default interactivity is disabled\n\nBy default, qwikified components will not be interactive, please look at the next section to learn how to enable interactivity.\n\n### Use `qwikify$()` as a migration strategy\n\nUsing React components in Qwik is a great way to migrate your application to Qwik, but it's not a silver bullet, you will need to rewrite your components to take advantage of Qwik's features.\n\nIt's also a great way to enjoy the React ecosystem, like [threejs](https://github.com/pmndrs/react-three-fiber) or [data-grid libs](https://mui.com/x/react-data-grid/).\n\nDon't abuse `qwikify$()` to build your application, as overusing will cause performance gains to be lost.\n\n### Build wide islands, not leaf nodes\n\nFor example, if you need to use several MUI components, to build a list, don't qwikify each individual MUI component, instead, build the whole list as a single qwikified React component.\n\n#### GOOD: Wide island\n\nA single qwikified component, with all the MUI components inside. Styles will not be duplicated, and context and theming will work as expected.\n\n```tsx\nimport * as React from 'react';\nimport List from '@mui/material/List';\nimport ListItem from '@mui/material/ListItem';\nimport ListItemText from '@mui/material/ListItemText';\nimport ListItemAvatar from '@mui/material/ListItemAvatar';\nimport Avatar from '@mui/material/Avatar';\nimport ImageIcon from '@mui/icons-material/Image';\nimport WorkIcon from '@mui/icons-material/Work';\nimport BeachAccessIcon from '@mui/icons-material/BeachAccess';\n\n// Qwikify the whole list\nexport const FolderList = qwikify$(() => {\n return (\n <List sx={{ width: '100%', maxWidth: 360, bgcolor: 'background.paper' }}>\n <ListItem>\n <ListItemAvatar>\n <Avatar>\n <ImageIcon />\n </Avatar>\n </ListItemAvatar>\n <ListItemText primary=\"Photos\" secondary=\"Jan 9, 2014\" />\n </ListItem>\n <ListItem>\n <ListItemAvatar>\n <Avatar>\n <WorkIcon />\n </Avatar>\n </ListItemAvatar>\n <ListItemText primary=\"Work\" secondary=\"Jan 7, 2014\" />\n </ListItem>\n <ListItem>\n <ListItemAvatar>\n <Avatar>\n <BeachAccessIcon />\n </Avatar>\n </ListItemAvatar>\n <ListItemText primary=\"Vacation\" secondary=\"July 20, 2014\" />\n </ListItem>\n </List>\n );\n});\n```\n\n#### BAD: Leaf nodes\n\nLeaf nodes are qwikified independently, effectively rendering dozens of nested react applications, each fully isolated from the others, and styles being duplicated.\n\n```tsx\nimport * as React from 'react';\nimport List from '@mui/material/List';\nimport ListItem from '@mui/material/ListItem';\nimport ListItemText from '@mui/material/ListItemText';\nimport ListItemAvatar from '@mui/material/ListItemAvatar';\nimport Avatar from '@mui/material/Avatar';\nimport ImageIcon from '@mui/icons-material/Image';\nimport WorkIcon from '@mui/icons-material/Work';\nimport BeachAccessIcon from '@mui/icons-material/BeachAccess';\n\nexport const MUIList = qwikify$(List);\nexport const MUIListItem = qwikify$(ListItem);\nexport const MUIListItemText = qwikify$(ListItemText);\nexport const MUIListItemAvatar = qwikify$(ListItemAvatar);\nexport const MUIAvatar = qwikify$(Avatar);\nexport const MUIImageIcon = qwikify$(ImageIcon);\nexport const MUIWorkIcon = qwikify$(WorkIcon);\nexport const MUIBeachAccessIcon = qwikify$(BeachAccessIcon);\n```\n\n```tsx\n// Qwik component using dozens of nested React islands\n// Each MUI-* it's an independent React application\nexport const FolderList = component$(() => {\n return (\n <MUIList sx={{ width: '100%', maxWidth: 360, bgcolor: 'background.paper' }}>\n <MUIListItem>\n <MUIListItemAvatar>\n <MUIAvatar>\n <MUIImageIcon />\n </MUIAvatar>\n </MUIListItemAvatar>\n <MUIListItemText primary=\"Photos\" secondary=\"Jan 9, 2014\" />\n </MUIListItem>\n <MUIListItem>\n <MUIListItemAvatar>\n <MUIAvatar>\n <MUIWorkIcon />\n </MUIAvatar>\n </MUIListItemAvatar>\n <MUIListItemText primary=\"Work\" secondary=\"Jan 7, 2014\" />\n </MUIListItem>\n <MUIListItem>\n <MUIListItemAvatar>\n <MUIAvatar>\n <MUIBeachAccessIcon />\n </MUIAvatar>\n </MUIListItemAvatar>\n <MUIListItemText primary=\"Vacation\" secondary=\"July 20, 2014\" />\n </MUIListItem>\n </MUIList>\n );\n});\n```\n\n## Adding interactivity\n\nIn order to add interactivity, in React terminology we need to [hydrate](https://react.dev/reference/react-dom/hydrate), usually in React applications this hydration task happens unconditionally at load time, [adding a massive overhead](https://www.builder.io/blog/hydration-is-pure-overhead) and making sites slow.\n\nQwik allows you decide when to hydrate your components, by using the `client:` JSX properties, this technique is commonly called partial hydration, popularized by [Astro](https://astro.build/).\n\n```diff\nexport default component$(() => {\n return (\n <>\n- <MUISlider></MUISlider>\n+ <MUISlider client:visible></MUISlider>\n </>\n );\n});\n```\n\nQwik comes with different strategies out of the box:\n\n### `client:load`\n\nThe component eagerly hydrates when the document loads.\n\n```tsx\n<MUISlider client:load></MUISlider>\n```\n\n**Use case:** Immediately-visible UI elements that need to be interactive as soon as possible.\n\n### `client:idle`\n\nThe component eagerly hydrates when the browser first becomes idle, ie, when everything important has already run before.\n\n```tsx\n<MUISlider client:idle></MUISlider>\n```\n\n**Use case:** Lower-priority UI elements that don’t need to be immediately interactive.\n\n### `client:visible`\n\nThe component eagerly hydrates when it becomes visible in the viewport.\n\n```tsx\n<MUISlider client:visible></MUISlider>\n```\n\n**Use case:** Low-priority UI elements that are either far down the page (“below the fold”) or so resource-intensive to load that you would prefer not to load them at all if the user never saw the element.\n\n### `client:hover`\n\nThe component eagerly hydrates when the mouse is over the component.\n\n```tsx\n<MUISlider client:hover></MUISlider>\n```\n\n**Use case:** Lowest-priority UI elements which interactivity is not crucial, and only needs to run in desktop.\n\n### `client:signal`\n\nThis is an advanced API that allows to hydrate the component whenever the passed signal becomes `true`.\n\n```tsx\nexport default component$(() => {\n const hydrateReact = useSignal(false);\n return (\n <>\n <button onClick$={() => (hydrateReact.value = true)}>Hydrate Slider when click</button>\n\n <MUISlider client:signal={hydrateReact}></MUISlider>\n </>\n );\n});\n```\n\nThis effectively allows you to implement custom strategies for hydration.\n\n### `client:event`\n\nThe component eagerly hydrates when specified DOM events are dispatched.\n\n```tsx\n<MUISlider client:event=\"click\"></MUISlider>\n```\n\n### `client:only`\n\nWhen `true`, the component will not run in SSR, only in the browser.\n\n```tsx\n<MUISlider client:only></MUISlider>\n```\n\n## Listening to React events\n\nEvents in React are handled by passing a function as a property to the component, for example:\n\n```tsx\n// React code (won't work in Qwik)\n\nimport { Slider } from '@mui/material';\n\n<Slider onChange={() => console.log('value changed')}></Slider>;\n```\n\nThe `qwikify()` function will convert this into a Qwik component that will also expose the React events as Qwik [QRLs](/docs/advanced/qrl.md):\n\n```tsx\nimport { Slider } from '@mui/material';\nimport { qwikify$ } from '@qwik.dev/react';\nconst MUISlider = qwikify$(Slider);\n\n<MUISlider client:visible onChange$={() => console.log('value changed')} />;\n```\n\nWe use the `client:visible` property to eagerly hydrate the component, otherwise the component would not be interactive and the events would never be dispatched.\n\n## Host element\n\nWhen wrapping a React component with `qwikify$()`, under the hood, a new DOM element is created, such as:\n\n```html\n<qwik-react>\n <button class=\"MUI-button\"></button>\n</qwik-react>\n```\n\nThe tag name of the wrapper element is configurable via `tagName`: `qwikify$(ReactCmp, { tagName: 'my-react' })`.\n\n### Listen to DOM events without hydration\n\nThe host element is not part of React, meaning that hydration is not necessary to listen for events, in order to add custom attributes and events to the host element, you can use the `host:` prefix in the JSX properties, such as:\n\n```tsx\n<MUIButton\n host:onClick$={() => {\n console.log('click a react component without hydration!!');\n }}\n/>\n```\n\nThis will effectively allow you to respond to a click in a [MUI button](https://mui.com/material-ui/react-button/) without downloading a single byte of React code.\n\n‍Happy hacking!\n"},{"id":"/docs/integrations/storybook/","title":"Storybook | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/storybook/","content":"# Storybook\n\n[Storybook](https://storybook.js.org/) is a frontend workshop for building UI components and pages in isolation. Thousands of teams use it for UI development, testing, and documentation. It's open source and free.\n\nSince version 7.0, Storybook supports Vite natively, which means it has first-class support for Qwik too.\n\n## Usage\n\nYou can add Storybook to your existing app, or library use:\n\n```shell\npnpm run qwik add storybook\n```\n\nThe previous command installs the necessary dependencies and adds an example component and stories\n\nNow you can serve the Storybook dashboard:\n\n```shell\npnpm run storybook\n```\n\n## Examples\n\n### Simple component\n\nThe following demonstrates a simple story that uses a qwik component:\n\n```tsx title=\"src/components/button.tsx\"\nimport { component$ } from \"@qwik.dev/core\";\n\nexport interface ButtonProps {\n label: string;\n}\n\nexport const Button = component$<ButtonProps>(({label}) => {\n return (\n <button>\n {label}\n </button>\n );\n});\n```\n\n```tsx title=\"src/components/button.stories.tsx\"\nimport type { Meta, StoryObj } from \"storybook-framework-qwik\";\nimport {Button, type ButtonProps} from \"./button\";\n\nconst meta: Meta<ButtonProps> = {\n component: Button,\n};\n\nexport default meta;\ntype Story = StoryObj<ButtonProps>;\n\nexport const Primary: Story = {\n args: {\n label: \"Hello World\",\n }\n};\n```\n\n### Component That Uses Qwik Router\n\nWhen using Qwik Router, you must pass a context to the story by using the [`<QwikRouterMockProvider>`](https://qwik.dev/docs/api/#qwikroutermockprovider):\n\n```tsx title=\"src/components/with-link.tsx\"\nimport { component$ } from \"@qwik.dev/core\";\nimport { Link } from \"@qwik.dev/router\";\n\nexport const WithLink = component$(() => {\n return (\n <Link href=\"https://google.com\">Google Link</Link>\n );\n});\n```\n\n```tsx title=\"src/components/with-link.stories.tsx\"\nimport type { Meta, StoryObj } from \"storybook-framework-qwik\";\nimport { QwikRouterMockProvider } from \"@qwik.dev/router\";\n\nimport { WithLink } from \"./with-link\";\n\nconst meta: Meta = {\n component: WithLink,\n};\n\ntype Story = StoryObj;\nexport default meta;\n\nexport const Primary: Story = {\n render: () =>\n <QwikRouterMockProvider>\n <WithLink />\n </QwikRouterMockProvider>\n};\n```\n\nFor more information please refer to the [storybook documentation.](https://storybook.js.org/docs)\n"},{"id":"/docs/integrations/styled-vanilla-extract/","title":"Styled Vanilla Extract | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/styled-vanilla-extract/","content":"# Styled Vanilla Extract\n\nStyled-vanilla-extract is a CSS framework built on top of [vanilla-extract](https://vanilla-extract.style/) that delivers a modern and performant CSS-in-JS with Zero-runtime.\n\nThis integration supports two ways of styling:\n\n- Using [Vanilla Extract](https://vanilla-extract.style/) directly.\n- [Styled-components](https://styled-components.com/) powered by Vanilla-extract\n\n## Usage\n\nYou can add `styled-vanilla-extract` easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add styled-vanilla-extract\n```\n\nAfter the installation a new route will be created in your project, showcasing the usage of the library in a new component.\n\n### The Vanilla Extract way\n\nPlease refer to the official docs for more information about [Vanilla Extract](https://vanilla-extract.style/documentation/getting-started).\n\n```tsx title=\"styles.css.ts\"\nimport { style } from 'styled-vanilla-extract/qwik';\n\nexport const blueClass = style({\n display: 'block',\n width: '100%',\n height: '500px',\n background: 'blue',\n});\n```\n\n```tsx title=\"component.tsx\"\nimport { blueClass } from './styles.css';\n\nexport const Cmp = component$(() => {\n return <div class={blueClass} />;\n});\n```\n\n```shell\npnpm run qwik add styled-vanilla-extract\n```\n\nWhile extremely popular, emotion and other CSS-in-JS libs are not the best choice for Qwik. [They are not optimized for runtime performance and they don't have a good SSR streaming support](https://dev.to/srmagura/why-were-breaking-up-wiht-css-in-js-4g9b), leading to a degraded server and client performance.\n\n## Styled-components\n\nUsing the same integration, you have a styled-components powered by Vanilla Extract, use the exported `styled` function to create your components.\n\n```tsx title=\"styles.css.ts\"\nimport { styled } from 'styled-vanilla-extract/qwik';\n\nexport const BlueBox = styled.div`\n display: block;\n width: 100%;\n height: 500px;\n background: blue;\n`;\n```\n\n```tsx title=\"component.tsx\"\nimport { BlueBox } from './styles.css';\n\nexport const Cmp = component$(() => {\n return <BlueBox />;\n});\n```\n"},{"id":"/docs/integrations/supabase/","title":"Supabase | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/supabase/","content":"# Supabase\n\nThe `Supabase` JS library plays nicely with the server-side APIs from Qwik such as `routeLoader$`, `routeAction$` or `server$`.\n\nFirst, install supabase in your Qwik project:\n\n```shell\npnpm install @supabase/supabase-js supabase-auth-helpers-qwik\n```\n\nThe second step would be to add the `PUBLIC_SUPABASE_URL` and `PUBLIC_SUPABASE_ANON_KEY` environment variables to `.env` file, the \"anon\" key is safe to be exposed in the client-side.\n\n```bash\nPUBLIC_SUPABASE_URL=https://xxxxxxx.supabase.co\nPUBLIC_SUPABASE_ANON_KEY=eyJhb.......\n```\n\nYou should be able to get these values from the Supabase dashboard, create a new `.env.local` file at the root of the project and paste them there.\n\nIt's possible to use Supabase with Qwik completely client-side, however, you would lose some of the performance benefits that you can achieve with leveraging the server. For a working example and code head over to [this repository](https://github.com/hamatoyogi/qwik-supabase-example).\n\n## Server-side\n\nThe Supabase client can now be used server-side - in `routeLoader`s and `routeAction`s - by calling the `createServerClient` function.\n\n```tsx\nimport { routeLoader$ } from '@qwik.dev/router';\nimport { createServerClient } from 'supabase-auth-helpers-qwik';\n\nexport const useDBTest = routeLoader$(async (requestEv) => {\n const supabaseClient = createServerClient(\n requestEv.env.get(\"PUBLIC_SUPABASE_URL\")!,\n requestEv.env.get(\"PUBLIC_SUPABASE_ANON_KEY\")!,\n requestEv\n );\n const { data } = await supabaseClient.from('test').select('*')\n return { data };\n});\n```\n"},{"id":"/docs/integrations/tailwind-v3/","title":"Tailwind | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/tailwind-v3/","content":"# Tailwind\nTailwind is a CSS framework that provides us with single-purpose utility classes which are\nopinionated for the most part, and which help us design our web pages from right inside our\nmarkup or `.js/.jsx/.ts/.tsx/.mdx` files. [Tailwindcss Website](https://tailwindcss.com/)\n## Usage\nYou can add Tailwind easily by using the following Qwik starter script:\n```shell\npnpm run qwik add tailwind-v3\n```\n\nThe previous command updates your app with the necessary dependencies.\n\nIt also adds new files to your project folder:\n\n- `postcss.config.js`\n- `tailwind.config.js`\n- `.vscode/settings.json`\n\nand modifies your `src/global.css` to include\n\n```css title=\"src/global.css\"\n\n# global.css file\n\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n...stuff...\n```\n"},{"id":"/docs/integrations/tailwind/","title":"Tailwind | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/tailwind/","content":"# Tailwind\n\nTailwind is a CSS framework that provides us with single-purpose utility classes which are\nopinionated for the most part, and which help us design our web pages from right inside our\nmarkup or `.js/.jsx/.ts/.tsx/.mdx` files. [Tailwindcss Website](https://tailwindcss.com/)\n\nThis page contains updated instructions for tailwind v4. If you need to use tailwind v3, you can find the relevant documentation [here](/docs/integrations/tailwind-v3.md).\n\n## Usage\n\nYou can add Tailwind v4 easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add tailwind\n```\n\nThe previous command updates your app with the necessary dependencies,\nand modifies the following files\n\n```css title=\"src/global.css\"\n\n@import \"tailwindcss\";\n\n/* ... other css stuff ... */\n\n/* ... to customize tailwind follow guidelines at https://tailwindcss.com/docs/theme ... */\n\n/* Explicitly registering sources */\n/* @source \"../node_modules/@your/ui-lib\"; */\n\n/* Setting your base path */\n/* @import \"tailwindcss\" source(\"../src\"); */\n\n/* Disabling automatic detection of source file */\n/* @import \"tailwindcss\" source(none); */\n\n```\n\n```ts title=\"vite.config.ts\"\nimport { defineConfig , type UserConfig} from 'vite'\nimport tailwindcss from '@tailwindcss/vite'\n// … other imports ...\n\nexport default defineConfig(({ command, mode }): UserConfig => {\n return {\n plugins: [\n tailwindcss(),\n // ... other plugins ...\n ]\n // ... other stuff ...\n }\n }\n)\n```\n"},{"id":"/docs/integrations/tauri/","title":"Tauri | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/tauri/","content":"# Tauri\n\nTauri is a framework to build desktop applications with any frontend framework and a Rust core.\n\nLearn more on the [Tauri website](https://tauri.app/v1/guides/getting-started/setup/qwik/).\n\n## Adapter\nMake sure you use the [Static Adapter](https://qwik.dev/docs/deployments/static/).\n\nThen you can build your app with\n\n```shell\npnpm run build\n```\n\n## Add Tauri\n\nTo install Tauri:\n\n```shell\npnpm install @tauri-apps/cli\n```\n\nIn your `package.json`, add this script:\n\n```json title=\"package.json\"\n\"scripts\": {\n \"tauri\": \"tauri\"\n}\n```\n\nThen, to scaffold a minimal Rust project that is pre-configured to use Tauri, open a terminal and run the following command:\n\n```shell\npnpm run tauri init\n```\n\nThis command will walk you through a quick setup:\n1. *What is your app name?*\nThis will be the name of your final bundle and what the OS will call your app. You can use any name you want here.\n1. *What should the window title be?*\nThis will be the title of the default main window. You can use any title you want here.\n3. *Where are your web assets (HTML/CSS/JS) located relative to the `<current dir>/src-tauri/tauri.conf.json` file that will be created?*\nThis is the path that Tauri will load your frontend assets from when building for production.\nUse `../dist` for this value.\n4. *What is the URL of your dev server?*\nThis can be either a URL or a file path that Tauri will load during development.\nUse `http://localhost:5173` for this value.\n5. *What is your frontend dev command?*\nThis is the command used to start your frontend dev server.\nUse `dev` command **(make sure to adapt this to use the package manager of your choice)**.\n6. *What is your frontend build command?*\nThis is the command to build your frontend files.\nUse `build` command **(make sure to adapt this to use the package manager of your choice)**.\n\nThat's it! Finally you can run this command to start developing your app:\n\n```shell\npnpm run tauri dev\n```\n"},{"id":"/docs/integrations/turso/","title":"Turso | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/turso/","content":"# Turso\n\n[Turso] is the edge database based on [libSQL] - the open-source\nopen-contribution fork of SQLite.\n\nIt enables you to place your data close to your users in over 35 locations\naround the world.\n\n## Usage\n\nYou can easily add Turso by using the following Qwik starter script:\n\n```shell\npnpm run qwik add turso\n```\n\nThis command will add the necessary dependencies to use Turso.\n\nIt also adds new files inside your project folder:\n\n- `src/lib/turso.ts`\n\nand adds or modifies a `.env.local` file to include\n\n```txt title=\".env.local\"\nPRIVATE_TURSO_DATABASE_URL=\nPRIVATE_TURSO_AUTH_TOKEN=\n```\n\n## Using file databases\n\nFor local development and CI integration, it is ideal to use local database files.\n\nFirst, check if SQLite is installed in your machine by running `sqlite3\n--version`. If you get anything other than a version number (e.g `0-14 20:58:05\n554764a6e721fab307c63a4f98cd958c8428a5d9d8edfde951858d6fd02daapl`), visit [this\nlink for installation instructions].\n\nProceed to create an SQLite file database by running the following command.\n\n```sh\nsqlite3 foo.db\n```\n\nCreate your database schema.\n\n```sh\nsqlite> create table todo (id integer not null, task text, done int default 0);\n```\n\nSeed some data into your table.\n\n```sh\nsqlite> insert into todo(id, task) values(1, \"Go to the gym\");\nsqlite> insert into todo(id, task) values(2, \"Buy groceries\");\n```\n\nQuit the shell `.quit`\n\nThen, assign the database file path to the `PRIVATE_TURSO_DATABASE_URL` environment variable\ninside `.env.local`.\n\n```\nPRIVATE_TURSO_DATABASE_URL=file:foo.db\n```\n\nA database token is not needed when working with file databases and `createClient` must be imported from `@libsql/client` since importing from `@libsql/client/web` [does not support local file URLs](https://docs.turso.tech/sdk/ts/reference#local-development).\n\n## Using a Turso database\n\nWhen you want to deploy your project to production, you can then [install the\nTurso CLI] to your machine and [create a Turso database].\n\nUse the Turso CLI's `db shell` command to issue queries to your database.\n\n```sh\nturso db shell <database-name>\n```\n\nCreate your database schema.\n\n```sh\n→ create table todo (id integer not null, task text, done int default 0);\n```\n\nSeed some data into your table.\n\n```sh\n→ insert into todo(id, task) values(1, \"Go to the gym\");\n→ insert into todo(id, task) values(2, \"Buy groceries\");\n```\n\nQuit the shell `.quit`\n\nUse the following instructions to obtain your Turso database credentials and\nassign them to the environment variables inside your deployment environment.\n\nStarting with the database url, run the following command.\n\n```sh\nturso db show <database-name> --url\n```\n\nCopy the resulting URL and assign it to the `PRIVATE_TURSO_DATABASE_URL` environment variable.\n\nAnd, for the database authentication token, run the command.\n\n```sh\nturso db tokens create <database-name>\n```\n\nCopy the resulting token and assign it to the `PRIVATE_TURSO_AUTH_TOKEN` environment\nvariable.\n\n## How to use Turso inside Qwik\n\nImport `tursoClient` inside your routes and initiate a database client instance\nwithin Qwik's server-side APIs that expose the `RequestEvent` object, such as\n`routeLoader$()`, `routeAction$()`, `server$()` and endpoint handlers such as\n`onGet`, `onPost`, `onRequest`.\n\n```ts\nimport { tursoClient } from \"~/utils/turso\";\n\nexport const useRouteLoader = routeLoader$(\n async (requestEvent: RequestEventBase) => {\n const client = tursoClient(requestEvent);\n\n const items = await client.execute(\"select * from table\");\n\n return {\n items: items.rows,\n };\n }\n);\n```\n\nFor more information, please visit the [Turso docs].\n\n[Turso]: https://turso.tech\n[libSQL]: https://turso.tech/libsql\n[this link for installation instructions]: https://sqlite.org/download.html\n[install the Turso CLI]:\n https://docs.turso.tech/reference/turso-cli#installation\n[create a Turso database]:\n https://docs.turso.tech/quickstart\n[Turso docs]: https://docs.turso.tech\n"},{"id":"/docs/integrations/vitest/","title":"Vitest | Integrations","description":"","url":"https://next.qwik.dev/docs/integrations/vitest/","content":"# Vitest\n\n[Vitest](https://vitest.dev/) is a blazing-fast unit test framework powered by Vite. Because Qwik Router uses [Vite](https://vitejs.dev/) by default, Vitest is our defacto unit test framework.\n\n## Usage\n\nYou can add vitest easily by using the following Qwik starter script:\n\n```shell\npnpm run qwik add vitest\n```\n\nAfter running the command, vitest will be installed and a new component will be added to your project. The component will be added to the `src/components/example` directory as well as a new unit test named `example.spec.tsx`.\nIf you are looking for an example for a Component with Qwik Router, see [QwikRouterMockProvider](/docs/api.md#qwikroutermockprovider).\n\n```tsx title=\"example.spec.tsx\"\nimport { createDOM } from '@qwik.dev/core/testing';\nimport { test, expect } from 'vitest';\nimport { ExampleTest } from './example';\n\ntest(`[ExampleTest Component]: Should render `, async () => {\n const { screen, render } = await createDOM();\n await render(<ExampleTest flag={true} />);\n expect(screen.outerHTML).toContain('');\n const div = screen.querySelector('.icon') as HTMLElement;\n expect(div.outerHTML).toContain('');\n});\n\ntest(`[ExampleTest Component]: Should render `, async () => {\n const { screen, render } = await createDOM();\n await render(<ExampleTest flag={false} />);\n expect(screen.outerHTML).toContain('');\n});\n\ntest(`[ExampleTest Component]: Click counter +1`, async () => {\n const { screen, render, userEvent } = await createDOM();\n await render(<ExampleTest flag={true} />);\n\n expect(screen.outerHTML).toContain('Count:0');\n\n const spanBefore = screen.querySelector('span') as HTMLDivElement;\n await userEvent('.btn-counter', 'click');\n expect(spanBefore.innerHTML).toEqual('Count:1');\n\n const spanAfter = screen.querySelector('span') as HTMLDivElement;\n await userEvent('button', 'click');\n expect(spanAfter.innerHTML).toEqual('Count:2');\n});\n```\n"},{"id":"/docs/labs/catch/","title":"Catch | Experimental","description":"","url":"https://next.qwik.dev/docs/labs/catch/","content":"# `Catch`\n\n**Stage:** `implementation`\n\n `Catch` is experimental and currently a technical preview. Its API and behavior may still\n change as we gather feedback from real-world usage.\n\n`Catch` renders `fallback$` instead of its children when a descendant throws.\n\nIt catches during SSR, during out-of-order streaming and on the client, and it composes with\n`Pending` in either order.\n\nTo use it, add `experimental: ['catchBoundary']` to your `qwikVite` plugin options:\n\n```ts\n// vite.config.ts\nimport { defineConfig } from 'vite';\nimport { qwikVite } from '@qwik.dev/core/optimizer';\n\nexport default defineConfig(() => {\n return {\n plugins: [\n qwikVite({\n experimental: ['catchBoundary'],\n }),\n ],\n };\n});\n```\n\n```tsx /Catch/ /fallback$/\nimport { $, Catch, component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <Catch\n fallback$={$((error, reset) => (\n <div role=\"alert\">\n <p>{error.message}</p>\n <button onClick$={() => reset()}>Try again</button>\n </div>\n ))}\n >\n <Profile />\n </Catch>\n );\n});\n```\n\n## Props\n\n### `fallback$`\n\nRequired. Receives the caught error and a `reset` QRL, and returns the JSX to render in place of the\nchildren.\n\n```tsx\nfallback$: QRL<(error: Error & { digest?: string }, reset: QRL<() => void>) => JSXOutput>;\n```\n\nThe error is always an `Error`, so `{error.message}` is safe: a value that is not an `Error` arrives\nwrapped, with the original on `cause`.\n\nWrap `reset` in a handler — `onClick$={() => reset()}`, not `onClick$={reset}` — so it stays wired in\na streamed fallback.\n\n### `onError$`\n\nOptional. A side effect for reporting; it never affects what renders.\n\n```tsx\nonError$?: QRL<(error: Error, info: CatchInfo) => void>;\n```\n\nIt receives the original error and a `CatchInfo`:\n\n- `phase` — where the error came from: `'render'`, `'event'`, or `'hook'` (task throws report\n `'hook'`).\n- `boundaryId` — identifies the boundary within the page.\n- `digest` — the code a production fallback shows for this error, so a user's bug report matches\n your logs.\n\nAn error caught during SSR is reported again if the client re-derives it, so dedupe in your\nreporter.\n\n## Reset\n\n`reset` clears the error and re-renders the children. If the condition that caused the throw is\ngone, the content comes back; if it still throws, the fallback renders again.\n\n```tsx\nfallback$={$((error, reset) => (\n <button onClick$={() => reset()}>Retry</button>\n))}\n```\n\n## Production redaction\n\nRedaction follows the error's origin. A server-origin error reaches the fallback as a generic\nmessage plus a `digest` — server details never leave the server. A client-origin error renders as\nthrown: its message already lives in the browser bundle. An SSR-caught error the client re-derives\n(reset, owner re-render) becomes client-origin and shows raw.\n\n```tsx\nfallback$={$((error) => (\n <p>\n Something went wrong. {error.digest && <code>{error.digest}</code>}\n </p>\n))}\n```\n\nLog `info.digest` from `onError$` to match a reported code back to the error in your logs. The\n`digest` is client-spoofable — branch on it for display, never for trust.\n\nFor a deliberate user-facing throw, use your own class and branch on it in the fallback:\n\n```tsx\nexport class DisplayError extends Error {}\n\nfallback$={$((error) => (\n <p>{error instanceof DisplayError ? error.message : 'Something went wrong.'}</p>\n))}\n```\n\nThe same throw during SSR is server-origin and redacts, so keep display throws client-side — or\nrender the message conditionally instead of throwing.\n\n## Caching\n\nAn error caught during SSR still responds 200, so the framework refuses to let that response be\ncached: it sends `Cache-Control: no-store` when the error precedes the first chunk, and it always\nskips the router's SSR cache. When this disables caching you configured — `cacheControl()` or a\nroute's `eTag`/`cacheKey` — the server logs a warning. A route that keeps erroring is therefore\nuncacheable: watch `onError$` and your server logs.\n\n## `transformError`\n\nA server render option that projects a thrown error into the `Error` the fallback displays during\nSSR. `onError$` still receives the original.\n\n```ts\n// entry.ssr.tsx\nexport default function (opts: RenderToStreamOptions) {\n return renderToStream(<Root />, {\n ...opts,\n transformError: (error) => (error instanceof HttpError ? new Error(error.publicMessage) : undefined),\n });\n}\n```\n\nReturn an `Error` to project it, or `undefined`/`null` to decline and fall through to the default\npolicy. Any other return, or a throw, redacts to the generic error. It is called synchronously, so\nit cannot be `async`.\n\n## Related\n\n- For loading states, see [Pending](/docs/labs/pending.md)\n- For the generated API entries, see [API Reference](/api/qwik.md#catch)\n"},{"id":"/docs/labs/devtools/","title":"🧪 Devtools","description":"","url":"https://next.qwik.dev/docs/labs/devtools/","content":"# Devtools\n\n**Stage:** `prototyping`\n\nSee https://github.com/QwikDev/devtools.\n"},{"id":"/docs/labs/each/","title":"🧪 Each | Experimental","description":"","url":"https://next.qwik.dev/docs/labs/each/","content":"# `Each`\n\n**Stage:** `implementation`\n\n `Each` is experimental and currently a technical preview. Its API and behavior may still change\n as we gather feedback from real-world usage.\n\n`Each` is a built-in Qwik component for rendering keyed lists.\n\nIt is most useful when list items have a stable identity and you want Qwik to preserve and move\nexisting rows instead of re-rendering the whole list when the order changes.\n\nTo use it, you must add `experimental: ['each']` to your `qwikVite` plugin options:\n\n```ts\n// vite.config.ts\nimport { defineConfig } from 'vite';\nimport { qwikVite } from '@qwik.dev/core/optimizer';\n\nexport default defineConfig(() => {\n return {\n plugins: [\n qwikVite({\n experimental: ['each'],\n }),\n ],\n };\n});\n```\n\n```tsx /Each/ /key$/ /item$/\nimport { Each, component$, useSignal } from '@qwik.dev/core';\n\ntype Todo = {\n id: string;\n label: string;\n};\n\nexport default component$(() => {\n const todos = useSignal<Todo[]>([\n { id: '1', label: 'Write docs' },\n { id: '2', label: 'Review keys' },\n { id: '3', label: 'Ship it' },\n ]);\n\n return (\n <>\n <button onClick$={() => (todos.value = [...todos.value].reverse())}>\n Reverse order\n </button>\n\n <ul>\n <Each\n items={todos.value}\n key$={(todo) => todo.id}\n item$={(todo) => <li>{todo.label}</li>}\n />\n </ul>\n </>\n );\n});\n```\n\n## Props\n\n`Each` accepts three props:\n\n- `items`: the array to render\n- `key$`: returns a stable unique key for each item\n- `item$`: returns the JSX for one item\n\n`item$` must return a single JSX node. If you need multiple siblings, wrap them in a container\nelement or a `Fragment`.\n\n```tsx /Fragment/ /Each/\nimport { Each, Fragment, component$ } from '@qwik.dev/core';\n\nexport default component$(() => {\n return (\n <ul>\n <Each\n items={['a', 'b', 'c']}\n key$={(item) => item}\n item$={(item) => (\n <Fragment>\n <li>Item {item}</li>\n </Fragment>\n )}\n />\n </ul>\n );\n});\n```\n\n## `Each` vs `items.map()`\n\nIf your list items have stable keys, prefer `Each`.\n\nIt is the specialized keyed-list primitive in Qwik and is designed to preserve and move existing\nrows efficiently.\n\nUse `items.map()` for simple list rendering or when you do not have a stable key:\n\n```tsx\n<ul>\n {todos.value.map((todo) => (\n <li key={todo.id}>{todo.label}</li>\n ))}\n</ul>\n```\n\nQwik may also be able to optimize some keyed `.map()` patterns into `Each` under the hood in the\nfuture when it can prove the transformation is safe. For now, use `Each` explicitly when you want\nits keyed-row preservation behavior.\n\nPrefer `Each` when:\n\n- items have stable ids\n- rows are frequently reordered, inserted, or removed\n- you want to preserve existing row DOM and component instances\n\nPrefer `map()` when:\n\n- there is no stable key for the item\n- you want ordinary JSX list rendering without `Each`'s keyed-row preservation behavior\n- the row output should be recomputed from replaced item objects even when the key stays the same\n\n## How keyed updates work\n\n`Each` uses the value from `key$` as the identity of the row.\n\nWhen keys stay the same, Qwik can move and reuse the existing rows instead of recreating them. This\nis why `Each` is a good fit for drag-and-drop lists, sortable tables, and other UIs where items\nmove around often.\n\nThere is an important tradeoff: if you replace an item object but keep the same key, `Each`\npreserves the existing row. That means the row template is not re-run just because a new object\nwith the same key was passed in.\n\nSo `Each` is usually the right choice for keyed collections. It has a different update strategy.\n\nIf you need the row output to update from replaced item objects, prefer `map()`. If you need\nrow-local updates with `Each`, model that row state with Qwik reactivity instead of relying on\nreplacing the whole item object.\n\n## Keys\n\nChoose keys that are stable across renders:\n\n- Good: database ids, slugs, UUIDs\n- Avoid: array indexes when the list can be reordered\n\nUsing unstable keys defeats the main benefit of `Each` and can produce confusing UI behavior.\n\n## Related\n\n- For general list rendering, see [Rendering](/docs/core/rendering.md)\n- For the generated API entry, see [API Reference](/api/qwik.md#each)\n"},{"id":"/docs/labs/","title":"🧪 Experimental | Overview","description":"","url":"https://next.qwik.dev/docs/labs/","content":"# Experimental Overview\n\nThe \"Experimental\" section is an incubator for ideas not yet ready for production. It's a place where we can publish our \"work in progress\" so the community can try it out and provide feedback, without any guarantees that the feature is stable or will make it into production.\n\nGiven that these are ideas in their initial stages, chances are they will significantly change over their lifetime, so they should not be relied upon in production.\n\nUSE AT YOUR OWN RISK.\n\n**Disclaimer**\n\nThis is a place to experiment, as such:\n- We make no guarantees about the stability of the API: _we can break it at any point._\n- It is not ready for production: _we want you to try it and give us feedback so that we can improve._\n- No guarantees that the feature will ever make it to production: _it can be abandoned at any point._\n\n**Expect lots of breaking changes as the features are being developed!!!**\n\n## Stages\n\nEach experimental feature can roughly be thought of as going through these stages:\n1. `proposal`: An RFC proposal no code yet\n2. `prototyping`: An experimental stage where we explore the API, algorithm and approaches. Missing features, probably not in a usable state.\n3. `implementation`: We know what needs to be built and are going through the built out process.\n4. `alpha`: We think the project is ready to receive feedback from the community. Try it out and let us know what works and what does not.\n5. `beta`: We think the project is ready to graduate to the main repo and be used in production.\n\n## Usage\n\nExperimental features are distributed under an experimental flag. This means that the feature is already part of the main package but is not enabled by default.\nTo enable the feature you need to set the corresponding flag in the `qwikVite` `experimental[]` array.\n"},{"id":"/docs/labs/insights/","title":"🧪 Insights | Experimental","description":"","url":"https://next.qwik.dev/docs/labs/insights/","content":"# Insights\n**Stage:** `prototyping`\n\nInsights allow your application to collect real user usage information to optimize the creation of bundles. By observing real user behavior, the Qwik build system can then do a better job prefetching bundles for your application. There are two benefits of this:\n1. By noticing which symbols are used together, the bundler can colocate the symbols in the same bundle minimizing the waterfall that could occur if there are too many small files needing to be downloaded.\n2. By observing in which order the symbols are used, the prefetcher can then fetch bundles in priority order ensuring that the bundles that are used more often are loaded first.\n\n## Architecture\n\nThe optimization consists of these parts:\n- A `<Insights>` component which collects time based bundle execution data.\n- A `qwikInsights` Vite Plugin to apply the usage data during the build process.\n- A registered application inside the builder.io database.\n\nCurrently Insights info is hosted in the Builder database. This information is about the execution of symbols/chunks in the application. The implementation of the service is open-source and you have the choice to use ours or host your own.\n\n## `<Insights>` component\n\nThe `<Insights>` component should be added to your `root.tsx` file.\n\nTo use it, you need to pass `experimental: ['insights']` as an option to the `qwikVite` plugin as such:\n\n```ts\n// vite.config.ts\n\nexport default defineConfig(({ command, mode }): UserConfig => {\n return {\n plugins: [\n // ... other plugins like qwikRouter() etc\n qwikVite({\n experimental: ['insights']\n // ... other options\n }),\n\n ],\n // ... rest of the config\n };\n}\n\n```\n\n```typescript\n// ...\nimport { Insights } from '@qwik.dev/core';\n\nexport default component$(() => {\n useQwikRouter();\n\n // ...\n return (\n <>\n <head>\n // ...\n <Insights\n publicApiKey={import.meta.env.PUBLIC_QWIK_INSIGHTS_KEY}\n />\n </head>\n <body lang=\"en\">\n // ...\n </body>\n </>\n );\n});\n```\n\nYou can get `PUBLIC_QWIK_INSIGHTS_KEY` by visiting [Qwik Insight](https://insights.qwik.dev/app/add/).\n\nThe `<Insights>` component collects this data:\n- Timing information of symbols.\n- The `pathname` part of the URL.\n- Random sessionID which identifies which symbol loads came from the same browser session.\n\nThe `` component does not collect any user-identifiable information.\n\nThe data collected being based on the frequency bundles are being grouped together at the same time, it is **not** advised to share the same API key between your preview and production environments. During preview, developers might use the application in 3G throttling and click around, which can put unrelated bundles together. After that the import graph would be wrong, leading to over-preloading, and Insights would then base its future data collection based on those corrupted bundles. If that happened to you, we recommend creating a new API key for your production environment. In normal usage, you will release a new version of your application and there will be a long enough window for Insights to collect the data. In case you face over-preloading in your app, you can always re-create a new API key. Drop us a message in the [Qwik Discord server](https://qwik.dev/chat) if this becomes a recurrent issue for you.\n\n## Vite integration\n\nOnce the application is running for a while and it collects sufficient information on symbol usage, the stats can be used to improve the bundles of the future version of the application. This is done by connecting the vite build with Insights like so:\n\nfile: `vite.config.js`\n```typescript\n//..\nimport { defineConfig, loadEnv } from 'vite';\nimport { qwikInsights } from '@qwik.dev/core/insights/vite';\n\nexport default defineConfig(async () => {\n return {\n plugins: [\n qwikInsights({\n publicApiKey: loadEnv('', '.', '').PUBLIC_QWIK_INSIGHTS_KEY,\n }),\n //...\n ],\n // ...\n };\n});\n```\n"},{"id":"/docs/labs/show/","title":"Show | Experimental","description":"","url":"https://next.qwik.dev/docs/labs/show/","content":"# `Show`\n\n**Stage:** `implementation`\n\n `Show` is experimental and currently a technical preview. Its API and behavior may still change\n as we gather feedback from real-world usage.\n\n`Show` is a built-in Qwik component for conditional rendering.\n\nIt is useful when you want the condition and branches to be QRL-based. `Show` tracks the value\nreturned from `when$`, renders `then$` when it is truthy, and renders `else$` when it is falsey.\nIf `else$` is omitted, falsey conditions render empty content.\n\nTo use it, you must add `experimental: ['show']` to your `qwikVite` plugin options:\n\n```ts\n// vite.config.ts\nimport { defineConfig } from 'vite';\nimport { qwikVite } from '@qwik.dev/core/optimizer';\n\nexport default defineConfig(() => {\n return {\n plugins: [\n qwikVite({\n experimental: ['show'],\n }),\n ],\n };\n});\n```\n\n```tsx /Show/ /when$/ /then$/ /else$/\nimport { Show, component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const count = useSignal(0);\n\n return (\n <>\n <button onClick$={() => count.value++}>Add item</button>\n <button onClick$={() => (count.value = 0)}>Clear</button>\n\n <Show\n when$={() => count.value}\n then$={(count) => (\n <p>\n {count} item{count === 1 ? '' : 's'} in your cart.\n </p>\n )}\n else$={(count) => <p>Your cart is empty ({count}).</p>}\n />\n </>\n );\n});\n```\n\n## Props\n\n`Show` accepts three props:\n\n- `when$`: returns the condition. Truthy values select `then$`, falsey values select `else$`.\n- `then$`: receives the value returned by `when$` and returns the JSX to render when it is truthy.\n- `else$`: optionally receives the value returned by `when$` and returns the JSX to render when it\n is falsey.\n\n`when$`, `then$`, and `else$` are QRL props. Use the `$` suffix so the optimizer can extract the\nclosures.\n\nThe `then$` and `else$` callback argument is typed from the return value of `when$`:\n\n```tsx /Show/ /when$/ /then$/ /else$/\nconst count = useSignal(0);\n\n<Show\n when$={() => count.value}\n then$={(count) => <p>{count} items selected.</p>}\n else$={(count) => <p>No items selected ({count}).</p>}\n/>;\n```\n\n## Without `else$`\n\nWhen `else$` is not provided, a falsey condition renders nothing:\n\n```tsx /Show/ /when$/ /then$/\nimport { Show, component$, useSignal } from '@qwik.dev/core';\n\nexport default component$(() => {\n const expanded = useSignal(false);\n\n return (\n <>\n <button onClick$={() => (expanded.value = !expanded.value)}>\n Toggle details\n </button>\n\n <Show\n when$={() => expanded.value}\n then$={() => <p>Details are visible.</p>}\n />\n </>\n );\n});\n```\n\n## Reactivity\n\n`Show` tracks the values read by `when$`. Put the reactive reads that should switch the branch\ninside `when$`:\n\n```tsx /Show/ /user.value/\n<Show\n when$={() => user.value?.name ?? ''}\n then$={(name) => <p>Hello {name}</p>}\n else$={() => <p>Please sign in.</p>}\n/>\n```\n\nOnly the selected branch is resolved and invoked. When `when$` is truthy, `then$` runs and `else$`\ndoes not. When `when$` is falsey, `else$` runs if it exists and `then$` does not.\n\n## `Show` vs JSX conditionals\n\nFor simple conditional markup, ordinary JSX is still a good fit:\n\n```tsx\n{signedIn.value ? <p>Welcome back.</p> : <p>Please sign in.</p>}\n```\n\nUse `Show` when you specifically want QRL-based conditional control flow and branch selection\nhandled by the built-in primitive.\n\n## Related\n\n- For general conditional rendering, see [Rendering](/docs/core/rendering.md)\n- For the generated API entry, see [API Reference](/api/qwik.md#show)\n"},{"id":"/docs/labs/typed-routes/","title":"🧪 Typed Routes","description":"","url":"https://next.qwik.dev/docs/labs/typed-routes/","content":"# Typed Routes\n**Stage:** `prototyping`\n\nProvides type safe way of building URLs within the application.\n\n## Installation\n\n1.\n\n```shell\npnpm install github:QwikDev/qwik-labs-build#main\n```\n\n2. update `vite.config.ts`\n ```typescript\n // ...\n import { qwikTypes } from '@qwik.dev/labs/vite';\n\n export default defineConfig(() => {\n return {\n plugins: [\n // ...\n qwikTypes() // <== Add `qwikTypes()` to the list of plugins\n ],\n // ...\n };\n });\n ```\n3. Run build so that it generates `~/routes.gen.d.ts` and `~/routes.config.tsx` files.\n3. To create a typesafe link:\n ```typescript\n import { AppLink } from '~/routes.config';\n\n export default component$(() => {\n // ...\n return (\n // ...\n <AppLink route=\"/your/[appParam]/link/\" param:appParam={\"some-value\"}>\n Link text\n </AppLink>\n );\n });\n ```\n\n# Declarative Routing\nThis is a package originally created by Jack Herrington aka *\"The Blue Collar Coder\"* for type safe routing inside NextJS applications and has been adapted for use inside Qwik Router\n\n## Installation\n1.\n\n```shell\npnpm dlx declarative-routing init\n```\n\n## Setup\nThe initialization process will create some important files for you.\n\n### .src/declarativeRoutes\n- `makeRoute.ts` - Used for defining page routes\n- `index.ts` - Where all of your route files will be imported from.\n- `hooks.ts` - A file with two custom hooks `useParams` & `useSearchParams` used to access type safe route urls, params, and searchParams\n\n### Each of your route directories\n- routeInfo.ts - Where you name the route, and provide a `zod` schema for the `params` and `search` (search params)\n\n## Usage\n\n### Declare Route Details\n```typescript title=\"/src/routes/pokemon/[pokemonId]/routeInfo.ts\"\nimport * as z from \"zod\";\n\nexport const Route = {\n name: \"PokemonDetail\",\n params: z.object({\n pokemonId: z.coerce.number(),\n }),\n};\n```\n\n### Inside Component\nThere are a few different ways you can use Declarative Routes inside your component.\n\n1. Use *RouteName*.Link\n```typescript title=\"myComponent.tsx\"\nimport { PokemonDetail } from \"~/declarativeRoutes\";\n\nexport default component$(() => {\n // ...\n return (\n // ...\n <PokemonDetail.Link pokemonId={1}>Bulbasaur</PokemonDetail.Link>\n );\n});\n```\n\n2. Use the standard Link and use the *RouteName* as a function to return the path\n```typescript title=\"myComponent.tsx\"\nimport { Link } from \"@qwik.dev/router\";\nimport { PokemonDetail } from \"~/declarativeRoutes\";\n\nexport default component$(() => {\n // ...\n return (\n // ...\n <Link href={PokemonDetail({ pokemonId: 1 })}>Bulbasaur</Link>\n );\n});\n```\n3. Use *RouteName*.ParamsLink\n```typescript title=\"myComponent.tsx\"\nimport { PokemonDetail } from \"~/declarativeRoutes\";\n\nexport default component$(() => {\n // ...\n return (\n // ...\n <PokemonDetail.ParamsLink params={{ pokemonId: 1 }}>Bulbasaur</PokemonDetail.ParamsLink>\n );\n});\n```\n4. Get the params from a *RouteName*\n\n```typescript title=\"myComponent.tsx\"\nimport { PokemonDetail } from \"~/declarativeRoutes\";\n\nexport default component$(() => {\n // Typescript will know the correct params and their types\n const { pokemonId } = useParams(PokemonDetail);\n // ...\n return (\n // ...\n );\n});\n```\n\n## Add or Change Routes\nIf you add a new route, or move an existing route, simply run\n\n```shell\npnpm dlx declarative-routing build\n```\n\nand this will rerun the process and update any changes needed\n\n## Links\n- [GitHub](https://github.com/ProNextJS/declarative-routing)\n- [Qwik Router Setup Instructions](https://github.com/ProNextJS/declarative-routing/blob/main/docs/qwikcity.md)\n- [Example Repos](https://github.com/ProNextJS/declarative-routing/tree/main/examples/qwikcity)\n"},{"id":"/api/","title":"API Reference","description":"Index of Qwik package API references.","url":"https://next.qwik.dev/api/","content":"# API Reference\n\n- [\\@qwik.dev/core/insights API Reference](/api/qwik-insights.md)\n- [\\@qwik.dev/core/optimizer API Reference](/api/qwik-optimizer.md)\n- [\\@qwik.dev/router/middleware/aws-lambda API Reference](/api/qwik-router-middleware-aws-lambda.md)\n- [\\@qwik.dev/router/middleware/azure-swa API Reference](/api/qwik-router-middleware-azure-swa.md)\n- [\\@qwik.dev/router/middleware/cloudflare-pages API Reference](/api/qwik-router-middleware-cloudflare-pages.md)\n- [\\@qwik.dev/router/middleware/firebase API Reference](/api/qwik-router-middleware-firebase.md)\n- [\\@qwik.dev/router/middleware/netlify-edge API Reference](/api/qwik-router-middleware-netlify-edge.md)\n- [\\@qwik.dev/router/middleware/node API Reference](/api/qwik-router-middleware-node.md)\n- [\\@qwik.dev/router/middleware/request-handler API Reference](/api/qwik-router-middleware-request-handler.md)\n- [\\@qwik.dev/router/middleware/vercel-edge API Reference](/api/qwik-router-middleware-vercel-edge.md)\n- [\\@qwik.dev/router/ssg API Reference](/api/qwik-router-ssg.md)\n- [\\@qwik.dev/router/vite/azure-swa API Reference](/api/qwik-router-vite-azure-swa.md)\n- [\\@qwik.dev/router/vite/bun-server API Reference](/api/qwik-router-vite-bun-server.md)\n- [\\@qwik.dev/router/vite/cloud-run API Reference](/api/qwik-router-vite-cloud-run.md)\n- [\\@qwik.dev/router/vite/cloudflare-pages API Reference](/api/qwik-router-vite-cloudflare-pages.md)\n- [\\@qwik.dev/router/vite/netlify-edge API Reference](/api/qwik-router-vite-netlify-edge.md)\n- [\\@qwik.dev/router/vite/node-server API Reference](/api/qwik-router-vite-node-server.md)\n- [\\@qwik.dev/router/vite/ssg API Reference](/api/qwik-router-vite-ssg.md)\n- [\\@qwik.dev/router/vite/vercel API Reference](/api/qwik-router-vite-vercel.md)\n- [\\@qwik.dev/router API Reference](/api/qwik-router.md)\n- [\\@qwik.dev/core/server API Reference](/api/qwik-server.md)\n- [\\@qwik.dev/core/testing API Reference](/api/qwik-testing.md)\n- [\\@qwik.dev/core/worker API Reference](/api/qwik-worker.md)\n- [\\@qwik.dev/core API Reference](/api/qwik.md)\n"}]}