Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/content/docs/rules/examples.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
---

pcx_content_type: navigation
title: Examples
sidebar:
Expand All @@ -19,5 +18,5 @@ We have a separate listing for [Cache rules examples](/cache/how-to/cache-rules/
<ResourcesBySelector
directory="rules"
types={["example"]}
filterables={["products", "goal", "operation"]}
filterables={["products", "tags"]}
/>
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
---

summary: Set up an A/B test by controlling what response is served based on cookies.
goal:
tags:
- A/B testing
operation:
- Cookies manipulation
- Rewrite URL
- Cookies
- URL rewrite
products:
- Snippets
pcx_content_type: example
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
---

summary: Dynamically set a cookie expiration and test group.
goal:
tags:
- A/B testing
operation:
- Cookies manipulation
- Cookies
products:
- Snippets
pcx_content_type: example
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
---

summary: Allow or deny a request based on a known pre-shared key in a header.
This is not meant to replace the [WebCrypto
API](/workers/runtime-apis/web-crypto/).
goal:
tags:
- Authentication
operation:
- Request modification
products:
- Snippets
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
---

summary: Send [Bots](/bots/) information to your origin. Refer to [Bot
Managenent variables](/bots/reference/bot-management-variables/) for a full
list of available fields.
goal:
- Manage headers
operation:
tags:
- Headers
- Request modification
products:
- Snippets
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
---

summary: Use the [bot score
field](/workers/runtime-apis/request/#incomingrequestcfproperties) to send
bots to a honeypot.
goal:
- Routing
operation:
- Redirect
tags:
- Redirects
products:
- Snippets
pcx_content_type: example
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
---

summary: Redirect requests to certain URLs based on a mapped object to the
request's URL.
goal:
- Routing
operation:
- Redirect
tags:
- Redirects
products:
- Snippets
pcx_content_type: example
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
---

summary: Redirect a response based on the country code in the header of a visitor.
goal:
tags:
- Localization
operation:
- Redirect
- Redirects
products:
- Snippets
preview:
Expand Down
146 changes: 75 additions & 71 deletions src/content/docs/rules/snippets/examples/custom-cache.mdx
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
---

summary: Control cache programmatically. Use this template to optimize performance and implement custom caching strategies.
goal:
- Other
operation:
- Cache
tags:
- Caching
products:
- Snippets
pcx_content_type: example
Expand All @@ -22,49 +19,54 @@ const USE_QUERY_STRING = true; // Include query string in the cache key
const INCLUDE_HEADERS = ["User-Agent"]; // Headers to include in the cache key

export default {
async fetch(request, env, ctx) {
// Generate a custom cache key based on user preferences
const cacheKey = createCacheKey(request);
console.log(`Retrieving cache for: ${cacheKey.url}.`)

// Access the default Cache API
const cache = caches.default;

// Attempt to retrieve the cached response
let response = await cache.match(cacheKey);

if (!response) {
// Cache miss: Fetch the asset from the origin
console.log(`Cache miss for: ${cacheKey.url}. Fetching from origin...`);
response = await fetch(request);

// Wrap the origin response for caching
response = new Response(response.body, response);

// Set Cache-Control headers to define the TTL
response.headers.set("Cache-Control", `s-maxage=${CACHE_DURATION_SECONDS}`);
response.headers.set("x-snippets-cache", "stored");

// Store the response in the cache
await cache.put(cacheKey, response.clone());
} else {
// Cache hit: Return the cached response
console.log(`Cache hit for: ${cacheKey.url}.`);
response = new Response(response.body, response);
response.headers.set("x-snippets-cache", "hit");

// Optionally check if the cache should expire based on age
const ageHeader = response.headers.get("Age");
if (ageHeader && parseInt(ageHeader, 10) > CACHE_DURATION_SECONDS) {
console.log(`Cache expired for: ${cacheKey.url}. Deleting cached response...`);
await cache.delete(cacheKey);
response.headers.set("x-snippets-cache", "deleted");
}
}

// Return the response to the client
return response;
},
async fetch(request, env, ctx) {
// Generate a custom cache key based on user preferences
const cacheKey = createCacheKey(request);
console.log(`Retrieving cache for: ${cacheKey.url}.`);

// Access the default Cache API
const cache = caches.default;

// Attempt to retrieve the cached response
let response = await cache.match(cacheKey);

if (!response) {
// Cache miss: Fetch the asset from the origin
console.log(`Cache miss for: ${cacheKey.url}. Fetching from origin...`);
response = await fetch(request);

// Wrap the origin response for caching
response = new Response(response.body, response);

// Set Cache-Control headers to define the TTL
response.headers.set(
"Cache-Control",
`s-maxage=${CACHE_DURATION_SECONDS}`,
);
response.headers.set("x-snippets-cache", "stored");

// Store the response in the cache
await cache.put(cacheKey, response.clone());
} else {
// Cache hit: Return the cached response
console.log(`Cache hit for: ${cacheKey.url}.`);
response = new Response(response.body, response);
response.headers.set("x-snippets-cache", "hit");

// Optionally check if the cache should expire based on age
const ageHeader = response.headers.get("Age");
if (ageHeader && parseInt(ageHeader, 10) > CACHE_DURATION_SECONDS) {
console.log(
`Cache expired for: ${cacheKey.url}. Deleting cached response...`,
);
await cache.delete(cacheKey);
response.headers.set("x-snippets-cache", "deleted");
}
}

// Return the response to the client
return response;
},
};

/**
Expand All @@ -73,28 +75,30 @@ export default {
* @returns {Request} - A valid cache key based on the URL
*/
function createCacheKey(request) {
const url = new URL(request.url); // Use the request's base URL
const cacheKey = new URL(url.origin); // Start with the origin (scheme + hostname)

// Optionally include the path
if (USE_PATH) {
cacheKey.pathname = url.pathname;
}

// Optionally include the query string
if (USE_QUERY_STRING) {
cacheKey.search = url.search;
}

// Optionally include specific headers
if (INCLUDE_HEADERS.length > 0) {
const headerParts = INCLUDE_HEADERS.map(header => `${header}=${request.headers.get(header) || ""}`).join("&");
cacheKey.searchParams.append("headers", headerParts);
}

// Return the constructed URL as the cache key
return new Request(cacheKey.toString(), {
method: "GET"
});
const url = new URL(request.url); // Use the request's base URL
const cacheKey = new URL(url.origin); // Start with the origin (scheme + hostname)

// Optionally include the path
if (USE_PATH) {
cacheKey.pathname = url.pathname;
}

// Optionally include the query string
if (USE_QUERY_STRING) {
cacheKey.search = url.search;
}

// Optionally include specific headers
if (INCLUDE_HEADERS.length > 0) {
const headerParts = INCLUDE_HEADERS.map(
(header) => `${header}=${request.headers.get(header) || ""}`,
).join("&");
cacheKey.searchParams.append("headers", headerParts);
}

// Return the constructed URL as the cache key
return new Request(cacheKey.toString(), {
method: "GET",
});
}
```
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
---

summary: Send debugging information in an errored response to a logging service.
goal:
tags:
- Logging
operation:
- Response modification
products:
- Snippets
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
---

summary: Adjust [Cross-Origin Resource Sharing
(CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) headers and
handle preflight requests.
goal:
- Manage headers
operation:
tags:
- Headers
- Request modification
- Response modification
products:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
---

summary: Modify the fetch request to follow redirects from the origin, ensuring the client receives the final response.
goal:
- Routing
operation:
- Redirect
tags:
- Redirects
products:
- Snippets
pcx_content_type: example
Expand Down
40 changes: 19 additions & 21 deletions src/content/docs/rules/snippets/examples/hex-timestamp.mdx
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
---

summary: Add a custom header to requests sent to the origin server with the current timestamp in hexadecimal format.
goal:
- Manage headers
operation:
tags:
- Headers
- Request modification
products:
- Snippets
Expand All @@ -14,26 +12,26 @@ description: Add a custom header to requests sent to the origin server with the

```js
export default {
async fetch(request) {
// Get the current timestamp
const timestamp = Date.now();
async fetch(request) {
// Get the current timestamp
const timestamp = Date.now();

// Convert the timestamp to hexadecimal format
const hexTimestamp = timestamp.toString(16);
// Convert the timestamp to hexadecimal format
const hexTimestamp = timestamp.toString(16);

// Clone the request and add the custom header
const modifiedRequest = new Request(request, {
headers: new Headers(request.headers)
});
modifiedRequest.headers.set("X-Hex-Timestamp", hexTimestamp);
// Clone the request and add the custom header
const modifiedRequest = new Request(request, {
headers: new Headers(request.headers),
});
modifiedRequest.headers.set("X-Hex-Timestamp", hexTimestamp);

// Log the custom header for debugging
console.log(`X-Hex-Timestamp: ${hexTimestamp}`);
// Log the custom header for debugging
console.log(`X-Hex-Timestamp: ${hexTimestamp}`);

// Pass the modified request to the origin
const response = await fetch(modifiedRequest);
// Pass the modified request to the origin
const response = await fetch(modifiedRequest);

return response;
},
return response;
},
};
```
```
3 changes: 1 addition & 2 deletions src/content/docs/rules/snippets/examples/index.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
---

hideChildren: true
pcx_content_type: navigation
title: Examples
Expand All @@ -15,6 +14,6 @@ Refer to [How it works](/rules/snippets/how-it-works/) and [Create a snippet in

<ResourcesBySelector
directory="rules/snippets/examples"
filterables={["goal", "operation"]}
filterables={["tags"]}
types={["example"]}
/>
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
---

summary: Extract the JWT token from a header, decode it, and implement
validation checks to verify it.
goal:
tags:
- Authentication
operation:
- Request modification
products:
- Snippets
Expand Down
Loading
Loading