Skip to content

Commit 9d9eba7

Browse files
vicbharshil1712
authored andcommitted
Update code from service worker to module worker format (#18139)
1 parent 68b9b4d commit 9d9eba7

File tree

7 files changed

+390
-379
lines changed

7 files changed

+390
-379
lines changed

src/content/docs/automatic-platform-optimization/reference/subdomain-subdirectories.mdx

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ title: Subdomains and subdirectories
33
pcx_content_type: how-to
44
sidebar:
55
order: 14
6-
76
---
87

98
## Run APO on a subdomain
@@ -36,24 +35,19 @@ If you choose to run APO only on a subdirectory, the rest of the domain should b
3635
The `cf-edge-cache: no-cache` instructs the APO service to bypass caching for non-WordPress parts of the site. You can implement this option with Cloudflare Workers using the example below.
3736

3837
```js
39-
addEventListener('fetch', event => {
40-
event.respondWith(handleRequest(event.request));
41-
});
42-
43-
async function handleRequest(request) {
44-
/**
45-
* Response properties are immutable. To change them, construct a new
46-
* Response object. Response headers can be modified through the headers `set` method.
47-
*/
48-
const originalResponse = await fetch(request);
38+
export default {
39+
async fetch(request, env, ctx) {
40+
const originalResponse = await fetch(request);
4941

50-
let response = new Response(originalResponse.body, originalResponse);
42+
// Response properties are immutable. To change them, construct a new Response object.
43+
const response = new Response(originalResponse.body, originalResponse);
5144

52-
// Add a header using set method
53-
response.headers.set('cf-edge-cache', 'no-cache');
45+
// Response headers can be modified through the headers `set` method.
46+
response.headers.set("cf-edge-cache", "no-cache");
5447

55-
return response;
56-
}
48+
return response;
49+
},
50+
};
5751
```
5852

5953
### Use Cache Rules

src/content/docs/images/transform-images/control-origin-access.mdx

Lines changed: 74 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,20 @@ pcx_content_type: reference
33
title: Control origin access
44
sidebar:
55
order: 24
6-
76
---
87

98
You can serve resized images without giving access to the original image. Images can be hosted on another server outside of your zone, and the true source of the image can be entirely hidden. The origin server may require authentication to disclose the original image, without needing visitors to be aware of it. Access to the full-size image may be prevented by making it impossible to manipulate resizing parameters.
109

1110
All these behaviors are completely customizable, because they are handled by custom code of a script running [on the edge in a Cloudflare Worker](/images/transform-images/transform-via-workers/).
1211

1312
```js
14-
addEventListener("fetch", event => {
15-
event.respondWith(handleRequest(event.request))
16-
})
17-
18-
async function handleRequest(request) {
19-
// Here you can compute arbitrary imageURL and
20-
// resizingOptions from any request data ...
21-
return fetch(imageURL, {cf:{image:resizingOptions}})
22-
}
13+
export default {
14+
async fetch(request, env, ctx) {
15+
// Here you can compute arbitrary imageURL and
16+
// resizingOptions from any request data ...
17+
return fetch(imageURL, { cf: { image: resizingOptions } });
18+
},
19+
};
2320
```
2421

2522
This code will be run for every request, but the source code will not be accessible to website visitors. This allows the code to perform security checks and contain secrets required to access the images in a controlled manner.
@@ -28,36 +25,39 @@ The examples below are only suggestions, and do not have to be followed exactly.
2825

2926
:::caution[Warning]
3027

31-
3228
When testing image transformations, make sure you deploy the script and test it from a regular web browser window. The preview in the dashboard does not simulate transformations.
3329

34-
3530
:::
3631

3732
## Hiding the image server
3833

3934
```js
40-
async function handleRequest(request) {
41-
const resizingOptions = {/* resizing options will be demonstrated in the next example */}
42-
43-
const hiddenImageOrigin = "https://secret.example.com/hidden-directory"
44-
const requestURL = new URL(request.url)
45-
// Append the request path such as "/assets/image1.jpg" to the hiddenImageOrigin.
46-
// You could also process the path to add or remove directories, modify filenames, etc.
47-
const imageURL = hiddenImageOrigin + requestURL.path
48-
// This will fetch image from the given URL, but to the website's visitors this
49-
// will appear as a response to the original request. Visitor’s browser will
50-
// not see this URL.
51-
return fetch(imageURL, {cf:{image:resizingOptions}})
52-
}
35+
export default {
36+
async fetch(request, env, ctx) {
37+
const resizingOptions = {
38+
/* resizing options will be demonstrated in the next example */
39+
};
40+
41+
const hiddenImageOrigin = "https://secret.example.com/hidden-directory";
42+
const requestURL = new URL(request.url);
43+
// Append the request path such as "/assets/image1.jpg" to the hiddenImageOrigin.
44+
// You could also process the path to add or remove directories, modify filenames, etc.
45+
const imageURL = hiddenImageOrigin + requestURL.path;
46+
// This will fetch image from the given URL, but to the website's visitors this
47+
// will appear as a response to the original request. Visitor’s browser will
48+
// not see this URL.
49+
return fetch(imageURL, { cf: { image: resizingOptions } });
50+
},
51+
};
5352
```
5453

5554
## Preventing access to full-size images
5655

5756
On top of protecting the original image URL, you can also validate that only certain image sizes are allowed:
5857

5958
```js
60-
async function handleRequest(request) {
59+
export default {
60+
async fetch(request, env, ctx) {
6161
const imageURL =// detail omitted in this example, see the previous example
6262

6363
const requestURL = new URL(request.url)
@@ -70,38 +70,46 @@ async function handleRequest(request) {
7070
throw Error("We don’t allow viewing images larger than 1000 pixels wide")
7171
}
7272
return fetch(imageURL, {cf:{image:resizingOptions}})
73-
}
73+
},};
7474
```
7575

7676
## Avoid image dimensions in URLs
7777

7878
You do not have to include actual pixel dimensions in the URL. You can embed sizes in the Worker script, and select the size in some other way — for example, by naming a preset in the URL:
7979

8080
```js
81-
async function handleRequest(request) {
82-
const requestURL = new URL(request.url)
83-
const resizingOptions = {}
84-
85-
// The regex selects the first path component after the "images"
86-
// prefix, and the rest of the path (e.g. "/images/first/rest")
87-
const match = requestURL.path.match(/images\/([^/]+)\/(.+)/)
88-
89-
// You can require the first path component to be one of the
90-
// predefined sizes only, and set actual dimensions accordingly.
91-
switch (match && match[1]) {
92-
case "small": resizingOptions.width = 300; break;
93-
case "medium": resizingOptions.width = 600; break;
94-
case "large": resizingOptions.width = 900; break;
95-
default:
96-
throw Error("invalid size");
97-
}
98-
99-
// The remainder of the path may be used to locate the original
100-
// image, e.g. here "/images/small/image1.jpg" would map to
101-
// "https://storage.example.com/bucket/image1.jpg" resized to 300px.
102-
const imageURL = "https://storage.example.com/bucket/" + match[2]
103-
return fetch(imageURL, {cf:{image:resizingOptions}})
104-
}
81+
export default {
82+
async fetch(request, env, ctx) {
83+
const requestURL = new URL(request.url);
84+
const resizingOptions = {};
85+
86+
// The regex selects the first path component after the "images"
87+
// prefix, and the rest of the path (e.g. "/images/first/rest")
88+
const match = requestURL.path.match(/images\/([^/]+)\/(.+)/);
89+
90+
// You can require the first path component to be one of the
91+
// predefined sizes only, and set actual dimensions accordingly.
92+
switch (match && match[1]) {
93+
case "small":
94+
resizingOptions.width = 300;
95+
break;
96+
case "medium":
97+
resizingOptions.width = 600;
98+
break;
99+
case "large":
100+
resizingOptions.width = 900;
101+
break;
102+
default:
103+
throw Error("invalid size");
104+
}
105+
106+
// The remainder of the path may be used to locate the original
107+
// image, e.g. here "/images/small/image1.jpg" would map to
108+
// "https://storage.example.com/bucket/image1.jpg" resized to 300px.
109+
const imageURL = "https://storage.example.com/bucket/" + match[2];
110+
return fetch(imageURL, { cf: { image: resizingOptions } });
111+
},
112+
};
105113
```
106114

107115
## Authenticated origin
@@ -111,7 +119,7 @@ Cloudflare image transformations cache resized images to aid performance. Images
111119
```js null {9}
112120
// generate signed headers (application specific)
113121
const signedHeaders = generatedSignedHeaders();
114-
122+
115123
fetch(private_url, {
116124
headers: signedHeaders
117125
cf: {
@@ -125,20 +133,20 @@ fetch(private_url, {
125133

126134
When using this code, the following headers are passed through to the origin, and allow your request to be successful:
127135

128-
* `Authorization`
129-
* `Cookie`
130-
* `x-amz-content-sha256`
131-
* `x-amz-date`
132-
* `x-ms-date`
133-
* `x-ms-version`
134-
* `x-sa-date`
135-
* `cf-access-client-id`
136-
* `cf-access-client-secret`
136+
- `Authorization`
137+
- `Cookie`
138+
- `x-amz-content-sha256`
139+
- `x-amz-date`
140+
- `x-ms-date`
141+
- `x-ms-version`
142+
- `x-sa-date`
143+
- `cf-access-client-id`
144+
- `cf-access-client-secret`
137145

138146
For more information, refer to:
139147

140-
* [AWS docs](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)
141-
* [Azure docs](https://docs.microsoft.com/en-us/rest/api/storageservices/List-Containers2#request-headers)
142-
* [Google Cloud docs](https://cloud.google.com/storage/docs/aws-simple-migration)
143-
* [Cloudflare Zero Trust docs](/cloudflare-one/identity/service-tokens/)
144-
* [SecureAuth docs](https://docs.secureauth.com/2104/en/authentication-api-guide.html)
148+
- [AWS docs](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)
149+
- [Azure docs](https://docs.microsoft.com/en-us/rest/api/storageservices/List-Containers2#request-headers)
150+
- [Google Cloud docs](https://cloud.google.com/storage/docs/aws-simple-migration)
151+
- [Cloudflare Zero Trust docs](/cloudflare-one/identity/service-tokens/)
152+
- [SecureAuth docs](https://docs.secureauth.com/2104/en/authentication-api-guide.html)

0 commit comments

Comments
 (0)