|
| 1 | +--- |
| 2 | +title: Web standards |
| 3 | +--- |
| 4 | + |
| 5 | +Throughout this documentation, you'll see references to the standard [Web APIs](https://developer.mozilla.org/en-US/docs/Web/API) 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. |
| 6 | + |
| 7 | +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](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). |
| 8 | + |
| 9 | +In particular, you'll get comfortable with the following: |
| 10 | + |
| 11 | +## Fetch APIs |
| 12 | + |
| 13 | +SvelteKit uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for getting data from the network. It's available in [hooks](hooks) and [server routes](routing#server) as well as in the browser. |
| 14 | + |
| 15 | +> A special version of `fetch` is available in [`load`](load) functions, [server hooks](hooks#server-hooks) and [API routes](routing#server) 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. |
| 16 | +
|
| 17 | +Besides `fetch` itself, the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) includes the following interfaces: |
| 18 | + |
| 19 | +### Request |
| 20 | + |
| 21 | +An instance of [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) is accessible in [hooks](hooks) and [server routes](routing#server) as `event.request`. It contains useful methods like `request.json()` and `request.formData()` for getting data that was posted to an endpoint. |
| 22 | + |
| 23 | +### Response |
| 24 | + |
| 25 | +An instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/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`. |
| 26 | + |
| 27 | +### Headers |
| 28 | + |
| 29 | +The [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/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](modules#sveltejs-kit-json) to send modified `response.headers`: |
| 30 | + |
| 31 | +```js |
| 32 | +// @errors: 2461 |
| 33 | +/// file: src/routes/what-is-my-user-agent/+server.js |
| 34 | +import { json } from '@sveltejs/kit'; |
| 35 | + |
| 36 | +/** @type {import('./$types').RequestHandler} */ |
| 37 | +export function GET({ request }) { |
| 38 | + // log all headers |
| 39 | + console.log(...request.headers); |
| 40 | + |
| 41 | + // create a JSON Response using a header we received |
| 42 | + return json({ |
| 43 | + // retrieve a specific header |
| 44 | + userAgent: request.headers.get('user-agent') |
| 45 | + }, { |
| 46 | + // set a header on the response |
| 47 | + headers: { 'x-custom-header': 'potato' } |
| 48 | + }); |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +## FormData |
| 53 | + |
| 54 | +When dealing with HTML native form submissions you'll be working with [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) objects. |
| 55 | + |
| 56 | +```js |
| 57 | +// @errors: 2461 |
| 58 | +/// file: src/routes/hello/+server.js |
| 59 | +import { json } from '@sveltejs/kit'; |
| 60 | + |
| 61 | +/** @type {import('./$types').RequestHandler} */ |
| 62 | +export async function POST(event) { |
| 63 | + const body = await event.request.formData(); |
| 64 | + |
| 65 | + // log all fields |
| 66 | + console.log([...body]); |
| 67 | + |
| 68 | + return json({ |
| 69 | + // get a specific field's value |
| 70 | + name: body.get('name') ?? 'world' |
| 71 | + }); |
| 72 | +} |
| 73 | +``` |
| 74 | +
|
| 75 | +## Stream APIs |
| 76 | +
|
| 77 | +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](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) — [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), [WritableStream](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) and [TransformStream](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream). |
| 78 | +
|
| 79 | +## URL APIs |
| 80 | +
|
| 81 | +URLs are represented by the [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/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](hooks) and [server routes](routing#server), [`$page.url`](modules#$app-stores) in [pages](routing#page), `from` and `to` in [`beforeNavigate` and `afterNavigate`](modules#$app-navigation) and so on. |
| 82 | +
|
| 83 | +### URLSearchParams |
| 84 | +
|
| 85 | +Wherever you encounter a URL, you can access query parameters via `url.searchParams`, which is an instance of [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams): |
| 86 | +
|
| 87 | +```js |
| 88 | +// @filename: ambient.d.ts |
| 89 | +declare global { |
| 90 | + const url: URL; |
| 91 | +} |
| 92 | + |
| 93 | +export {}; |
| 94 | + |
| 95 | +// @filename: index.js |
| 96 | +// ---cut--- |
| 97 | +const foo = url.searchParams.get('foo'); |
| 98 | +``` |
| 99 | +
|
| 100 | +## Web Crypto |
| 101 | +
|
| 102 | +The [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) is made available via the `crypto` global. It's used internally for [Content Security Policy](configuration#csp) headers, but you can also use it for things like generating UUIDs: |
| 103 | +
|
| 104 | +```js |
| 105 | +const uuid = crypto.randomUUID(); |
| 106 | +``` |
0 commit comments