Skip to content

Commit 386420a

Browse files
worengakodster28
authored andcommitted
PCX-14407: Incorporate Feedback to HTML Rewriter (#19515)
1 parent e86d7f6 commit 386420a

File tree

1 file changed

+29
-18
lines changed

1 file changed

+29
-18
lines changed

src/content/docs/workers/examples/turnstile-html-rewriter.mdx

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ import { TabItem, Tabs } from "~/components";
2323
```js
2424
export default {
2525
async fetch(request, env) {
26-
const SITE_KEY = env.SITE_KEY
26+
const SITE_KEY = env.SITE_KEY; // The Turnstile Sitekey of your widget (pass as env or secret)
27+
const TURNSTILE_ATTR_NAME = 'your_id_to_replace'; // The id of the element to put a Turnstile widget in
2728
let res = await fetch(request)
2829

2930
// Instantiate the API to run on specific elements, for example, `head`, `div`
@@ -32,17 +33,15 @@ export default {
3233
// `.on` attaches the element handler and this allows you to match on element/attributes or to use the specific methods per the API
3334
.on('head', {
3435
element(element) {
35-
3636
// In this case, you are using `append` to add a new script to the `head` element
3737
element.append(`<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>`, { html: true });
3838
},
3939
})
4040
.on('div', {
4141
element(element) {
42-
43-
// You are using the `getAttribute` method here to retrieve the `id` or `class` of an element
44-
if (element.getAttribute('id') === <NAME_OF_ATTRIBUTE>) {
45-
element.append(`<div class="cf-turnstile" data-sitekey="${SITE_KEY}" data-theme="light"></div>`, { html: true });
42+
// Add a turnstile widget element into if an element with the id of TURNSTILE_ATTR_NAME is found
43+
if (element.getAttribute('id') === TURNSTILE_ATTR_NAME) {
44+
element.append(`<div class="cf-turnstile" data-sitekey="${SITE_KEY}"></div>`, { html: true });
4645
}
4746
},
4847
})
@@ -57,7 +56,9 @@ export default {
5756
```ts
5857
export default {
5958
async fetch(request, env): Promise<Response> {
60-
const SITE_KEY = env.SITE_KEY
59+
const SITE_KEY = env.SITE_KEY; // The Turnstile Sitekey of your widget (pass as env or secret)
60+
const TURNSTILE_ATTR_NAME = 'your_id_to_replace'; // The id of the element to put a Turnstile widget in
61+
6162
let res = await fetch(request)
6263

6364
// Instantiate the API to run on specific elements, for example, `head`, `div`
@@ -73,9 +74,8 @@ export default {
7374
})
7475
.on('div', {
7576
element(element) {
76-
77-
// You are using the `getAttribute` method here to retrieve the `id` or `class` of an element
78-
if (element.getAttribute('id') === <NAME_OF_ATTRIBUTE>) {
77+
// Add a turnstile widget element into if an element with the id of TURNSTILE_ATTR_NAME is found
78+
if (element.getAttribute('id') === TURNSTILE_ATTR_NAME) {
7979
element.append(`<div class="cf-turnstile" data-sitekey="${SITE_KEY}" data-theme="light"></div>`, { html: true });
8080
}
8181
},
@@ -94,6 +94,7 @@ from js import HTMLRewriter, fetch
9494

9595
async def on_fetch(request, env):
9696
site_key = env.SITE_KEY
97+
attr_name = env.TURNSTILE_ATTR_NAME
9798
res = await fetch(request)
9899

99100
class Append:
@@ -112,7 +113,7 @@ async def on_fetch(request, env):
112113

113114
# Instantiate the API to run on specific elements, for example, `head`, `div`
114115
head = create_proxy(Append())
115-
div = create_proxy(AppendOnID("NAME_OF_ATTRIBUTE"))
116+
div = create_proxy(AppendOnID(attr_name))
116117
new_res = HTMLRewriter.new().on("head", head).on("div", div).transform(res)
117118

118119
return new_res
@@ -128,7 +129,7 @@ This is only half the implementation for Turnstile. The corresponding token that
128129
<TabItem label="JavaScript" icon="seti:javascript">
129130

130131
```js
131-
async function handlePost(request) {
132+
async function handlePost(request, env) {
132133
const body = await request.formData();
133134
// Turnstile injects a token in `cf-turnstile-response`.
134135
const token = body.get('cf-turnstile-response');
@@ -137,10 +138,10 @@ async function handlePost(request) {
137138
// Validate the token by calling the `/siteverify` API.
138139
let formData = new FormData();
139140

140-
// `secret_key` here is set using Wrangler secrets
141-
formData.append('secret', secret_key);
141+
// `secret_key` here is the Turnstile Secret key, which should be set using Wrangler secrets
142+
formData.append('secret', env.SECRET_KEY);
142143
formData.append('response', token);
143-
formData.append('remoteip', ip);
144+
formData.append('remoteip', ip); //This is optional.
144145

145146
const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
146147
const result = await fetch(url, {
@@ -155,16 +156,26 @@ async function handlePost(request) {
155156
}
156157
// The Turnstile token was successfully validated. Proceed with your application logic.
157158
// Validate login, redirect user, etc.
158-
return await fetch(request)
159+
160+
// Clone the original request with a new body
161+
const newRequest = new Request(request, {
162+
body: request.body, // Reuse the body
163+
method: request.method,
164+
headers: request.headers
165+
});
166+
167+
return await fetch(newRequest);
159168
}
160169

161170
export default {
162171
async fetch(request, env) {
163-
const SITE_KEY = env.SITE_KEY
172+
const SITE_KEY = env.SITE_KEY; // The Turnstile Sitekey of your widget (pass as env or secret)
173+
const TURNSTILE_ATTR_NAME = 'your_id_to_replace'; // The id of the element to put a Turnstile widget in
174+
164175
let res = await fetch(request)
165176

166177
if (request.method === 'POST') {
167-
return handlePost(request)
178+
return handlePost(request, env)
168179
}
169180

170181
// Instantiate the API to run on specific elements, for example, `head`, `div`

0 commit comments

Comments
 (0)