Skip to content

Commit 61b3e71

Browse files
authored
Update code from service worker to module worker format (#17905)
1 parent c26b2d7 commit 61b3e71

File tree

4 files changed

+76
-97
lines changed

4 files changed

+76
-97
lines changed
Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
---
22
pcx_content_type: how-to
33
title: Delay action
4-
54
---
65

76
Customers with a Bot Management and a [Workers](/workers/) subscription can use the template below to introduce a delay to requests that are likely from bots.
@@ -14,26 +13,22 @@ const PATH_START = '/exampleURI';
1413
const DELAY_FROM = 5; // in seconds
1514
const DELAY_TO = 10; // in seconds
1615

17-
addEventListener('fetch', event => {
18-
event.respondWith(handleRequest(event.request))
19-
})
16+
export default {
17+
async fetch(request, env, ctx): Promise<Response> {
18+
const url = new URL(request.url);
19+
const botScore = request.cf.botManagement.score
2020

21-
async function handleRequest(request) {
22-
let url = new URL(request.url);
23-
let botScore = request.cf.botManagement.score
21+
if (url.pathname.startsWith(PATH_START) && botScore < 30) {
22+
// Random delay between DELAY_FROM and DELAY_TO seconds
23+
const delay = Math.floor(Math.random() * (DELAY_TO - DELAY_FROM + 1)) + DELAY_FROM;
24+
await new Promise(resolve => setTimeout(resolve, delay * 1000));
2425

25-
26-
if (url.pathname.startsWith(PATH_START) && botScore < 30) {
27-
// Random delay between DELAY_FROM and DELAY_TO seconds
28-
const delay = Math.floor(Math.random() * (DELAY_TO - DELAY_FROM + 1)) + DELAY_FROM;
29-
await new Promise(resolve => setTimeout(resolve, delay * 1000));
26+
// Fetch the original request
27+
return fetch(request);
28+
}
3029

31-
// Fetch the original request
32-
return fetch(request);
33-
}
34-
else {
3530
// Fetch the original request without delay
3631
return fetch(request);
37-
}
38-
}
32+
},
33+
} satisfies ExportedHandler<Env>;
3934
```

src/content/docs/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata.mdx

Lines changed: 41 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,26 @@ sidebar:
55
order: 5
66
head: []
77
description: Configure per-hostname settings such as URL rewriting and custom headers.
8-
98
---
109

11-
import { Render } from "~/components"
10+
import { Render } from "~/components";
1211

1312
You may wish to configure per-hostname (customer) settings beyond the scale of Page Rules or Rate Limiting, which have a maximum of 125 rules each.
1413

1514
To do this, you will first need to reach out to your account team to enable access to Custom Metadata. After configuring custom metadata, you can use it in the following ways:
1615

17-
* Read the metadata JSON from [Cloudflare Workers](/workers/) (requires access to Workers) to define per-hostname behavior.
18-
* Use custom metadata values in [rule expressions](/ruleset-engine/rules-language/expressions/) of different Cloudflare security products to define the rule scope.
16+
- Read the metadata JSON from [Cloudflare Workers](/workers/) (requires access to Workers) to define per-hostname behavior.
17+
- Use custom metadata values in [rule expressions](/ruleset-engine/rules-language/expressions/) of different Cloudflare security products to define the rule scope.
1918

2019
<Render file="ssl-for-saas-plan-limitation" />
2120

22-
***
21+
---
2322

2423
## Examples
2524

26-
* Per-customer URL rewriting — for example, customers 1-10,000 fetch assets from server A, 10,001-20,000 from server B, etc.
27-
* Adding custom headers — for example, `X-Customer-ID: $number` based on the metadata you provided
28-
* Setting HTTP Strict Transport Security (“HSTS”) headers on a per-customer basis
25+
- Per-customer URL rewriting — for example, customers 1-10,000 fetch assets from server A, 10,001-20,000 from server B, etc.
26+
- Adding custom headers — for example, `X-Customer-ID: $number` based on the metadata you provided
27+
- Setting HTTP Strict Transport Security (“HSTS”) headers on a per-customer basis
2928

3029
Please speak with your Solutions Engineer to discuss additional logic and requirements.
3130

@@ -54,32 +53,32 @@ curl --request PATCH \
5453

5554
Changes to metadata will propagate across Cloudflare’s edge within 30 seconds.
5655

57-
***
56+
---
5857

5958
## Accessing custom metadata from a Cloudflare Worker
6059

6160
The metadata object will be accessible on each request using the `request.cf.hostMetadata` property. You can then read the data, and customize any behavior on it using the Worker.
6261

63-
In the example below we will use the user\_id in the Worker that was submitted using the API call above `"custom_metadata":{"customer_id":"12345","redirect_to_https": true,"security_tag":"low"}`, and set a request header to send the `customer_id` to the origin:
62+
In the example below we will use the user_id in the Worker that was submitted using the API call above `"custom_metadata":{"customer_id":"12345","redirect_to_https": true,"security_tag":"low"}`, and set a request header to send the `customer_id` to the origin:
6463

6564
```js
66-
addEventListener('fetch', event => {
67-
event.respondWith(fetchAndAddHeader(event.request));
68-
});
69-
/**
70-
* Fetch and add a X-Customer-Id header to the origin based on hostname
71-
* @param {Request} request
72-
*/ async function fetchAndAddHeader(request) {
73-
let customer_id = request.cf.hostMetadata.customer_id;
74-
let newHeaders = new Headers(request.headers);
75-
newHeaders.append('X-Customer-Id', customer_id);
76-
let init = {
77-
headers: newHeaders,
78-
method: request.method,
79-
};
80-
let response = await fetch(request.url, init);
81-
return response;
82-
}
65+
export default {
66+
/**
67+
* Fetch and add a X-Customer-Id header to the origin based on hostname
68+
* @param {Request} request
69+
*/
70+
async fetch(request, env, ctx): Promise<Response> {
71+
const customer_id = request.cf.hostMetadata.customer_id;
72+
const newHeaders = new Headers(request.headers);
73+
newHeaders.append('X-Customer-Id', customer_id);
74+
75+
const init = {
76+
headers: newHeaders,
77+
method: request.method,
78+
};
79+
return fetch(request.url, init);
80+
},
81+
} satisfies ExportedHandler<Env>;
8382
```
8483

8584
## Accessing custom metadata in a rule expression
@@ -92,35 +91,35 @@ The following rule expression defines that there will be a rule match if the `se
9291
lookup_json_string(cf.hostname.metadata, "security_tag") eq "low"
9392
```
9493

95-
***
94+
---
9695

9796
## Best practices
9897

99-
* Ensure that the JSON schema used is fixed: changes to the schema without corresponding Cloudflare Workers changes will potentially break websites, or fall back to any defined “default” behavior
100-
* Prefer a flat JSON structure
101-
* Use string keys in snake\_case (rather than camelCase or PascalCase)
102-
* Use proper booleans (true/false rather than `true` or `1` or `0`)
103-
* Use numbers to represent integers instead of strings (`1` or `2` instead of `"1"` or `"2"`)
104-
* Define fallback behaviour in the non-presence of metadata
105-
* Define fallback behaviour if a key or value in the metadata are unknown
98+
- Ensure that the JSON schema used is fixed: changes to the schema without corresponding Cloudflare Workers changes will potentially break websites, or fall back to any defined “default” behavior
99+
- Prefer a flat JSON structure
100+
- Use string keys in snake_case (rather than camelCase or PascalCase)
101+
- Use proper booleans (true/false rather than `true` or `1` or `0`)
102+
- Use numbers to represent integers instead of strings (`1` or `2` instead of `"1"` or `"2"`)
103+
- Define fallback behaviour in the non-presence of metadata
104+
- Define fallback behaviour if a key or value in the metadata are unknown
106105

107106
General guidance is to follow [Google’s JSON Style guide](https://google.github.io/styleguide/jsoncstyleguide.xml) where appropriate.
108107

109-
***
108+
---
110109

111110
## Limitations
112111

113112
There are some limitations to the metadata that can be provided to Cloudflare:
114113

115-
* It must be valid JSON.
116-
* Any origin resolution — for example, directing requests for a given hostname to a specific backend — must be provided as a hostname that exists within Cloudflare’s DNS (even for non-authoritative setups). Providing an IP address directly will cause requests to error.
117-
* The total payload must not exceed 4 KB.
118-
* It requires a Cloudflare Worker that knows how to process the schema and trigger logic based on the contents.
119-
* Custom metadata cannot be set on custom hostnames that contain wildcards.
114+
- It must be valid JSON.
115+
- Any origin resolution — for example, directing requests for a given hostname to a specific backend — must be provided as a hostname that exists within Cloudflare’s DNS (even for non-authoritative setups). Providing an IP address directly will cause requests to error.
116+
- The total payload must not exceed 4 KB.
117+
- It requires a Cloudflare Worker that knows how to process the schema and trigger logic based on the contents.
118+
- Custom metadata cannot be set on custom hostnames that contain wildcards.
120119

121120
:::note
122121

123-
Be careful when modifying the schema. Adding, removing, or changing keys and possible values may cause the Cloudflare Worker to either ignore the data or return an error for requests that trigger it.
122+
Be careful when modifying the schema. Adding, removing, or changing keys and possible values may cause the Cloudflare Worker to either ignore the data or return an error for requests that trigger it.
124123
:::
125124

126125
### Terraform support

src/content/docs/cloudflare-one/tutorials/access-workers.mdx

Lines changed: 13 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -10,27 +10,20 @@ products:
1010
- Access
1111
languages:
1212
- JavaScript
13-
1413
---
1514

16-
17-
1815
This tutorial covers how to use a [Cloudflare Worker](/workers/) to add custom HTTP headers to traffic, and how to send those custom headers to your origin services protected by [Cloudflare Access](/cloudflare-one/policies/access/).
1916

2017
Some applications and networking implementations require specific custom headers to be passed to the origin, which can be difficult to implement for traffic moving through a Zero Trust proxy. You can configure a Worker to send the [user authorization headers](/cloudflare-one/identity/authorization-cookie/) required by Access.
2118

22-
***
19+
---
2320

2421
## Before you begin
2522

26-
27-
28-
* Secure your origin server with Cloudflare Access
29-
23+
- Secure your origin server with Cloudflare Access
3024

3125
## Before you begin
3226

33-
3427
1. Log in to the [Cloudflare dashboard](https://dash.cloudflare.com/) and select your account. Go to **Workers & Pages**.
3528

3629
2. If this is your first Worker, select **Create Worker**. Otherwise, select **Create application**, then select **Create Worker**.
@@ -41,30 +34,26 @@ Some applications and networking implementations require specific custom headers
4134

4235
5. Input the following Worker:
4336

44-
```javascript title="Worker with custom HTTP headers"
45-
addEventListener("fetch", event => {
46-
event.respondWith(handleRequest(event.request))
47-
})
37+
```js title="Worker with custom HTTP headers"
38+
export default {
39+
async fetch(request, env, ctx): Promise<Response> {
40+
const { headers } = request;
41+
const cfaccessemail = headers.get("cf-access-authenticated-user-email");
4842

49-
async function handleRequest(request) {
50-
const { headers } = request;
51-
const cfaccessemail = headers.get("cf-access-authenticated-user-email");
52-
const requestWithID = new Request(request);
53-
requestWithID.headers.set('company-user-id', cfaccessemail);
43+
const requestWithID = new Request(request);
44+
requestWithID.headers.set('company-user-id', cfaccessemail);
5445

55-
return await fetch(requestWithID);
56-
}
57-
58-
```
46+
return fetch(requestWithID);
47+
},
48+
} satisfies ExportedHandler<Env>;
49+
```
5950

6051
6. Select **Save and deploy**.
6152

6253
Your Worker is now ready to send custom headers to your Access-protected origin services.
6354

6455
## Apply the Worker to your hostname
6556

66-
67-
6857
1. Select the Worker you created, then go to **Triggers**.
6958
2. In **Routes**, select **Add route**.
7059
3. Enter the hostname and zone for your origin, then select **Add route**.
@@ -79,6 +68,3 @@ The Worker will now insert a custom header into requests that match the defined
7968
"Company-User-Id": "[email protected]",
8069
"Connection": "keep-alive"
8170
```
82-
83-
84-

src/content/docs/images/manage-images/serve-images/serve-private-images.mdx

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ pcx_content_type: how-to
33
title: Serve private images
44
sidebar:
55
order: 23
6-
76
---
87

98
You can serve private images by using signed URL tokens. When an image requires a signed URL, the image cannot be accessed without a token unless it is being requested for a variant set to always allow public access.
@@ -14,10 +13,8 @@ You can serve private images by using signed URL tokens. When an image requires
1413

1514
:::note
1615

17-
1816
Private images do not currently support custom paths.
1917

20-
2118
:::
2219

2320
The example below uses a Worker that takes in a regular URL without a signed token and returns a tokenized URL that expires after one day. You can, however, set this expiration period to whatever you need, by changing the const `EXPIRATION` value.
@@ -62,11 +59,13 @@ async function generateSignedUrl(url) {
6259
return new Response(url);
6360
}
6461

65-
addEventListener('fetch', event => {
66-
const url = new URL(event.request.url);
67-
const imageDeliveryURL = new URL(
68-
url.pathname.slice(1).replace('https:/imagedelivery.net', 'https://imagedelivery.net')
69-
);
70-
event.respondWith(generateSignedUrl(imageDeliveryURL));
71-
});
62+
export default {
63+
async fetch(request, env, ctx): Promise<Response> {
64+
const url = new URL(event.request.url);
65+
const imageDeliveryURL = new URL(
66+
url.pathname.slice(1).replace('https:/imagedelivery.net', 'https://imagedelivery.net')
67+
);
68+
return generateSignedUrl(imageDeliveryURL);
69+
},
70+
} satisfies ExportedHandler<Env>;
7271
```

0 commit comments

Comments
 (0)