Web standards
Throughout this documentation, you’ll see references to the standard Web APIs that SvelteKit builds on top of. Rather than reinventing the wheel, we use the platform, which means your existing web development skills are applicable to SvelteKit. Conversely, time spent learning SvelteKit will help you be a better web developer elsewhere.
These APIs are available in all modern browsers and in many non-browser environments like Cloudflare Workers, Deno, and Vercel Functions. During development, and in adapters for Node-based environments (including AWS Lambda), they’re made available via polyfills where necessary (for now, that is — Node is rapidly adding support for more web standards).
In particular, you’ll get comfortable with the following:
Fetch APIs
SvelteKit uses fetch for getting data from the network. It’s available in hooks and server routes as well as in the browser.
A special version of
fetchis available inloadfunctions, server hooks and API routes for invoking endpoints directly during server-side rendering, without making an HTTP call, while preserving credentials. (To make credentialled fetches in server-side code outsideload, you must explicitly passcookieand/orauthorizationheaders.) It also allows you to make relative requests, whereas server-sidefetchnormally requires a fully qualified URL.
Besides fetch itself, the Fetch API includes the following interfaces:
Request
An instance of Request is accessible in hooks and server routes as event.request. It contains useful methods like request.json() and request.formData() for getting data that was posted to an endpoint.
Response
An instance of Response is returned from await fetch(...) and handlers in +server.js files. Fundamentally, a SvelteKit app is a machine for turning a Request into a Response.
Headers
The Headers interface allows you to read incoming request.headers and set outgoing response.headers. For example, you can get the request.headers as shown below, and use the json convenience function to send modified response.headers:
import { function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json } from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */
export function function GET({ request }: {
request: any;
}): Response
GET({ request: anyrequest }) {
// log all headers
var console: Consoleconsole.Console.log(...data: any[]): voidlog(...request: anyrequest.headers);
// create a JSON Response using a header we received
return function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json({
// retrieve a specific header
userAgent: anyuserAgent: request: anyrequest.headers.get('user-agent')
}, {
// set a header on the response
ResponseInit.headers?: HeadersInit | undefinedheaders: { 'x-custom-header': 'potato' }
});
}import { function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json } from '@sveltejs/kit';
import type { type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler } from './$types';
export const const GET: RequestHandlerGET: type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler = ({ request: RequestThe original request object.
request }) => {
// log all headers
var console: Consoleconsole.Console.log(...data: any[]): voidlog(...request: RequestThe original request object.
request.Request.headers: HeadersReturns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.
headers);
// create a JSON Response using a header we received
return function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json({
// retrieve a specific header
userAgent: string | nulluserAgent: request: RequestThe original request object.
request.Request.headers: HeadersReturns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.
headers.Headers.get(name: string): string | nullget('user-agent')
}, {
// set a header on the response
ResponseInit.headers?: HeadersInit | undefinedheaders: { 'x-custom-header': 'potato' }
});
};FormData
When dealing with HTML native form submissions you’ll be working with FormData objects.
import { function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json } from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */
export async function function POST(event: any): Promise<Response>POST(event: anyevent) {
const const body: anybody = await event: anyevent.request.formData();
// log all fields
var console: Consoleconsole.Console.log(...data: any[]): voidlog([...const body: anybody]);
return function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json({
// get a specific field's value
name: anyname: const body: anybody.get('name') ?? 'world'
});
}import { function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json } from '@sveltejs/kit';
import type { type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler } from './$types';
export const const POST: RequestHandlerPOST: type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler = async (event: Kit.RequestEvent<Record<string, any>, string | null>event) => {
const const body: FormDatabody = await event: Kit.RequestEvent<Record<string, any>, string | null>event.RequestEvent<Record<string, any>, string | null>.request: RequestThe original request object.
request.Body.formData(): Promise<FormData>formData();
// log all fields
var console: Consoleconsole.Console.log(...data: any[]): voidlog([...const body: FormDatabody]);
return function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json({
// get a specific field's value
name: FormDataEntryValuename: const body: FormDatabody.FormData.get(name: string): FormDataEntryValue | nullget('name') ?? 'world'
});
};Stream APIs
Most of the time, your endpoints will return complete data, as in the userAgent example above. Sometimes, you may need to return a response that’s too large to fit in memory in one go, or is delivered in chunks, and for this the platform provides streams — ReadableStream, WritableStream and TransformStream.
URL APIs
URLs are represented by the URL interface, which includes useful properties like origin and pathname (and, in the browser, hash). This interface shows up in various places — event.url in hooks and server routes, page.url in pages, from and to in beforeNavigate and afterNavigate and so on.
URLSearchParams
Wherever you encounter a URL, you can access query parameters via url.searchParams, which is an instance of URLSearchParams:
const const foo: string | nullfoo = const url: URLurl.URL.searchParams: URLSearchParamssearchParams.URLSearchParams.get(name: string): string | nullReturns the first value associated to the given search parameter.
get('foo');Web Crypto
The Web Crypto API is made available via the crypto global. It’s used internally for Content Security Policy headers, but you can also use it for things like generating UUIDs:
const const uuid: `${string}-${string}-${string}-${string}-${string}`uuid = var crypto: Cryptocrypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`Available only in secure contexts.
randomUUID();Edit this page on GitHub llms.txt