Skip to content

Commit a65a29a

Browse files
[Rules] Add Snippets example to follow redirects from origin (#18522)
--------- Co-authored-by: Pedro Sousa <[email protected]>
1 parent 929aade commit a65a29a

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
---
2+
type: example
3+
summary: Modify the fetch request to follow redirects from the origin, ensuring the client receives the final response.
4+
goal:
5+
- Routing
6+
operation:
7+
- Redirect
8+
products:
9+
- Snippets
10+
pcx_content_type: example
11+
title: Follow redirects from the origin
12+
description: Modify the fetch request to follow redirects from the origin, ensuring the client receives the final response.
13+
---
14+
15+
```js wrap
16+
export default {
17+
async fetch(request) {
18+
// Define fetch options to follow redirects
19+
const fetchOptions = {
20+
redirect: "follow", // Ensure fetch follows redirects automatically. Each subrequest in a redirect chain counts against the subrequest limit.
21+
};
22+
23+
// Make the fetch request to the origin
24+
const response = await fetch(request, fetchOptions);
25+
26+
// Log the final URL after redirects (optional, for debugging)
27+
console.log(`Final URL after redirects: ${response.url}`);
28+
29+
// Return the final response to the client
30+
return response;
31+
},
32+
};
33+
```
34+
35+
This template is ready for use and should fit most redirect-following scenarios.
36+
37+
It ensures the Snippet transparently follows redirects issued by the origin server. The `redirect: "follow"` option of the [Fetch API](/workers/runtime-apis/fetch/) ensures automatic handling of `3xx` redirects, returning the final response. If the origin response is not a redirect, the original content is returned.
38+
39+
:::note
40+
Snippets have a [maximum number of subrequests per invocation](/rules/snippets/#availability) which depends on your plan. If the origin server issues multiple redirects, each redirect subrequest will count towards this limit. When the number of subrequests exceeds the limit for your Cloudflare plan, you will receive a [1202 error](/rules/snippets/errors/#error-1202-snippets-exceeded-subrequests-limit). Ensure your origin configuration minimizes unnecessary redirects.
41+
:::

0 commit comments

Comments
 (0)