Integrating Turnstile with the Cloudflare WAF to challenge fetch requests

This post details the integration of Cloudflare Turnstile with the Cloudflare Web Application Firewall (WAF) to enable the challenging of browser-initiated API calls (fetch requests). Previously, fetch requests that were challenged by the WAF would fail because the browser could not render the HTML required to solve the challenge. This integration introduces "Turnstile Pre-Clearance mode," which allows Turnstile to issue a `cf_clearance` cookie for the domain it's embedded on. This cookie enables WAF rules to allow subsequent fetch requests to pass through without further challenges after the user has completed a Turnstile challenge on the page. The post provides a practical example of implementing this by overriding the `fetch()` function to invoke Turnstile when a `cf-mitigated` header indicates a challenge is required, and then replaying the request with the obtained `cf_clearance` cookie.
More from the Website Security & Threat Management trail
- We tested our own WAF with frontier AI models. Here’s what we found
- When scanners miss the attack: how Cloudflare Client-Side Security protects storefronts
- Introducing automatic remediation policies with Cloudflare CASB
- Introducing context-aware vulnerability discovery and remediation with Cloudflare Managed Defense and OpenAI Daybreak Models
- Introducing Adaptive Intelligence: undermining the economics of every bot attack