Getting started
Core concepts
Build and deploy
Advanced
Best practices
Appendix
Reference
- @sveltejs/kit
- @sveltejs/kit/hooks
- @sveltejs/kit/node/polyfills
- @sveltejs/kit/node
- @sveltejs/kit/vite
- $app/environment
- $app/forms
- $app/navigation
- $app/paths
- $app/server
- $app/state
- $app/stores
- $app/types
- $env/dynamic/private
- $env/dynamic/public
- $env/static/private
- $env/static/public
- $lib
- $service-worker
- Configuration
- Command Line Interface
- Types
@sveltejs/kit
- @sveltejs/kit
- Server
- VERSION
- error
- fail
- isActionFailure
- isHttpError
- isRedirect
- json
- normalizeUrl
- redirect
- text
- Action
- ActionFailure
- ActionResult
- Actions
- Adapter
- AfterNavigate
- AwaitedActions
- BeforeNavigate
- Builder
- ClientInit
- Config
- Cookies
- Emulator
- Handle
- HandleClientError
- HandleFetch
- HandleServerError
- HandleValidationError
- HttpError
- Invalid
- KitConfig
- LessThan
- Load
- LoadEvent
- LoadProperties
- Navigation
- NavigationBase
- NavigationEnter
- NavigationEvent
- NavigationExternal
- NavigationFormSubmit
- NavigationLink
- NavigationPopState
- NavigationTarget
- NavigationType
- NumericRange
- OnNavigate
- Page
- ParamMatcher
- PrerenderOption
- Redirect
- RemoteCommand
- RemoteForm
- RemoteFormField
- RemoteFormFieldType
- RemoteFormFieldValue
- RemoteFormFields
- RemoteFormInput
- RemoteFormIssue
- RemotePrerenderFunction
- RemoteQuery
- RemoteQueryFunction
- RemoteQueryOverride
- RemoteResource
- RequestEvent
- RequestHandler
- Reroute
- ResolveOptions
- RouteDefinition
- SSRManifest
- ServerInit
- ServerInitOptions
- ServerLoad
- ServerLoadEvent
- Snapshot
- SubmitFunction
- Transport
- Transporter
- Private types
- AdapterEntry
- Csp
- CspDirectives
- HttpMethod
- Logger
- MaybePromise
- PrerenderEntryGeneratorMismatchHandler
- PrerenderEntryGeneratorMismatchHandlerValue
- PrerenderHttpErrorHandler
- PrerenderHttpErrorHandlerValue
- PrerenderMap
- PrerenderMissingIdHandler
- PrerenderMissingIdHandlerValue
- PrerenderOption
- PrerenderUnseenRoutesHandler
- PrerenderUnseenRoutesHandlerValue
- Prerendered
- RequestOptions
- RouteSegment
- TrailingSlash
import{classServerServer,constVERSION:stringVERSION,functionerror(status:number,body:App.Error):never(+1overload)Throws an error with a HTTP status code and an optional message.When called during request handling, this will cause SvelteKit toreturn an error response without invokinghandleError.Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.
@paramstatus TheHTTP status code. Must be in the range 400-599.@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.@throwsError If the provided status is invalid (not between 400 and 599).error,functionfail(status:number):ActionFailure<undefined> (+1overload)Create anActionFailure object. Call when form submission fails.
@paramstatus TheHTTP status code. Must be in the range 400-599.fail,functionisActionFailure(e:unknown):eisActionFailureChecks whether this is an action failure thrown by {@link fail}.
@parame The object to check.isActionFailure,functionisHttpError<Textendsnumber>(e:unknown,status?:T):eis(HttpError_1&{status:Textendsundefined?never:T;})
Checks whether this is an error thrown by {@link error}.
@paramstatus The status to filter for.isHttpError,functionisRedirect(e:unknown):eisRedirect_1Checks whether this is a redirect thrown by {@link redirect}.
@parame The object to check.isRedirect,functionjson(data:any,init?:ResponseInit):ResponseCreate a JSONResponse object from the supplied data.
@paramdata The value that will be serialized as JSON.@paraminit Options such asstatus andheaders that will be added to the response.Content-Type: application/json andContent-Length headers will be added automatically.json,functionnormalizeUrl(url:URL|string):{url:URL;wasNormalized:boolean;denormalize:(url?:string|URL)=>URL;}
Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.Returns the normalized URL as well as a method for adding the potential suffix backbased on a new pathname (possibly including search) or URL.
import{ normalizeUrl }from'@sveltejs/kit';const{url,denormalize}=normalizeUrl('/blog/post/__data.json');console.log(url.pathname);// /blog/postconsole.log(denormalize('/blog/post/a'));// /blog/post/a/__data.json
@since2.18.0normalizeUrl,functionredirect(status:300|301|302|303|304|305|306|307|308|({}&number),location:string|URL):neverRedirect a request. When called during request handling, SvelteKit will return a redirect response.Make sure you’re not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)307 Temporary Redirect: redirect will keep the request method308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
@paramstatus TheHTTP status code. Must be in the range 300-308.@paramlocation The location to redirect to.@throwsRedirect This error instructs SvelteKit to redirect to the specified location.@throwsError If the provided status is invalid.redirect,functiontext(body:string,init?:ResponseInit):ResponseCreate aResponse object from the supplied body.
@parambody The value that will be used as-is.@paraminit Options such asstatus andheaders that will be added to the response. AContent-Length header will be added automatically.text}from'@sveltejs/kit';Server
classServer{…}constructor(manifest: SSRManifest);init(options: ServerInitOptions):Promise<void>;respond(request: Request,options: RequestOptions):Promise<Response>;VERSION
constVERSION:string;error
Throws an error with a HTTP status code and an optional message.When called during request handling, this will cause SvelteKit toreturn an error response without invokinghandleError.Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.
functionerror(status:number,body:App.Error):never;functionerror(status:number,body?:{message:string;}extendsApp.Error?App.Error|string|undefined:never):never;fail
Create anActionFailure object. Call when form submission fails.
functionfail(status:number):ActionFailure<undefined>;functionfail<T=undefined>(status:number,data:T):ActionFailure<T>;isActionFailure
Checks whether this is an action failure thrown byfail.
functionisActionFailure(e:unknown):eisActionFailure;isHttpError
Checks whether this is an error thrown byerror.
functionisHttpError<Textendsnumber>(e:unknown,status?:T):eisHttpError_1&{status:Textendsundefined?never:T;};isRedirect
Checks whether this is a redirect thrown byredirect.
functionisRedirect(e:unknown):eisRedirect_1;json
Create a JSONResponse object from the supplied data.
functionjson(data:any,init?:ResponseInit):Response;normalizeUrl
Available since 2.18.0
Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.Returns the normalized URL as well as a method for adding the potential suffix backbased on a new pathname (possibly including search) or URL.
import{functionnormalizeUrl(url:URL|string):{url:URL;wasNormalized:boolean;denormalize:(url?:string|URL)=>URL;}
Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.Returns the normalized URL as well as a method for adding the potential suffix backbased on a new pathname (possibly including search) or URL.
import{ normalizeUrl }from'@sveltejs/kit';const{url,denormalize}=normalizeUrl('/blog/post/__data.json');console.log(url.pathname);// /blog/postconsole.log(denormalize('/blog/post/a'));// /blog/post/a/__data.json
@since2.18.0normalizeUrl}from'@sveltejs/kit';const{consturl:URLurl,constdenormalize:(url?:string|URL)=>URLdenormalize}=functionnormalizeUrl(url:URL|string):{url:URL;wasNormalized:boolean;denormalize:(url?:string|URL)=>URL;}
Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.Returns the normalized URL as well as a method for adding the potential suffix backbased on a new pathname (possibly including search) or URL.
import{ normalizeUrl }from'@sveltejs/kit';const{url,denormalize}=normalizeUrl('/blog/post/__data.json');console.log(url.pathname);// /blog/postconsole.log(denormalize('/blog/post/a'));// /blog/post/a/__data.json
@since2.18.0normalizeUrl('/blog/post/__data.json');varconsole:ConsoleTheconsole module provides a simple debugging console that is similar to theJavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console class with methods such asconsole.log(),console.error() andconsole.warn() that can be used to write to any Node.js stream. - A global
console instance configured to write toprocess.stdout andprocess.stderr. The globalconsole can be used without importing thenode:console module.
Warning: The global console object’s methods are neither consistentlysynchronous like the browser APIs they resemble, nor are they consistentlyasynchronous like all other Node.js streams. See thenote on process I/O formore information.
Example using the globalconsole:
console.log('hello world');// Prints: hello world, to stdoutconsole.log('hello %s','world');// Prints: hello world, to stdoutconsole.error(newError('Whoops, something bad happened'));// Prints error message and stack trace to stderr:// Error: Whoops, something bad happened// at [eval]:5:15// at Script.runInThisContext (node:vm:132:18)// at Object.runInThisContext (node:vm:309:38)// at node:internal/process/execution:77:19// at [eval]-wrapper:6:22// at evalScript (node:internal/process/execution:76:60)// at node:internal/main/eval_string:23:3constname='Will Robinson';console.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr
Example using theConsole class:
constout=getStreamSomehow();consterr=getStreamSomehow();constmyConsole=newconsole.Console(out,err);myConsole.log('hello world');// Prints: hello world, to outmyConsole.log('hello %s','world');// Prints: hello world, to outmyConsole.error(newError('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to errconstname='Will Robinson';myConsole.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err
@seesourceconsole.Console.log(message?:any,...optionalParams: any[]):void(+1overload)Prints tostdout with newline. Multiple arguments can be passed, with thefirst used as the primary message and all additional used as substitutionvalues similar toprintf(3)(the arguments are all passed toutil.format()).
constcount=5;console.log('count: %d',count);// Prints: count: 5, to stdoutconsole.log('count:',count);// Prints: count: 5, to stdout
Seeutil.format() for more information.
@sincev0.1.100log(consturl:URLurl.URL.pathname: stringpathname);// /blog/postvarconsole:ConsoleTheconsole module provides a simple debugging console that is similar to theJavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console class with methods such asconsole.log(),console.error() andconsole.warn() that can be used to write to any Node.js stream. - A global
console instance configured to write toprocess.stdout andprocess.stderr. The globalconsole can be used without importing thenode:console module.
Warning: The global console object’s methods are neither consistentlysynchronous like the browser APIs they resemble, nor are they consistentlyasynchronous like all other Node.js streams. See thenote on process I/O formore information.
Example using the globalconsole:
console.log('hello world');// Prints: hello world, to stdoutconsole.log('hello %s','world');// Prints: hello world, to stdoutconsole.error(newError('Whoops, something bad happened'));// Prints error message and stack trace to stderr:// Error: Whoops, something bad happened// at [eval]:5:15// at Script.runInThisContext (node:vm:132:18)// at Object.runInThisContext (node:vm:309:38)// at node:internal/process/execution:77:19// at [eval]-wrapper:6:22// at evalScript (node:internal/process/execution:76:60)// at node:internal/main/eval_string:23:3constname='Will Robinson';console.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr
Example using theConsole class:
constout=getStreamSomehow();consterr=getStreamSomehow();constmyConsole=newconsole.Console(out,err);myConsole.log('hello world');// Prints: hello world, to outmyConsole.log('hello %s','world');// Prints: hello world, to outmyConsole.error(newError('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to errconstname='Will Robinson';myConsole.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err
@seesourceconsole.Console.log(message?:any,...optionalParams: any[]):void(+1overload)Prints tostdout with newline. Multiple arguments can be passed, with thefirst used as the primary message and all additional used as substitutionvalues similar toprintf(3)(the arguments are all passed toutil.format()).
constcount=5;console.log('count: %d',count);// Prints: count: 5, to stdoutconsole.log('count:',count);// Prints: count: 5, to stdout
Seeutil.format() for more information.
@sincev0.1.100log(constdenormalize:(url?:string|URL)=>URLdenormalize('/blog/post/a'));// /blog/post/a/__data.jsonfunctionnormalizeUrl(url:URL|string):{url:URL;wasNormalized:boolean;denormalize:(url?:string|URL)=>URL;};redirect
Redirect a request. When called during request handling, SvelteKit will return a redirect response.Make sure you’re not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)307 Temporary Redirect: redirect will keep the request method308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
functionredirect(status:|300|301|302|303|304|305|306|307|308|({}&number),location:string|URL):never;text
Create aResponse object from the supplied body.
functiontext(body:string,init?:ResponseInit):Response;Action
Shape of a form action method that is part ofexport const actions = {...} in+page.server.js.Seeform actions for more information.
typeAction<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,OutputDataextendsRecord<string,any>|void=Record<string,any>|void,RouteIdextendsAppRouteId|null=AppRouteId|null>=(event:RequestEvent<Params,RouteId>)=>MaybePromise<OutputData>;ActionFailure
interfaceActionFailure<T=undefined> {…}status:number;data:T;[uniqueSymbol]:true;ActionResult
When calling a form action via fetch, the response will be one of these shapes.
<formmethod="post"use:enhance={()=>{return({ result })=>{// result is of type ActionResult};}}typeActionResult<Successextends|Record<string,unknown>|undefined=Record<string,any>,Failureextends|Record<string,unknown>|undefined=Record<string,any>>=|{ type:'success'; status:number; data?:Success}|{ type:'failure'; status:number; data?:Failure}|{ type:'redirect'; status:number; location:string}|{ type:'error'; status?:number; error:any};Actions
Shape of theexport const actions = {...} object in+page.server.js.Seeform actions for more information.
typeActions<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,OutputDataextendsRecord<string,any>|void=Record<string,any>|void,RouteIdextendsAppRouteId|null=AppRouteId|null>=Record<string,Action<Params,OutputData,RouteId>>;Adapter
Adapters are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.
interfaceAdapter{…}name:string;The name of the adapter, using for logging. Will typically correspond to the package name.
adapt:(builder:Builder)=>MaybePromise<void>;builderAn object provided by SvelteKit that contains methods for adapting the app
This function is called after SvelteKit has built your app.
supports?:{…}Checks called during dev and build to determine whether specific features will work in production with this adapter.
read?:(details:{ config:any; route:{ id:string} })=>boolean;details.configThe merged route config
Test support forread from$app/server.
instrumentation?:()=>boolean;- available since v2.31.0
Test support forinstrumentation.server.js. To pass, the adapter must support runninginstrumentation.server.js prior to the application code.
emulate?:()=>MaybePromise<Emulator>;Creates anEmulator, which allows the adapter to influence the environmentduring dev, build and prerendering.
AfterNavigate
The argument passed toafterNavigate callbacks.
typeAfterNavigate=(Navigation|NavigationEnter)&{/*** The type of navigation:* - `enter`: The app has hydrated/started* - `form`: The user submitted a `<form method="GET">`* - `link`: Navigation was triggered by a link click* - `goto`: Navigation was triggered by a `goto(...)` call or a redirect* - `popstate`: Navigation was triggered by back/forward navigation*/type:Exclude<NavigationType,'leave'>;/*** Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.*/willUnload:false;};AwaitedActions
typeAwaitedActions<TextendsRecord<string,(...args:any)=>any>>=OptionalUnion<{[KeyinkeyofT]:UnpackValidationError<Awaited<ReturnType<T[Key]>>>;}[keyofT]>;BeforeNavigate
The argument passed tobeforeNavigate callbacks.
typeBeforeNavigate=Navigation&{/*** Call this to prevent the navigation from starting.*/cancel:()=>void;};Builder
This object is passed to theadapt function of adapters.It contains various methods and properties that are useful for adapting the app.
interfaceBuilder{…}log:Logger;Print messages to the console.log.info andlog.minor are silent unless Vite’slogLevel isinfo.
rimraf:(dir:string)=>void;Removedir and all its contents.
mkdirp:(dir:string)=>void;Createdir and any required parent directories.
config:ValidatedConfig;The fully resolved Svelte config.
prerendered:Prerendered;Information about prerendered pages and assets, if any.
routes:RouteDefinition[];An array of all routes (including prerendered)
createEntries:(fn:(route:RouteDefinition)=>AdapterEntry)=>Promise<void>;fnA function that groups a set of routes into an entry point- deprecated Use
builder.routesinstead
Create separate functions that map to one or more routes of your app.
findServerAssets:(routes:RouteDefinition[])=>string[];Find all the assets imported by server files belonging toroutes
generateFallback:(dest:string)=>Promise<void>;Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
generateEnvModule:()=>void;Generate a module exposing build-time environment variables as$env/dynamic/public.
generateManifest:(opts:{ relativePath:string; routes?:RouteDefinition[] })=>string;optsa relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated
Generate a server-side manifest to initialise the SvelteKitserver with.
getBuildDirectory:(name:string)=>string;namepath to the file, relative to the build directory
Resolve a path to thename directory insideoutDir, e.g./path/to/.svelte-kit/my-adapter.
getClientDirectory:()=>string;Get the fully resolved path to the directory containing client-side assets, including the contents of yourstatic directory.
getServerDirectory:()=>string;Get the fully resolved path to the directory containing server-side code.
getAppPath:()=>string;Get the application path including any configuredbase path, e.g.my-base-path/_app.
writeClient:(dest:string)=>string[];destthe destination folder- returns an array of files written to
dest
Write client assets todest.
writePrerendered:(dest:string)=>string[];destthe destination folder- returns an array of files written to
dest
Write prerendered files todest.
writeServer:(dest:string)=>string[];destthe destination folder- returns an array of files written to
dest
Write server-side code todest.
copy:(from: string,to: string,opts?:{filter?(basename:string):boolean;replace?:Record<string,string>;})=>string[];fromthe source file or directorytothe destination file or directoryopts.filtera function to determine whether a file or directory should be copiedopts.replacea map of strings to replace- returns an array of files that were copied
Copy a file or directory.
hasServerInstrumentationFile:()=>boolean;- returns true if the server instrumentation file exists, false otherwise
- available since v2.31.0
Check if the server instrumentation file exists.
instrument:(args:{entrypoint:string;instrumentation:string;start?:string;module?:|{exports:string[];}|{generateText:(args:{ instrumentation:string; start:string})=>string;};})=>void;optionsan object containing the following properties:options.entrypointthe path to the entrypoint to trace.options.instrumentationthe path to the instrumentation file.options.startthe name of the start file. This is whatentrypointwill be renamed to.options.moduleconfiguration for the resulting entrypoint module.options.module.generateTexta function that receives the relative paths to the instrumentation and start files, and generates the text of the module to be traced. If not provided, the default implementation will be used, which uses top-level await.- available since v2.31.0
Instrumententrypoint withinstrumentation.
Renamesentrypoint tostart and creates a new module atentrypoint which importsinstrumentation and then dynamically importsstart. This allowsthe module hooks necessary for instrumentation libraries to be loaded prior to any application code.
Caveats:
- “Live exports” will not work. If your adapter uses live exports, your users will need to manually import the server instrumentation on startup.
- If
tlaisfalse, OTEL auto-instrumentation may not work properly. Use it if your environment supports it. - Use
hasServerInstrumentationFileto check if the user has a server instrumentation file; if they don’t, you shouldn’t do this.
compress:(directory:string)=>Promise<void>;directoryThe directory containing the files to be compressed
Compress files indirectory with gzip and brotli, where appropriate. Generates.gz and.br files alongside the originals.
ClientInit
Available since 2.10.0
Theinit will be invoked once the app starts in the browser
typeClientInit=()=>MaybePromise<void>;Config
See theconfiguration reference for details.
Cookies
interfaceCookies{…}get:(name:string,opts?:import('cookie').CookieParseOptions)=>string|undefined;namethe name of the cookieoptsthe options, passed directly tocookie.parse. See documentationhere
Gets a cookie that was previously set withcookies.set, or from the request headers.
getAll:(opts?:import('cookie').CookieParseOptions)=>Array<{ name:string; value:string }>;optsthe options, passed directly tocookie.parse. See documentationhere
Gets all cookies that were previously set withcookies.set, or from the request headers.
set:(name: string,value: string,opts:import('cookie').CookieSerializeOptions&{ path:string })=>void;namethe name of the cookievaluethe cookie valueoptsthe options, passed directly tocookie.serialize. See documentationhere
Sets a cookie. This will add aset-cookie header to the response, but also make the cookie available viacookies.get orcookies.getAll during the current request.
ThehttpOnly andsecure options aretrue by default (except onhttp://localhost, wheresecure isfalse), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. ThesameSite option defaults tolax.
You must specify apath for the cookie. In most cases you should explicitly setpath: '/' to make the cookie available throughout your app. You can use relative paths, or setpath: '' to make the cookie only available on the current path and its children
delete:(name:string,opts:import('cookie').CookieSerializeOptions&{ path:string})=>void;namethe name of the cookieoptsthe options, passed directly tocookie.serialize. Thepathmust match the path of the cookie you want to delete. See documentationhere
Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
You must specify apath for the cookie. In most cases you should explicitly setpath: '/' to make the cookie available throughout your app. You can use relative paths, or setpath: '' to make the cookie only available on the current path and its children
serialize:(name: string,value: string,opts:import('cookie').CookieSerializeOptions&{ path:string })=>string;namethe name of the cookievaluethe cookie valueoptsthe options, passed directly tocookie.serialize. See documentationhere
Serialize a cookie name-value pair into aSet-Cookie header string, but don’t apply it to the response.
ThehttpOnly andsecure options aretrue by default (except onhttp://localhost, wheresecure isfalse), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. ThesameSite option defaults tolax.
You must specify apath for the cookie. In most cases you should explicitly setpath: '/' to make the cookie available throughout your app. You can use relative paths, or setpath: '' to make the cookie only available on the current path and its children
Emulator
A collection of functions that influence the environment during dev, build and prerendering
interfaceEmulator{…}platform?(details:{ config:any; prerender:PrerenderOption}):MaybePromise<App.Platform>;A function that is called with the current routeconfig andprerender optionand returns anApp.Platform object
Handle
Thehandle hook runs every time the SvelteKit server receives arequest anddetermines theresponse.It receives anevent object representing the request and a function calledresolve, which renders the route and generates aResponse.This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
typeHandle=(input:{event:RequestEvent;resolve:(event:RequestEvent,opts?:ResolveOptions)=>MaybePromise<Response>;})=>MaybePromise<Response>;HandleClientError
The client-sidehandleError hook runs when an unexpected error is thrown while navigating.
If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event.Make sure that this functionnever throws an error.
typeHandleClientError=(input:{error:unknown;event:NavigationEvent;status:number;message:string;})=>MaybePromise<void|App.Error>;HandleFetch
ThehandleFetch hook allows you to modify (or replace) the result of anevent.fetch call that runs on the server (or during prerendering) inside an endpoint,load,action,handle,handleError orreroute.
typeHandleFetch=(input:{event:RequestEvent;request:Request;fetch:typeoffetch;})=>MaybePromise<Response>;HandleServerError
The server-sidehandleError hook runs when an unexpected error is thrown while responding to a request.
If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event.Make sure that this functionnever throws an error.
typeHandleServerError=(input:{error:unknown;event:RequestEvent;status:number;message:string;})=>MaybePromise<void|App.Error>;HandleValidationError
ThehandleValidationError hook runs when the argument to a remote function fails validation.
It will be called with the validation issues and the event, and must return an object shape that matchesApp.Error.
typeHandleValidationError<IssueextendsStandardSchemaV1.Issue=StandardSchemaV1.Issue>=(input:{issues:Issue[];event:RequestEvent;})=>MaybePromise<App.Error>;HttpError
The object returned by theerror function.
interfaceHttpError{…}status:number;TheHTTP status code, in the range 400-599.
body:App.Error;The content of the error.
Invalid
A function and proxy object used to imperatively create validation errors in form handlers.
Callinvalid(issue1, issue2, ...issueN) to throw a validation error.If an issue is astring, it applies to the form as a whole (and will show up infields.allIssues())Access properties to create field-specific issues:invalid.fieldName('message').The type structure mirrors the input data structure for type-safe field access.
typeInvalid<Input=any>=((...issues:Array<string|StandardSchemaV1.Issue>)=>never)&InvalidField<Input>;KitConfig
See theconfiguration reference for details.
LessThan
typeLessThan<TNumberextendsnumber,TArrayextendsany[]=[]>=TNumberextendsTArray['length']?TArray[number]:LessThan<TNumber,[...TArray,TArray['length']]>;Load
The generic form ofPageLoad andLayoutLoad. You should import those from./$types (seegenerated types)rather than usingLoad directly.
typeLoad<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,InputDataextendsRecord<string,unknown>|null=Record<string,any>|null,ParentDataextendsRecord<string,unknown>=Record<string,any>,OutputDataextendsRecord<string,unknown>|void=Record<string,any>|void,RouteIdextendsAppRouteId|null=AppRouteId|null>=(event:LoadEvent<Params,InputData,ParentData,RouteId>)=>MaybePromise<OutputData>;LoadEvent
The generic form ofPageLoadEvent andLayoutLoadEvent. You should import those from./$types (seegenerated types)rather than usingLoadEvent directly.
interfaceLoadEvent<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,DataextendsRecord<string,unknown>|null=Record<string,any>|null,ParentDataextendsRecord<string,unknown>=Record<string,any>,RouteIdextendsAppRouteId|null=AppRouteId|null>extendsNavigationEvent<Params,RouteId> {…}fetch:typeoffetch;fetch is equivalent to thenativefetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) go directly to the handler function when running on the server, without the overhead of an HTTP call. - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
textandjsonmethods of theResponseobject. Note that headers willnot be serialized, unless explicitly included viafilterSerializedResponseHeaders - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookieshere
data:Data;Contains the data returned by the route’s serverload function (in+layout.server.js or+page.server.js), if any.
setHeaders:(headers:Record<string,string>)=>void;If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
exportasyncfunctionfunctionload({ fetch,setHeaders }:{fetch:any;setHeaders:any;}):Promise<any>
load({fetch,setHeaders}) {constconsturl:"https://cms.example.com/articles.json"url=`https://cms.example.com/articles.json`;constconstresponse:anyresponse=awaitfetch:anyfetch(consturl:"https://cms.example.com/articles.json"url);setHeaders:anysetHeaders({age:anyage:constresponse:anyresponse.headers.get('age'),'cache-control':constresponse:anyresponse.headers.get('cache-control')});returnconstresponse:anyresponse.json();}Setting the same header multiple times (even in separateload functions) is an error — you can only set a given header once.
You cannot add aset-cookie header withsetHeaders — use thecookies API in a server-onlyload function instead.
setHeaders has no effect when aload function runs in the browser.
parent:()=>Promise<ParentData>;await parent() returns data from parent+layout.jsload functions.Implicitly, a missing+layout.js is treated as a({ data }) => data function, meaning that it will return and forward data from parent+layout.server.js files.
Be careful not to introduce accidental waterfalls when usingawait parent(). If for example you only want to merge parent data into the returned output, call itafter fetching your other data.
depends:(...deps:Array<`${string}:${string}`>)=>void;This function declares that theload function has adependency on one or more URLs or custom identifiers, which can subsequently be used withinvalidate() to causeload to rerun.
Most of the time you won’t need this, asfetch callsdepends on your behalf — it’s only necessary if you’re using a custom API client that bypassesfetch.
URLs can be absolute or relative to the page being loaded, and must beencoded.
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to theURI specification.
The following example shows how to usedepends to register a dependency on a custom identifier, which isinvalidated after a button click, making theload function rerun.
letletcount:numbercount=0;exportasyncfunctionfunctionload({ depends }:{depends:any;}):Promise<{count:number;}>
load({depends}) {depends:anydepends('increase:count');return{count:numbercount:letcount:numbercount++};}<script>import{ invalidate }from'$app/navigation';let{ data }=$props();constincrease=async()=>{awaitinvalidate('increase:count');}</script><p>{data.count}<p><buttonon:click={increase}>Increase Count</button>untrack:<T>(fn:()=>T)=>T;Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
exportasyncfunctionfunctionload({ untrack,url }:{untrack:any;url:any;}):Promise<{message:string;}|undefined>
load({untrack,url}) {// Untrack url.pathname so that path changes don't trigger a rerunif(untrack:anyuntrack(()=>url:anyurl.pathname==='/')) {return{message:stringmessage:'Welcome!'};}}tracing:{…}- available since v2.31.0
Access to spans for tracing. If tracing is not enabled or the function is being run in the browser, these spans will do nothing.
enabled:boolean;Whether tracing is enabled.
root:Span;The root span for the request. This span is namedsveltekit.handle.root.
current:Span;The span associated with the currentload function.
LoadProperties
typeLoadProperties<inputextendsRecord<string,any>|void>=inputextendsvoid?undefined// needs to be undefined, because void will break intellisense:inputextendsRecord<string,any>?input:unknown;Navigation
typeNavigation=|NavigationExternal|NavigationFormSubmit|NavigationPopState|NavigationLink;NavigationBase
interfaceNavigationBase{…}from:NavigationTarget|null;Where navigation was triggered from
to:NavigationTarget|null;Where navigation is going to/has gone to
willUnload:boolean;Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation)
complete:Promise<void>;A promise that resolves once the navigation is complete, and rejects if the navigationfails or is aborted. In the case of awillUnload navigation, the promise will never resolve
NavigationEnter
interfaceNavigationEnterextendsNavigationBase{…}type:'enter';The type of navigation:
form: The user submitted a<form method="GET">leave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickgoto: Navigation was triggered by agoto(...)call or a redirectpopstate: Navigation was triggered by back/forward navigation
delta?:undefined;In case of a history back/forward navigation, the number of steps to go back/forward
event?:undefined;DispatchedEvent object when navigation occured bypopstate orlink.
NavigationEvent
interfaceNavigationEvent<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,RouteIdextendsAppRouteId|null=AppRouteId|null> {…}params:Params;The parameters of the current page - e.g. for a route like/blog/[slug], a{ slug: string } object
route:{…}Info about the current route
id:RouteId;The ID of the current route - e.g. forsrc/routes/blog/[slug], it would be/blog/[slug]. It isnull when no route is matched.
url:URL;The URL of the current page
NavigationExternal
interfaceNavigationExternalextendsNavigationBase{…}type:Exclude<NavigationType,'enter'|'popstate'|'link'|'form'>;The type of navigation:
form: The user submitted a<form method="GET">leave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickgoto: Navigation was triggered by agoto(...)call or a redirectpopstate: Navigation was triggered by back/forward navigation
delta?:undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationFormSubmit
interfaceNavigationFormSubmitextendsNavigationBase{…}type:'form';The type of navigation:
form: The user submitted a<form method="GET">leave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickgoto: Navigation was triggered by agoto(...)call or a redirectpopstate: Navigation was triggered by back/forward navigation
event:SubmitEvent;TheSubmitEvent that caused the navigation
delta?:undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationLink
interfaceNavigationLinkextendsNavigationBase{…}type:'link';The type of navigation:
form: The user submitted a<form method="GET">leave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickgoto: Navigation was triggered by agoto(...)call or a redirectpopstate: Navigation was triggered by back/forward navigation
event:PointerEvent;ThePointerEvent that caused the navigation
delta?:undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationPopState
interfaceNavigationPopStateextendsNavigationBase{…}type:'popstate';The type of navigation:
form: The user submitted a<form method="GET">leave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickgoto: Navigation was triggered by agoto(...)call or a redirectpopstate: Navigation was triggered by back/forward navigation
delta:number;In case of a history back/forward navigation, the number of steps to go back/forward
event:PopStateEvent;ThePopStateEvent that caused the navigation
NavigationTarget
Information about the target of a specific navigation.
interfaceNavigationTarget<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,RouteIdextendsAppRouteId|null=AppRouteId|null> {…}params:Params|null;Parameters of the target page - e.g. for a route like/blog/[slug], a{ slug: string } object.Isnull if the target is not part of the SvelteKit app (could not be resolved to a route).
route:{…}Info about the target route
id:RouteId|null;The ID of the current route - e.g. forsrc/routes/blog/[slug], it would be/blog/[slug]. It isnull when no route is matched.
url:URL;The URL that is navigated to
NavigationType
enter: The app has hydrated/startedform: The user submitted a<form method="GET">leave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickgoto: Navigation was triggered by agoto(...)call or a redirectpopstate: Navigation was triggered by back/forward navigation
typeNavigationType=|'enter'|'form'|'leave'|'link'|'goto'|'popstate';NumericRange
typeNumericRange<TStartextendsnumber,TEndextendsnumber>=Exclude<TEnd|LessThan<TEnd>,LessThan<TStart>>;OnNavigate
The argument passed toonNavigate callbacks.
typeOnNavigate=Navigation&{/*** The type of navigation:* - `form`: The user submitted a `<form method="GET">`* - `link`: Navigation was triggered by a link click* - `goto`: Navigation was triggered by a `goto(...)` call or a redirect* - `popstate`: Navigation was triggered by back/forward navigation*/type:Exclude<NavigationType,'enter'|'leave'>;/*** Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.*/willUnload:false;};Page
The shape of thepage reactive object and the$page store.
interfacePage<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,RouteIdextendsAppRouteId|null=AppRouteId|null> {…}url:URL&{ pathname:ResolvedPathname };The URL of the current page.
params:Params;The parameters of the current page - e.g. for a route like/blog/[slug], a{ slug: string } object.
route:{…}Info about the current route.
id:RouteId;The ID of the current route - e.g. forsrc/routes/blog/[slug], it would be/blog/[slug]. It isnull when no route is matched.
status:number;HTTP status code of the current page.
error:App.Error|null;The error object of the current page, if any. Filled from thehandleError hooks.
data:App.PageData&Record<string,any>;The merged result of all data from allload functions on the current page. You can type a common denominator throughApp.PageData.
state:App.PageState;The page state, which can be manipulated using thepushState andreplaceState functions from$app/navigation.
form:any;Filled only after a form submission. Seeform actions for more info.
ParamMatcher
The shape of a param matcher. Seematching for more info.
typeParamMatcher=(param:string)=>boolean;PrerenderOption
typePrerenderOption=boolean|'auto';Redirect
The object returned by theredirect function.
interfaceRedirect{…}status:300|301|302|303|304|305|306|307|308;TheHTTP status code, in the range 300-308.
location:string;The location to redirect to.
RemoteCommand
The return value of a remotecommand function. SeeRemote functions for full documentation.
typeRemoteCommand<Input,Output>={(arg:Input):Promise<Awaited<Output>>&{updates(...queries:Array<RemoteQuery<any>|RemoteQueryOverride>):Promise<Awaited<Output>>;};/** The number of pending command executions */getpending():number;};RemoteForm
The return value of a remoteform function. SeeRemote functions for full documentation.
typeRemoteForm<InputextendsRemoteFormInput|void,Output>={/** Attachment that sets up an event handler that intercepts the form submission on the client to prevent a full page reload */[attachment:symbol]:(node:HTMLFormElement)=>void;method:'POST';/** The URL to send the form to. */action:string;/** Use the `enhance` method to influence what happens when the form is submitted. */enhance(callback:(opts:{form:HTMLFormElement;data:Input;submit:()=>Promise<void>&{updates:(...queries:Array<RemoteQuery<any>|RemoteQueryOverride>)=>Promise<void>;};})=>void|Promise<void>):{method:'POST';action:string;[attachment:symbol]:(node:HTMLFormElement)=>void;};/*** Create an instance of the form for the given `id`.* The `id` is stringified and used for deduplication to potentially reuse existing instances.* Useful when you have multiple forms that use the same remote form action, for example in a loop.* ```svelte* {#each todos as todo}*{@consttodoForm = updateTodo.for(todo.id)}*<form {...todoForm}>*{#if todoForm.result?.invalid}<p>Invalid data</p>{/if}*...*</form>*{/each}* ```*/for(id:ExtractId<Input>):Omit<RemoteForm<Input,Output>,'for'>;/** Preflight checks */preflight(schema:StandardSchemaV1<Input,any>):RemoteForm<Input,Output>;/** Validate the form contents programmatically */validate(options?:{/** Set this to `true` to also show validation issues of fields that haven't been touched yet. */includeUntouched?:boolean;/** Set this to `true` to only run the `preflight` validation. */preflightOnly?:boolean;/** Perform validation as if the form was submitted by the given button. */submitter?:HTMLButtonElement|HTMLInputElement;}):Promise<void>;/** The result of the form submission */getresult():Output|undefined;/** The number of pending submissions */getpending():number;/** Access form fields using object notation */fields:Inputextendsvoid?never:RemoteFormFields<Input>;/** Spread this onto a `<button>` or `<input type="submit">` */buttonProps:{type:'submit';formmethod:'POST';formaction:string;onclick:(event:Event)=>void;/** Use the `enhance` method to influence what happens when the form is submitted. */enhance(callback:(opts:{form:HTMLFormElement;data:Input;submit:()=>Promise<void>&{updates:(...queries:Array<RemoteQuery<any>|RemoteQueryOverride>)=>Promise<void>;};})=>void|Promise<void>):{type:'submit';formmethod:'POST';formaction:string;onclick:(event:Event)=>void;};/** The number of pending submissions */getpending():number;};};RemoteFormField
Form field accessor type that provides name(), value(), and issues() methods
typeRemoteFormField<ValueextendsRemoteFormFieldValue>=RemoteFormFieldMethods<Value>&{/*** Returns an object that can be spread onto an input element with the correct type attribute,* aria-invalid attribute if the field is invalid, and appropriate value/checked property getters/setters.*@example* ```svelte* <input {...myForm.fields.myString.as('text')} />* <input {...myForm.fields.myNumber.as('number')} />* <input {...myForm.fields.myBoolean.as('checkbox')} />* ```*/as<TextendsRemoteFormFieldType<Value>>(...args:AsArgs<T,Value>):InputElementProps<T>;};RemoteFormFieldType
typeRemoteFormFieldType<T>={[KinkeyofInputTypeMap]:TextendsInputTypeMap[K]?K:never;}[keyofInputTypeMap];RemoteFormFieldValue
typeRemoteFormFieldValue=|string|string[]|number|boolean|File|File[];RemoteFormFields
Recursive type to build form fields structure with proxy access
typeRemoteFormFields<T>=WillRecurseIndefinitely<T>extendstrue?RecursiveFormFields:NonNullable<T>extends|string|number|boolean|File?RemoteFormField<NonNullable<T>>:Textendsstring[]|File[]?RemoteFormField<T>&{[Kinnumber]:RemoteFormField<T[number]>;}:TextendsArray<inferU>?RemoteFormFieldContainer<T>&{[Kinnumber]:RemoteFormFields<U>;}:RemoteFormFieldContainer<T>&{[KinkeyofT]-?:RemoteFormFields<T[K]>;};RemoteFormInput
interfaceRemoteFormInput{…}[key: string]: MaybeArray<string|number|boolean|File|RemoteFormInput>;RemoteFormIssue
interfaceRemoteFormIssue{…}message:string;path:Array<string|number>;RemotePrerenderFunction
The return value of a remoteprerender function. SeeRemote functions for full documentation.
typeRemotePrerenderFunction<Input,Output>=(arg:Input)=>RemoteResource<Output>;RemoteQuery
typeRemoteQuery<T>=RemoteResource<T>&{/*** On the client, this function will update the value of the query without re-fetching it.** On the server, this can be called in the context of a `command` or `form` and the specified data will accompany the action response back to the client.* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.*/set(value:T):void;/*** On the client, this function will re-fetch the query from the server.** On the server, this can be called in the context of a `command` or `form` and the refreshed data will accompany the action response back to the client.* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.*/refresh():Promise<void>;/*** Temporarily override the value of a query. This is used with the `updates` method of a [command](https://svelte.dev/docs/kit/remote-functions#command-Updating-queries) or [enhanced form submission](https://svelte.dev/docs/kit/remote-functions#form-enhance) to provide optimistic updates.** ```svelte* <script>* import { getTodos, addTodo } from './todos.remote.js';* const todos = getTodos();* </script>** <form {...addTodo.enhance(async ({ data, submit }) => {* await submit().updates(* todos.withOverride((todos) => [...todos, { text: data.get('text') }])* );* })}>* <input type="text" name="text" />* <button type="submit">Add Todo</button>* </form>* ```*/withOverride(update:(current:Awaited<T>)=>Awaited<T>):RemoteQueryOverride;};RemoteQueryFunction
The return value of a remotequery function. SeeRemote functions for full documentation.
typeRemoteQueryFunction<Input,Output>=(arg:Input)=>RemoteQuery<Output>;RemoteQueryOverride
interfaceRemoteQueryOverride{…}_key:string;release():void;RemoteResource
typeRemoteResource<T>=Promise<Awaited<T>>&{/** The error in case the query fails. Most often this is a [`HttpError`](https://svelte.dev/docs/kit/@sveltejs-kit#HttpError) but it isn't guaranteed to be. */geterror():any;/** `true` before the first result is available and during refreshes */getloading():boolean;}&(|{/** The current value of the query. Undefined until `ready` is `true` */getcurrent():undefined;ready:false;}|{/** The current value of the query. Undefined until `ready` is `true` */getcurrent():Awaited<T>;ready:true;});RequestEvent
interfaceRequestEvent<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,RouteIdextendsAppRouteId|null=AppRouteId|null> {…}cookies:Cookies;Get or set cookies related to the current request
fetch:typeoffetch;fetch is equivalent to thenativefetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) go directly to the handler function when running on the server, without the overhead of an HTTP call. - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
textandjsonmethods of theResponseobject. Note that headers willnot be serialized, unless explicitly included viafilterSerializedResponseHeaders - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookieshere.
getClientAddress:()=>string;The client’s IP address, set by the adapter.
locals:App.Locals;Contains custom data that was added to the request within theserver handle hook.
params:Params;The parameters of the current route - e.g. for a route like/blog/[slug], a{ slug: string } object.
platform:Readonly<App.Platform>|undefined;Additional data made available through the adapter.
request:Request;The original request object.
route:{…}Info about the current route.
id:RouteId;The ID of the current route - e.g. forsrc/routes/blog/[slug], it would be/blog/[slug]. It isnull when no route is matched.
setHeaders:(headers:Record<string,string>)=>void;If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
exportasyncfunctionfunctionload({ fetch,setHeaders }:{fetch:any;setHeaders:any;}):Promise<any>
load({fetch,setHeaders}) {constconsturl:"https://cms.example.com/articles.json"url=`https://cms.example.com/articles.json`;constconstresponse:anyresponse=awaitfetch:anyfetch(consturl:"https://cms.example.com/articles.json"url);setHeaders:anysetHeaders({age:anyage:constresponse:anyresponse.headers.get('age'),'cache-control':constresponse:anyresponse.headers.get('cache-control')});returnconstresponse:anyresponse.json();}Setting the same header multiple times (even in separateload functions) is an error — you can only set a given header once.
You cannot add aset-cookie header withsetHeaders — use thecookies API instead.
url:URL;The requested URL.
isDataRequest:boolean;true if the request comes from the client asking for+page/layout.server.js data. Theurl property will be stripped of the internal informationrelated to the data request in this case. Use this property instead if the distinction is important to you.
isSubRequest:boolean;true for+server.js calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-originfetch requests on the server.
tracing:{…}- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
enabled:boolean;Whether tracing is enabled.
root:Span;The root span for the request. This span is namedsveltekit.handle.root.
current:Span;The span associated with the currenthandle hook,load function, or form action.
isRemoteRequest:boolean;true if the request comes from the client via a remote function. Theurl property will be stripped of the internal informationrelated to the data request in this case. Use this property instead if the distinction is important to you.
RequestHandler
A(event: RequestEvent) => Response function exported from a+server.js file that corresponds to an HTTP verb (GET,PUT,PATCH, etc) and handles requests with that method.
It receivesParams as the first generic argument, which you can skip by usinggenerated types instead.
typeRequestHandler<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,RouteIdextendsAppRouteId|null=AppRouteId|null>=(event:RequestEvent<Params,RouteId>)=>MaybePromise<Response>;Reroute
Available since 2.3.0
Thereroute hook allows you to modify the URL before it is used to determine which route to render.
typeReroute=(event:{url:URL;fetch:typeoffetch;})=>MaybePromise<void|string>;ResolveOptions
interfaceResolveOptions{…}transformPageChunk?:(input:{ html:string; done:boolean})=>MaybePromise<string|undefined>;inputthe html chunk and the info if this is the last chunk
Applies custom transforms to HTML. Ifdone is true, it’s the final chunk. Chunks are not guaranteed to be well-formed HTML(they could include an element’s opening tag but not its closing tag, for example)but they will always be split at sensible boundaries such as%sveltekit.head% or layout/page components.
filterSerializedResponseHeaders?:(name:string,value:string)=>boolean;nameheader namevalueheader value
Determines which headers should be included in serialized responses when aload function loads a resource withfetch.By default, none will be included.
preload?:(input:{ type:'font'|'css'|'js'|'asset'; path:string})=>boolean;inputthe type of the file and its path
Determines what should be added to the<head> tag to preload it.By default,js andcss files will be preloaded.
RouteDefinition
interfaceRouteDefinition<Config=any> {…}id:string;api:{methods:Array<HttpMethod|'*'>;};page:{methods:Array<Extract<HttpMethod,'GET'|'POST'>>;};pattern:RegExp;prerender:PrerenderOption;segments:RouteSegment[];methods:Array<HttpMethod|'*'>;config:Config;SSRManifest
interfaceSSRManifest{…}appDir:string;appPath:string;assets:Set<string>;Static files fromkit.config.files.assets and the service worker (if any).
mimeTypes:Record<string,string>;_:{…}private fields
client:NonNullable<BuildData['client']>;nodes:SSRNodeLoader[];remotes:Record<string,()=>Promise<any>>;hashed filename -> import to that file
routes:SSRRoute[];prerendered_routes:Set<string>;matchers:()=>Promise<Record<string,ParamMatcher>>;server_assets:Record<string,number>;A[file]: size map of all assets imported by server code.
ServerInit
Available since 2.10.0
Theinit will be invoked before the server responds to its first request
typeServerInit=()=>MaybePromise<void>;ServerInitOptions
interfaceServerInitOptions{…}env:Record<string,string>;A map of environment variables.
read?:(file:string)=>MaybePromise<ReadableStream|null>;A function that turns an asset filename into aReadableStream. Required for theread export from$app/server to work.
ServerLoad
The generic form ofPageServerLoad andLayoutServerLoad. You should import those from./$types (seegenerated types)rather than usingServerLoad directly.
typeServerLoad<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,ParentDataextendsRecord<string,any>=Record<string,any>,OutputDataextendsRecord<string,any>|void=Record<string,any>|void,RouteIdextendsAppRouteId|null=AppRouteId|null>=(event:ServerLoadEvent<Params,ParentData,RouteId>)=>MaybePromise<OutputData>;ServerLoadEvent
interfaceServerLoadEvent<ParamsextendsAppLayoutParams<'/'>=AppLayoutParams<'/'>,ParentDataextendsRecord<string,any>=Record<string,any>,RouteIdextendsAppRouteId|null=AppRouteId|null>extendsRequestEvent<Params,RouteId> {…}parent:()=>Promise<ParentData>;await parent() returns data from parent+layout.server.jsload functions.
Be careful not to introduce accidental waterfalls when usingawait parent(). If for example you only want to merge parent data into the returned output, call itafter fetching your other data.
depends:(...deps:string[])=>void;This function declares that theload function has adependency on one or more URLs or custom identifiers, which can subsequently be used withinvalidate() to causeload to rerun.
Most of the time you won’t need this, asfetch callsdepends on your behalf — it’s only necessary if you’re using a custom API client that bypassesfetch.
URLs can be absolute or relative to the page being loaded, and must beencoded.
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to theURI specification.
The following example shows how to usedepends to register a dependency on a custom identifier, which isinvalidated after a button click, making theload function rerun.
letletcount:numbercount=0;exportasyncfunctionfunctionload({ depends }:{depends:any;}):Promise<{count:number;}>
load({depends}) {depends:anydepends('increase:count');return{count:numbercount:letcount:numbercount++};}<script>import{ invalidate }from'$app/navigation';let{ data }=$props();constincrease=async()=>{awaitinvalidate('increase:count');}</script><p>{data.count}<p><buttonon:click={increase}>Increase Count</button>untrack:<T>(fn:()=>T)=>T;Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
exportasyncfunctionfunctionload({ untrack,url }:{untrack:any;url:any;}):Promise<{message:string;}|undefined>
load({untrack,url}) {// Untrack url.pathname so that path changes don't trigger a rerunif(untrack:anyuntrack(()=>url:anyurl.pathname==='/')) {return{message:stringmessage:'Welcome!'};}}tracing:{…}- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
enabled:boolean;Whether tracing is enabled.
root:Span;The root span for the request. This span is namedsveltekit.handle.root.
current:Span;The span associated with the current serverload function.
Snapshot
The type ofexport const snapshot exported from a page or layout component.
interfaceSnapshot<T=any> {…}capture:()=>T;restore:(snapshot:T)=>void;SubmitFunction
typeSubmitFunction<Successextends|Record<string,unknown>|undefined=Record<string,any>,Failureextends|Record<string,unknown>|undefined=Record<string,any>>=(input:{action:URL;formData:FormData;formElement:HTMLFormElement;controller:AbortController;submitter:HTMLElement|null;cancel:()=>void;})=>MaybePromise<|void|((opts:{formData:FormData;formElement:HTMLFormElement;action:URL;result:ActionResult<Success,Failure>;/*** Call this to get the default behavior of a form submission response.*@paramoptions Set `reset: false` if you don't want the `<form>` values to be reset after a successful submission.*@paraminvalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission.*/update:(options?:{reset?:boolean;invalidateAll?:boolean;})=>Promise<void>;})=>MaybePromise<void>)>;Transport
Available since 2.11.0
Thetransport hook allows you to transport custom types across the server/client boundary.
Each transporter has a pair ofencode anddecode functions. On the server,encode determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (orfalse otherwise).
In the browser,decode turns the encoding back into an instance of the custom type.
importtype{typeTransport={[x:string]:Transporter<any,any>;}
Thetransport hook allows you to transport custom types across the server/client boundary.
Each transporter has a pair ofencode anddecode functions. On the server,encode determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (orfalse otherwise).
In the browser,decode turns the encoding back into an instance of the custom type.
importtype{ Transport }from'@sveltejs/kit';declareclassMyCustomType{data:any}// hooks.jsexportconsttransport:Transport={MyCustomType:{encode:(value)=>valueinstanceofMyCustomType&& [value.data],decode:([data])=>newMyCustomType(data)}};
@since2.11.0Transport}from'@sveltejs/kit';declareclassclassMyCustomTypeMyCustomType{MyCustomType.data: anydata:any}// hooks.jsexportconstconsttransport:Transporttransport:typeTransport={[x:string]:Transporter<any,any>;}
Thetransport hook allows you to transport custom types across the server/client boundary.
Each transporter has a pair ofencode anddecode functions. On the server,encode determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (orfalse otherwise).
In the browser,decode turns the encoding back into an instance of the custom type.
importtype{ Transport }from'@sveltejs/kit';declareclassMyCustomType{data:any}// hooks.jsexportconsttransport:Transport={MyCustomType:{encode:(value)=>valueinstanceofMyCustomType&& [value.data],decode:([data])=>newMyCustomType(data)}};
@since2.11.0Transport={typeMyCustomType: {encode: (value: any)=>false|any[];decode:([data]:any)=>MyCustomType;}
MyCustomType:{Transporter<any,any>.encode: (value:any)=>anyencode:(value:anyvalue)=>value:anyvalueinstanceofclassMyCustomTypeMyCustomType&&[value:MyCustomTypevalue.MyCustomType.data: anydata],Transporter<any,any>.decode: (data:any)=>anydecode:([data:anydata])=>newconstructorMyCustomType(): MyCustomTypeMyCustomType(data:anydata)}};typeTransport=Record<string,Transporter>;Transporter
A member of thetransport hook.
interfaceTransporter<T=any,U=Exclude<any,false|0|''|null|undefined|typeofNaN>> {…}encode:(value:T)=>false|U;decode:(data:U)=>T;Private types
The following are referenced by the public types documented above, but cannot be imported directly:
AdapterEntry
interfaceAdapterEntry{…}id:string;A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication.For example,/foo/a-[b] and/foo/[c] are different routes, but would bothbe represented in a Netlify _redirects file as/foo/:param, so they share an ID
filter(route: RouteDefinition): boolean;A function that compares the candidate route with the current route to determineif it should be grouped with the current route.
Use cases:
- Fallback pages:
/foo/[c]is a fallback for/foo/a-[b], and/[...catchall]is a fallback for all routes - Grouping routes that share a common
config:/fooshould be deployed to the edge,/barand/bazshould be deployed to a serverless function
complete(entry: {generateManifest(opts:{ relativePath:string}):string}): MaybePromise<void>;A function that is invoked once the entry has been created. This is where youshould write the function to the filesystem and generate redirect manifests.
Csp
namespaceCsp{typeActionSource='strict-dynamic'|'report-sample';typeBaseSource=|'self'|'unsafe-eval'|'unsafe-hashes'|'unsafe-inline'|'wasm-unsafe-eval'|'none';typeCryptoSource=`${'nonce'|'sha256'|'sha384'|'sha512'}-${string}`;typeFrameSource=|HostSource|SchemeSource|'self'|'none';typeHostNameScheme=`${string}.${string}`|'localhost';typeHostSource=`${HostProtocolSchemes}${HostNameScheme}${PortScheme}`;typeHostProtocolSchemes=`${string}://`|'';typeHttpDelineator='/'|'?'|'#'|'\\';typePortScheme=`:${number}`|''|':*';typeSchemeSource=|'http:'|'https:'|'data:'|'mediastream:'|'blob:'|'filesystem:';typeSource=|HostSource|SchemeSource|CryptoSource|BaseSource;typeSources=Source[];}CspDirectives
interfaceCspDirectives{…}'child-src'?:Csp.Sources;'default-src'?:Array<Csp.Source|Csp.ActionSource>;'frame-src'?:Csp.Sources;'worker-src'?:Csp.Sources;'connect-src'?:Csp.Sources;'font-src'?:Csp.Sources;'img-src'?:Csp.Sources;'manifest-src'?:Csp.Sources;'media-src'?:Csp.Sources;'object-src'?:Csp.Sources;'prefetch-src'?:Csp.Sources;'script-src'?:Array<Csp.Source|Csp.ActionSource>;'script-src-elem'?:Csp.Sources;'script-src-attr'?:Csp.Sources;'style-src'?:Array<Csp.Source|Csp.ActionSource>;'style-src-elem'?:Csp.Sources;'style-src-attr'?:Csp.Sources;'base-uri'?:Array<Csp.Source|Csp.ActionSource>;sandbox?:Array<|'allow-downloads-without-user-activation'|'allow-forms'|'allow-modals'|'allow-orientation-lock'|'allow-pointer-lock'|'allow-popups'|'allow-popups-to-escape-sandbox'|'allow-presentation'|'allow-same-origin'|'allow-scripts'|'allow-storage-access-by-user-activation'|'allow-top-navigation'|'allow-top-navigation-by-user-activation'>;'form-action'?:Array<Csp.Source|Csp.ActionSource>;'frame-ancestors'?:Array<Csp.HostSource|Csp.SchemeSource|Csp.FrameSource>;'navigate-to'?:Array<Csp.Source|Csp.ActionSource>;'report-uri'?:string[];'report-to'?:string[];'require-trusted-types-for'?:Array<'script'>;'trusted-types'?:Array<'none'|'allow-duplicates'|'*'|string>;'upgrade-insecure-requests'?:boolean;'require-sri-for'?:Array<'script'|'style'|'script style'>;- deprecated
'block-all-mixed-content'?:boolean;- deprecated
'plugin-types'?:Array<`${string}/${string}`|'none'>;- deprecated
referrer?:Array<|'no-referrer'|'no-referrer-when-downgrade'|'origin'|'origin-when-cross-origin'|'same-origin'|'strict-origin'|'strict-origin-when-cross-origin'|'unsafe-url'|'none'>;- deprecated
HttpMethod
typeHttpMethod=|'GET'|'HEAD'|'POST'|'PUT'|'DELETE'|'PATCH'|'OPTIONS';Logger
interfaceLogger{…}(msg:string):void;success(msg: string):void;error(msg: string):void;warn(msg: string):void;minor(msg: string):void;info(msg: string):void;MaybePromise
typeMaybePromise<T>=T|Promise<T>;PrerenderEntryGeneratorMismatchHandler
interfacePrerenderEntryGeneratorMismatchHandler{…}(details:{ generatedFromId:string; entry:string; matchedId:string; message:string}):void;PrerenderEntryGeneratorMismatchHandlerValue
typePrerenderEntryGeneratorMismatchHandlerValue=|'fail'|'warn'|'ignore'|PrerenderEntryGeneratorMismatchHandler;PrerenderHttpErrorHandler
interfacePrerenderHttpErrorHandler{…}(details:{status:number;path:string;referrer:string|null;referenceType:'linked'|'fetched';message:string;}):void;PrerenderHttpErrorHandlerValue
typePrerenderHttpErrorHandlerValue=|'fail'|'warn'|'ignore'|PrerenderHttpErrorHandler;PrerenderMap
typePrerenderMap=Map<string,PrerenderOption>;PrerenderMissingIdHandler
interfacePrerenderMissingIdHandler{…}(details:{ path:string; id:string; referrers:string[]; message:string}):void;PrerenderMissingIdHandlerValue
typePrerenderMissingIdHandlerValue=|'fail'|'warn'|'ignore'|PrerenderMissingIdHandler;PrerenderOption
typePrerenderOption=boolean|'auto';PrerenderUnseenRoutesHandler
interfacePrerenderUnseenRoutesHandler{…}(details:{ routes:string[]; message:string}):void;PrerenderUnseenRoutesHandlerValue
typePrerenderUnseenRoutesHandlerValue=|'fail'|'warn'|'ignore'|PrerenderUnseenRoutesHandler;Prerendered
interfacePrerendered{…}pages:Map<string,{/** The location of the .html file relative to the output directory */file:string;}>;A map ofpath to{ file } objects, where a path like/foo corresponds tofoo.html and a path like/bar/ corresponds tobar/index.html.
assets:Map<string,{/** The MIME type of the asset */type:string;}>;A map ofpath to{ type } objects.
redirects:Map<string,{status:number;location:string;}>;A map of redirects encountered during prerendering.
paths:string[];An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
RequestOptions
interfaceRequestOptions{…}getClientAddress(): string;platform?:App.Platform;RouteSegment
interfaceRouteSegment{…}content:string;dynamic:boolean;rest:boolean;TrailingSlash
typeTrailingSlash='never'|'always'|'ignore';Edit this page on GitHub llms.txt