Fetch APIs
SvelteKit usesfetch for getting data from the network. It’s available in hooks and server routes as well as in the browser.
A special version of
fetch is available in load functions, 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 outside load, you must explicitly pass cookie and/or authorization headers. It also allows you to make relative requests, whereas server-side fetch normally requires a fully qualified URL.fetch itself, the Fetch API includes the following interfaces:
Request
An instance ofRequest 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.
src/routes/api/user/+server.js
Response
An instance ofResponse 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.
src/routes/api/data/+server.js
Headers
TheHeaders interface allows you to read incoming request.headers and set outgoing response.headers.
src/routes/what-is-my-user-agent/+server.js
FormData
When dealing with HTML native form submissions you’ll be working withFormData objects.
src/routes/login/+page.server.js
Stream APIs
Most of the time, your endpoints will return complete data. 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:Example: Streaming response
URL APIs
URLs are represented by theURL interface, which includes useful properties like origin and pathname (and, in the browser, hash). This interface shows up in various places:
event.urlin hooks and server routes$page.urlin pagesfromandtoinbeforeNavigateandafterNavigate
Example: Accessing URL properties
Example: Accessing URL properties
src/routes/blog/+page.server.js
URLSearchParams
Wherever you encounter a URL, you can access query parameters viaurl.searchParams, which is an instance of URLSearchParams:
Working with search parameters
Working with search parameters
src/routes/search/+page.server.js
Web Crypto
The Web Crypto API is made available via thecrypto global. It’s used internally for Content Security Policy headers, but you can also use it for things like generating UUIDs:
Example: Hashing with Web Crypto
Example: Hashing with Web Crypto
src/lib/server/crypto.js
Benefits of using web standards
By building on web standards, SvelteKit provides several advantages:Transferable skills
Knowledge you gain is applicable across the web platform, not just SvelteKit
Future-proof
As browsers add new features, SvelteKit apps benefit automatically
Better compatibility
Code works across different runtimes: Node.js, Deno, Cloudflare Workers, etc.
Reduced learning curve
If you know web APIs, you already know much of SvelteKit