Sometimes you may want to show Turnstile only for certain requests. For example, you might let an approved agent use a form without completing Turnstile. Here are two ways to conditionally render it: use a Transform Rule to pass request information to your site in a header, or use HTMLRewriter in a Worker to remove the widget from the response.
Turnstile runs in the browser and gives your server a token to check. If you want someone to complete an action without Turnstile, do not show them the widget and do not require a token when they complete that action. Keep both checks for everyone else.
This tutorial shows two ways to leave the widget off the page. In Example 1, a Request Header Transform Rule sends request information to your site in a header. In Example 2, HTMLRewriter removes the widget using Bot Management metadata from the Worker request. Each example also covers the server-side token check.
A Request Header Transform Rule can add or remove a header before a request reaches your website. This example uses two rules: the first removes any visitor-supplied x-turnstile-bypass header, and the second sets it to true for requests with detection IDs you choose.
Configure your website to leave Turnstile off the page and accept submissions without a token when it receives x-turnstile-bypass: true. Other visitors still get Turnstile. This example requires Enterprise Bot Management to identify the selected agents.
The rule evaluates each incoming request. It adds the header to eligible page requests and form submissions separately.
-
Find the Bot Detection ID or IDs for the agent in Botbase.
-
In the Cloudflare dashboard, go to Rules > Overview.
Go to Overview ↗ -
Create a rule that removes any incoming bypass header. This prevents visitors from forging the header to bypass Turnstile.
- Select Create rule > Request Header Transform Rule.
- Under If incoming requests match…, select Custom filter expression.
- Under When incoming requests match…, enter an expression for every hostname where your application trusts this header. For example:
http.host eq "example.com". - Under Then… > Modify request header, set Operation to Remove and Header name to
x-turnstile-bypass. - Deploy the rule.
-
Create a second rule that sets the header for approved detection IDs:
-
Select Create rule > Request Header Transform Rule.
-
Under If incoming requests match…, select Custom filter expression.
-
Under When incoming requests match…, enter an expression that matches your hostname and the detection ID or IDs you want to allow. For example, replace the hostname and IDs in this expression:
http.host eq "example.com" and any(cf.bot_management.detection_ids[*] in {12345 6789}) -
Under Then… > Modify request header, set Operation to Set static, Header name to
x-turnstile-bypass, and Value totrue. This setsx-turnstile-bypass: trueon matching requests so your site can skip Turnstile for them. -
Set this rule's priority after the removal rule, then select Deploy. Ensure no later rule changes this header.
-
At your origin, check for exactly one x-turnstile-bypass: true header. Confirm the hostname and operation. Omit Turnstile on matching page requests, and skip Siteverify on matching submissions. Render and validate normally for other requests. The request header is not available to browser JavaScript. If browser code renders the widget, pass the rendering decision from your server to the page.
In your form handler, check the header again. If it has exactly one value of true, accept the form without a Turnstile token. Otherwise, require a token and verify it with Siteverify. Keep your other form checks unchanged.
For example, in an Express form handler with body parsing configured:
async function handlePost(req, res) {
// Read every value so duplicate headers cannot grant an exception.
const bypassValues = [];
for (let i = 0; i < req.rawHeaders.length; i += 2) {
if (req.rawHeaders[i].toLowerCase() === "x-turnstile-bypass") {
bypassValues.push(req.rawHeaders[i + 1]);
}
}
const skipTurnstile =
req.method === "POST" &&
req.hostname === "example.com" &&
req.path === "/submit" &&
bypassValues.length === 1 &&
bypassValues[0] === "true";
if (!skipTurnstile) {
const token = req.body["cf-turnstile-response"];
const result = token && (await verifyTurnstile(token));
if (!result?.success) {
return res.status(400).send("Turnstile verification failed");
}
}
// Continue processing the form as usual.
}Replace the example hostname and path with yours. Use your existing Siteverify call for verifyTurnstile().
If clients can reach your origin directly, they can send this header themselves. Restrict origin access through Cloudflare, for example with Cloudflare Tunnel or authenticated origin connections. Reject duplicate or comma-joined header values.
If you cache the form page, use separate cache entries for responses with and without Turnstile. Otherwise, do not cache the page.
Test an approved agent, an ordinary visitor, a forged bypass header, and a submission that does not qualify. Ordinary visitors and ineligible submissions must provide valid tokens.
This example modifies the existing Turnstile demo ↗︎ to remove Turnstile elements from the HTML response. It checks Bot Management detection IDs on each request, including form submissions. A standard form POST is a new request and does not inherit headers from the page request. This approach requires Enterprise Bot Management.
Replace the example IDs, hostname, and paths with your approved values. Find detection IDs in Botbase.
const approvedDetectionIds = new Set([12345, 6789]);
function isApprovedAgent(request) {
const url = new URL(request.url);
const isTurnstilePage =
request.method === "GET" && ["/", "/explicit"].includes(url.pathname);
const isFormSubmission =
request.method === "POST" && url.pathname === "/handler";
if (
url.hostname !== "example.com" ||
(!isTurnstilePage && !isFormSubmission)
) {
return false;
}
const detectionIds = request.cf?.botManagement?.detectionIds ?? [];
return detectionIds.some((id) => approvedDetectionIds.has(id));
}
function rewriteTurnstilePage(request, response) {
if (request.method !== "GET" || !isApprovedAgent(request)) {
return response;
}
class RemoveHandler {
element(element) {
element.remove();
}
}
return (
new HTMLRewriter()
// Match the script URL with or without query parameters.
.on(
'script[src^="https://challenges.cloudflare.com/turnstile/v0/api.js"]',
new RemoveHandler(),
)
// Remove the explicit-render callback and widget containers.
.on("#turnstile-render", new RemoveHandler())
.on(".cf-turnstile", new RemoveHandler())
.on("#myWidget", new RemoveHandler())
.transform(response)
);
}type BotManagedRequest = Request<unknown, IncomingRequestCfProperties>;
const approvedDetectionIds = new Set<number>([12345, 6789]);
function isApprovedAgent(request: BotManagedRequest): boolean {
const url = new URL(request.url);
const isTurnstilePage =
request.method === "GET" && ["/", "/explicit"].includes(url.pathname);
const isFormSubmission =
request.method === "POST" && url.pathname === "/handler";
if (
url.hostname !== "example.com" ||
(!isTurnstilePage && !isFormSubmission)
) {
return false;
}
const detectionIds = request.cf?.botManagement?.detectionIds ?? [];
return detectionIds.some((id) => approvedDetectionIds.has(id));
}
function rewriteTurnstilePage(
request: BotManagedRequest,
response: Response,
): Response {
if (request.method !== "GET" || !isApprovedAgent(request)) {
return response;
}
class RemoveHandler {
element(element: Element) {
element.remove();
}
}
return (
new HTMLRewriter()
// Match the script URL with or without query parameters.
.on(
'script[src^="https://challenges.cloudflare.com/turnstile/v0/api.js"]',
new RemoveHandler(),
)
// Remove the explicit-render callback and widget containers.
.on("#turnstile-render", new RemoveHandler())
.on(".cf-turnstile", new RemoveHandler())
.on("#myWidget", new RemoveHandler())
.transform(response)
);
}In the demo's fetch() handler, pass each page response to rewriteTurnstilePage(request, response) before returning it.
In src/explicit.html, add an ID to the inline script that renders the widget:
-<script>
+<script id="turnstile-render">On each form submission, evaluate the detection IDs again. Skip only Siteverify for approved requests. Continue processing the form and running its other checks.
async function handlePost(request) {
const body = await request.formData();
if (!isApprovedAgent(request)) {
// Keep the existing token extraction and Siteverify check here.
const token = body.get("cf-turnstile-response");
}
// Continue with the demo's normal form processing and response.
}async function handlePost(request: BotManagedRequest) {
const body = await request.formData();
if (!isApprovedAgent(request)) {
// Keep the existing token extraction and Siteverify check here.
const token = body.get("cf-turnstile-response");
}
// Continue with the demo's normal form processing and response.
}If you cache the HTML response, use separate cache entries for eligible and other requests. Otherwise, do not cache the response.
Test the page request and form submission with an approved agent and an ordinary browser. Confirm that only approved requests omit the widget and skip Siteverify.