DocsSvelteKit
- Core conceptsRemote functionsquery
The query function allows you to read dynamic data from the server (for static data, consider using `pReference$app/serverquerynamespace query { /** * Creates a batch query function that collects multiple calls and executes thCore conceptsRemote functionsqueryQuery argumentsQuery functions can accept an argument, such as the slug of an individual post:<!--- file: src/routes/Core conceptsRemote functionsqueryDeduplicationWhen you call a query function, SvelteKit serializes the argument you call it with and uses it as a caCore conceptsRemote functionsqueryRefreshing queriesAny query can be re-fetched via its refresh method, which retrieves the latest value from the server:<Core conceptsRemote functionsquery.batchquery.batch works like query except that it batches requests that happen within the same macrotask. ThReference$app/serverrm, getRequestEvent, prerender, query, read, requested } from '$app/server';Core conceptsRemote functionsprerenderThe prerender function is similar to query, except that it will be invoked at build time to prerenderCore conceptsRemote functionsUsing `getRequestEvent`Inside query, form and command you can use `getRequestEvent` to get the current `RequestEvent` object.Core conceptsRemote functionsRedirectsInside query, form and prerender functions it is possible to use the `redirect(...)` function. It is nCore conceptsRemote functionsformt } from '@sveltejs/kit'; import { query, form } from '$app/server'; import * as db from '$lib/server/database'; import * as authCore conceptsRemote functionsHandling validation errorsthe argument passed to a command, query or prerender function would fail validation:the function signature changed between deployAppendixFrequently asked questionsHow do I set up a database?Put the code to query your database in a server route - don't query the database in .svelte files. YouReference@sveltejs/kitRemoteResource<T> & { /** The error in case the query fails. Most often this is a [`HttpError`](https://svelte.dev/docs/kit/@sveltejs-kitReference$app/navigationinvalidateAllCauses all load and query functions belonging to the currently active page to re-run. Returns a PromisCore conceptsRemote functionsOverviews file, and come in four flavours: query, form, command and prerender. On the client, the exported functions are transformed to feReference@sveltejs/kitRemoteQuerytype RemoteQuery<T> = RemoteResource<T> & { /** * Returns a plain promise with the result. * UnliReference@sveltejs/kitRemoteQueryFunctionThe return value of a remote query function. See Remote functions for full documentation. type RemoteQCore conceptsForm actionsNamed actions};To invoke a named action, add a query parameter with the name prefixed by a / character:<!--- file: src/routes/login/+page.svelCore conceptsRemote functionscommanddisabled or fails to load.As with query and form, if the function accepts an argument, it should be validated by passing a StandaAdvancedLink optionsdata-sveltekit-keepfocusepfocus> <input type="text" name="query"> </form>...will cause the currently focused element to retain focus after navigatiReference$app/navigationinvalidatesed to fetch or depends (including query parameters). To create a custom identifier, use a string beginning with [a-z]+: (e.g. cusBest practicesAuthSessions vs tokensly revoked, but require a database query to be made on each request.In contrast, JWT generally are not checked against a datastoreBest practicesAccessibilityFocus managementull} */ const to_focus = document.querySelector('.focus-me'); to_focus?.focus(); });You can also programmatically navigate to aReference@sveltejs/kitRequestedResultfor await (const arg of requested(query, ...) { * void query(arg).refresh(); * } * ``` */ refreshAll: () => PromiReference$app/serverrequestedunction requested<Input, Output>( query: RemoteQueryFunction<Input, Output>, limit?: number ): RequestedResult<Input>;Core conceptsRemote functionsSingle-flight mutationsClient-requested refreshesple. The server always knows which query functions to update, but it may not know which specific query instances to update. For exBuild and deployVercelIncremental Static RegenerationallowQueryA list of valid query parameters that contribute to the cache key. Other parameters (such as utm trackCore conceptsLoading dataUsing URL dataurlhParams (which contains the parsed query string as a `URLSearchParams` object). url.hash cannot be accessed during load, since itCore conceptsRemote functionsSingle-flight mutationsServer-driven refreshesarguments:export const getPosts = query(async () => { /* ... */ }); export const getPost = query(v.string(), async (slug) => { /Getting startedWeb standardsURL APIsURLSearchParamsou encounter a URL, you can access query parameters via url.searchParams, which is an instance of `URLSearchParams`:const foo = urAdvancedHooksServer hookshandleValidationErrorrt * as v from 'valibot'; import { query } from '$app/server'; export const getTodo = query(v.string(), (id) => { // implementatBest practicesImages@sveltejs/enhanced-imgPer-image transformser-image transforms by appending a query string:<enhanced:img src="./path/to/your/image.jpg?blur=15" alt="An alt text" />See the iBest practicesImages@sveltejs/enhanced-imgDynamically choosing an imagee to specify enhanced via a custom query:<script> const imageModules = import.meta.glob( '/path/to/assets/*.{avif,AVIF,gif,GIF,Best practicesImages@sveltejs/enhanced-imgsrcset` and sizes`widths, you can do that with the w query parameter:<enhanced:img src="./image.png?w=1280;640;400" sizes="(min-width:1920px) 12Best practicesPerformanceNavigationPreventing waterfallshigh latency). For example, if you query a database to get the current user and then use that data to make a second query for a liAppendixMigrating from SapperPages and layoutsStoresparams properties, but no path or query.You access them differently in SvelteKit. stores is now getStores, but in most cases it iDocsSvelte
- MiscCustom elements
re possible). const el = document.querySelector('my-element'); // get the current value of the 'name' prop console.log(el.name);Referencesvelte/reactivityMediaQueryAvailable since 5.7.0 Creates a media query and provides a current property that reflects whether or nRuntimeImperative component APImountp = mount(App, { target: document.querySelector('#app'), props: { some: 'property' } });You can mount multiple components per paReferencesvelte/motionprefersReducedMotionAvailable since 5.7.0 A media query that matches if the user prefers reduced motion.<script> import {RuntimeImperative component APIhydrate= hydrate(App, { target: document.querySelector('#app'), props: { some: 'property' } });As with mount, effects will not run duriReferencesvelte/reactivitycreateSubscriberntegrating with web APIs like MediaQuery, IntersectionObserver, or WebSocket.If subscribe is called inside an effect (including inLegacy APIsImperative component APICreating a componentapp = new App({ target: document.querySelector('#server-rendered-html'), hydrate: true });[!NOTE] In Svelte 5+, use [`mount`](sMiscTestingUnit and component tests with VitestComponent testingwrite expectations document.body.querySelector('button').click(); flushSync(); expect(document.body.innerHTML).toBe('<button>