How to validate Turnstile with Playwright
Your website might be using Cloudflare Turnstile to protect it from spam and abuse. But when testing your web application end to end with tools such as Playwright, it can be tricky to validate it. In this quick guide, we'll show you how to validate Turnstile with Playwright.
NOTE: The goal of this guide is not to bypass Turnstile by simulating a human interaction. It's to validate the turnstile using the sandbox mode.
Why do we need to validate Turnstile when using the sandbox mode?
When using the sandbox mode, the captcha can take some time to load and validate. This can be fixed by simply waiting for a set amount of time but will likely slow down your tests and introduce some flakiness.
The best approach is to have a way to know for sure when the captcha is loaded and validated.
How to set up Turnstile in sandbox mode?
Cloudflare provides some tokens to use in testing environments. You can find them in the Cloudflare Turnstile documentation.
We are using the following combination as they guarantee a successful validation:
- Sitekey:
1x00000000000000000000AA - Secret key:
1x0000000000000000000000000000000AA
Validate Turnstile with Playwright
As you might have noticed, Turnstile uses a closed Shadow DOM. This complicates how we can validate it with Playwright. That being said, they do expose a hidden input that contains the response token. We will use this to know when the captcha is loaded and validated.
await expect(
page.locator(`input[name="cf-turnstile-response"][type="hidden"]`)
).toHaveValue("XXXX.DUMMY.TOKEN.XXXX");
It's fine to keep the XXXX.DUMMY.TOKEN.XXXX here as long as you use the provided sandbox token in your frontend and in the backend that validates it.
Thank you for reading! If you have any questions or feedback, please feel free to contact us at hi@davette.ca.