Skip to content

Commit 506c8c5

Browse files
author
Rich Harris
committed
handleFetch exercise
1 parent 7189200 commit 506c8c5

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

content/tutorial/04-advanced-sveltekit/01-hooks/03-handle-fetch/README.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,33 @@
22
title: handleFetch
33
---
44

5-
> Coming soon
5+
The `event` object has a `fetch` method that behaves like the standard [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API), but with superpowers:
6+
7+
- it can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers from the incoming request
8+
- it can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context)
9+
- internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call
10+
11+
Its behaviour can be modified with the `handleFetch` hook, which by default looks like this:
12+
13+
```js
14+
/// file: src/hooks.server.js
15+
export async function handleFetch({ event, request, fetch }) {
16+
return await fetch(request);
17+
}
18+
```
19+
20+
For example, we could respond to requests for `src/routes/a/+server.js` with responses from `src/routes/b/+server.js` instead:
21+
22+
```js
23+
/// file: src/hooks.server.js
24+
export async function handleFetch({ event, request, fetch }) {
25+
+++ const url = new URL(request.url);
26+
if (url.pathname === '/a') {
27+
return await fetch('/b');
28+
}+++
29+
30+
return await fetch(request);
31+
}
32+
```
33+
34+
Later, when we cover [universal `load` functions](universal-load-functions), we'll see that `event.fetch` can also be called from the browser. In that scenario, `handleFetch` is useful if you have requests to a public URL like `https://api.yourapp.com` from the browser, that should be redirected to an internal URL (bypassing whatever proxies and load balancers sit between the API server and the public internet) when running on the server.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export async function handleFetch({ event, request, fetch }) {
2+
return await fetch(request);
3+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export async function handleFetch({ event, request, fetch }) {
2+
const url = new URL(request.url);
3+
if (url.pathname === '/a') {
4+
return await fetch('/b');
5+
}
6+
7+
return await fetch(request);
8+
}

0 commit comments

Comments
 (0)