DocsSvelteKit
- Reference$app/serverread
Available since 2.4.0 Read the contents of an imported asset from the filesystem import { read } fromCore conceptsRoutingFurther readingundefinedCore conceptsLoading dataFurther readingundefinedCore conceptsForm actionsFurther readingundefinedCore conceptsPage optionsFurther readingundefinedAdvancedAdvanced routingFurther readingundefinedAdvancedHooksFurther readingundefinedAdvancedErrorsFurther readingundefinedAdvancedServer-only modulesFurther readingundefinedBest practicesPerformanceFurther readingFor the most part, building a performant SvelteKit app is the same as building any performant web app. You should be able to apply information from geBest practicesAccessibilityFurther readingFor the most part, building an accessible SvelteKit app is the same as building an accessible web app. You should be able to apply information from thBuild and deployCloudflareCloudflare PagesFurther readingYou may wish to refer to Cloudflare's documentation for deploying a SvelteKit site on Cloudflare Pages.Reference$app/stateSvelteKit makes three read-only state objects available via the $app/state module — page, navigating aBuild and deployWriting adapters` } } }, supports: { read: ({ config, route }) => { // Return `true` if the route with the given `config` can usReference$app/serverimport { getRequestEvent, read } from '$app/server';Best practicesAccessibilityto accessibility, see the "further reading" section of this guide for additional resources.We recognize that accessibility can beCore conceptsForm actionsAnatomy of an actionquestEvent object, allowing you to read the data with request.formData(). After processing the request (for example, logging the uBuild and deployNode serversEnvironment variablesIn dev and preview, SvelteKit will read environment variables from your .env file (or .env.local, or .Reference$app/statenavigatingA read-only object representing an in-progress navigation, with from, to, type and (if type === 'popstReference$app/statepageA read-only reactive object with information about the current page, serving several use cases:undefinReference$app/stateupdatedA read-only reactive value that's initially false. If `version.pollInterval` is a non-zero value, SvelCore conceptsState managementComponent and page state is preservedsplit(' ').length; const estimatedReadingTime = wordCount / 250; </script> <header> <h1>{data.title}</h1> <p>Reading time: {MaBest practicesAccessibilityRoute announcementsreload. When this happens, screen readers and other assistive technology will read out the new page's title so that users understBest practicesAccessibilityFocus managementthe web with a keyboard or screen reader will start interacting with the page from the beginning.To simulate this behavior duringReference$app/storesnavigatingvelte 5, see docs for more info) A readable store. When navigating starts, its value is a Navigation object with from, to, type anReference$app/storesupdatedvelte 5, see docs for more info) A readable store whose initial value is false. If `version.pollInterval` is a non-zero value, SveAdvancedServer-only modulesServer-only utilities/server` module, which contains a `read` function for reading assets from the filesystem, can likewise only be imported by code thBest practicesAccessibilityThe "lang" attributesure that any assistive technology reading the document uses the correct pronunciation. For example, if your content is in German,Reference@sveltejs/kitCookiesdisabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults tReference@sveltejs/kitRequestEventslug: string } object. platform: Readonly<App.Platform> | undefined; Additional data made available through the adapter. requesReference@sveltejs/kitServerInitOptions; A map of environment variables. read?: (file: string) => ReadableStream; A function that turns an asset filename into a ReadablReference$app/storespagevelte 5, see docs for more info) A readable store whose value contains page data.On the server, this store can only be subscribedCore conceptsRouting+serverrst argument to Response can be a `ReadableStream`, making it possible to stream large amounts of data or create server-sent eventCore conceptsState managementUsing state and stores with contextkeep reactivity across boundaries. Read more about it [here](/docs/svelte/$state#Passing-state-into-functions) [!LEGACY] You alsoReference@sveltejs/kit/nodecreateReadableStream2.4.0 Converts a file on disk to a readable stream function createReadableStream(file: string): ReadableStream;Build and deployNode serversSocket activationN_PID` and `LISTEN_FDS` are always read without a prefix. To take advantage of socket activation follow these steps.undefined [SAdvancedLink optionsdata-sveltekit-keepfocusiously focused element) and screen reader and other assistive technology users often expect focus to be moved after a navigation.AppendixMigrating to SvelteKit v2Dynamic environment variables cannot be used during prerenderingronment variables can no longer be read during prerendering in SvelteKit 2 — you should use the static modules instead. If the useReference@sveltejs/kitAdapterk in production with this adapter. read?: (details: { config: any; route: { id: string } }) => boolean; undefined Test support fGetting startedWeb standardsFetch APIsHeadersThe `Headers` interface allows you to read incoming request.headers and set outgoing response.headers.Build and deployNode serversEnvironment variablesADDRESS_HEADER` and XFF_DEPTH`ed to specify an ADDRESS_HEADER to read the address from:ADDRESS_HEADER=True-Client-IP node build[!NOTE] Headers can easily be spoAdvancedPackagingAnatomy of a package.jsonfilesby default). Your package.json and README and LICENSE will always be included, so you don't need to specify them.{ "files": ["disBuild and deployNetlifyTroubleshootingAccessing the file systemyour deployment. Instead, use the `read` function from $app/server to access your files. read does not work inside edge deploymentBuild and deployVercelTroubleshootingAccessing the file systemyour deployment. Instead, use the `read` function from $app/server to access your files. read does not work inside routes deployedAdvancedPackagingAnatomy of a package.jsonlicenserranty is MIT.{ "license": "MIT" }Read more about it here. Note that you should also include a LICENSE file in your package.Best practicesPerformanceReducing code sizePackagesour Vite config to make the output readable, but remember to undo that before deploying your app), or via the network tab of yourExamplesStores
TutorialBasic SvelteKit
- Headers and cookiesReading and writing cookies
PI.In your load functions, you can read a cookie with cookies.get(name, options): export function load(+++{ cookies }+++) { +++c$app/statepageSvelteKit makes three readonly state objects available via the $app/state module — page, navigating anIntroductionWhat is SvelteKit?s of building something production-ready:undefined SvelteKit apps are server-rendered by default (like traditional 'multi-page appDocsSvelte
- Referencesvelte/storereadable
Creates a Readable store that allows reading by subscription. function readable<T>( value?: T | undefReferencesvelte/storereadonlye derived from the old one that is readable. function readonly<T>(store: Readable<T>): Readable<T>;Referencesvelte/storeReadableReadable interface for subscribing. interface Readable<T> {/*…*/} subscribe(this: void, run: SubscribeRuntimeStoressvelte/storereadablevalue, and the second argument to readable is the same as the second argument to writable.import { readable } from 'svelte/store'RuntimeStoressvelte/storereadonlymple helper function makes a store readonly. You can still subscribe to the changes from the original one using this new readableReferenceCompiler warningsd keyboard commands used by screen reader and keyboard-only users create accessibility complications. To avoid complications, acceRunes$stateallow Svelte to run code when you read or write properties, including via methods like array.push(...), triggering granular updatTemplate syntax{@attach ...}s mounted to the DOM or when state read inside the function updates.Optionally, they can return a function that is called before tStylingCustom properties> </g>Inside the component, we can read these custom properties (and provide fallback values) using `var(...)`:<style> .Referencesvelte/storeimport { derived, fromStore, get, readable, readonly, toStore, writable } from 'svelte/store';Runes$effected, $props) that are synchronously read inside its function body (including indirectly, via function calls) and registers them asSpecial elements<svelte:window>All except scrollX and scrollY are readonly.<svelte:window bind:scrollY={y} />[!NOTE] Note that the page will not be scrolled to tMiscCustom elementsthe DOM element (as well as being readable/writable as attributes, where possible). const el = document.querySelector('my-elemenRunes$derivedUnderstanding dependenciesAnything read synchronously inside the $derived expression (or $derived.by function body) is considereTemplate syntaxbind:DimensionsAll visible elements have the following readonly bindings, measured with a ResizeObserver:undefined <dReferencesvelte/reactivitySvelteDateion of the built-in `Date` object. Reading the date (whether with methods like date.getTime() or date.toString(), or via things liReferencesvelte/reactivitySvelteMapsion of the built-in `Map` object. Reading contents of the map (by iterating, or by reading map.size or calling map.get(...) or maReferencesvelte/reactivitySvelteSetsion of the built-in `Set` object. Reading contents of the set (by iterating, or by reading set.size or calling set.has(...) as inReferencesvelte/reactivitySvelteURLsion of the built-in `URL` object. Reading properties of the URL (such as url.href or url.pathname) in an effect or derived will cReferencesvelte/reactivitySvelteURLSearchParamsbuilt-in `URLSearchParams` object. Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in tReferencesvelteuntrack`$derived` or `$effect`, any state read inside fn will not be treated as a dependency.$effect(() => { // this will run when `dataReferencesvelte/compilerCompileOptionslse, they will only be created for readonly exported values (i.e. those declared with const, class and function). If compiling witReferencesvelte/motionSpringinterface Spring<T> extends Readable<T> {/*…*/} set(new_value: T, opts?: SpringUpdateOpts): PromReferencesvelte/motionTweenedinterface Tweened<T> extends Readable<T> {/*…*/} set(value: T, opts?: TweenedOptions<T>): PromisReferencesvelte/storederivedstore by synchronizing one or more readable stores and applying an aggregation function over its input values. function derived<STemplate syntax{@attach ...}Controlling when attachments re-runhanges to foo or bar (or any state read inside foo): function foo(bar) { return (node) => { veryExpensiveSetupWork(node); upTemplate syntaxbind:bind:thisunted — in other words, you should read it inside an effect or an event handler, but not during component initialisation:<script>Referencesvelte/storeWritableing. interface Writable<T> extends Readable<T> {/*…*/} set(this: void, value: T): void; undefined Set value and inform subRunes$derivedUpdate propagation-evaluated until they are actually read (the 'pull').If the new value of a derived is referentially identical to its previous valuTemplate syntaxbind:bind:_property_ for componentse `$bindable` rune:<script> let { readonlyProperty, bindableProperty = $bindable() } = $props(); </script>Declaring a propeMiscFrequently asked questionsWhere can I get support?ou’re stuck with a specific error. Read through the existing questions tagged with Svelte or ask your own!There are online forumsReferencesvelte/storewritabletore that allows both updating and reading by subscription. function writable<T>( value?: T | undefined, start?: StartStopNotifiTemplate syntaxbind:Function bindingsv.toLowerCase()} />In the case of readonly bindings like dimension bindings, the get value should be null:<div bind:clientWidMiscTypeScriptEnhancing built-in DOM typesenced in your tsconfig.json. If it reads something like "include": ["src/**/*"] and your d.ts file is inside sRuntimeStoressvelte/storegetGenerally, you should read the value of a store by subscribing to it and using the value as it changesMiscSvelte 5 migration guideReactivity syntax changes$: → $derived/$effects still the number itself, and you read it directly, without a wrapper like .value or getDouble().A $: statement could also be useReferenceRuntime errorsClient errorsprops_rest_readonly$props()` such as `%property%` are readonlyMiscSvelte 5 migration guideReactivity syntax changeslet → $states still the number itself, and you read and write directly to it, without a wrapper like .value or getCount().[!DETAILS] Why we diMiscSvelte 5 migration guideOther breaking changesScoped CSS uses :where(...)of the <style> contents). You can read more detail here.In the event that you need to support ancient browsers that don't iMiscTypeScriptPreprocessor setupOther build toolsplugin config (see the respective READMEs for more info). If you're starting a new project, you can also use the rollup or webpacMiscSvelte 5 migration guideEvent changesMultiple event handlerstwo(e); }} > ... </button>When spreading props, local event handlers must go after the spread, or they risk being overwTutorialAdvanced Svelte
- Advanced bindingsThis
ecial bind:this directive to get a readonly binding to an element in your component.The $effect in this exercise attempts to creatNext stepsCongratulations!nished the Svelte tutorial and are ready to start building.The next two parts of the tutorial will focus on SvelteKit, a full-fledAdvanced reactivityRaw statey creating a proxy that intercepts reads and writes.Occasionally, that's not what you want. If you're not changing individual propMotionTweened valuess a writable target property and a readonly current property — update the <progress> element...<progress value={progress.+++currenMotionSpringse a writable target property and a readonly current property. Update the event handlers...<svg onmousemove={(e) => { coords.+++Advanced bindingsDimensionspx</span> </div>These bindings are readonly — changing the values of w and h won't have any effect on the element.[!NOTutorialAdvanced SvelteKit
- Environment variables$env/dynamic/private
If you need to read the values of environment variables when the app runs, as opposed to when the appAdvanced loadingUniversal load functionsdata directly from a database, or reading cookies.Sometimes it doesn't make sense to load data from the server when doing a clien