Skip to content

Commit a0ce968

Browse files
committed
[Rules] Snippets example to follow redirects from origin
1 parent 7e150c1 commit a0ce968

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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
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. Remember that each subrequest in a redirect chain counts against 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.
38+
The `fetch()` API's `redirect: "follow"` option ensures automatic handling of `3xx` redirects, returning the final response. If the origin response is not a redirect, the original content is returned.
39+
40+
**Important**: 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. Ensure your origin configuration minimizes unnecessary redirects.

0 commit comments

Comments
 (0)