Cloudflare Turnstile
What is Turnstile?
Turnstile is Cloudflare's CAPTCHA alternative that protects your site from automated spam and abuse.
It can be used to protect your login, registration, and contact forms, as well as any other page that requires user input.
You can learn more about Turnstile from the official docs (opens in a new tab).
How to use Turnstile?
Cloudstarter has built-in support for Turnstile. You can easily enable Turnstile for your project by following the steps below.
Prerequisites
Before you can use Turnstile, you need to go to the Cloudflare dashboard and enable Turnstile for your domain. Here is how you can do that:
- Go to the Cloudflare dashboard and find Turnstile on the left sidebar.
- Select Add a site and fill out the site name and your website’s domain, or select from your existing websites on Cloudflare.
- Choose Managed in Widget mode.
- Copy the
sitekey
andsecret key
and add them to your project's.dev.vars
file.
You should also add them to your project in the Cloudflare dashboard by following the steps here (opens in a new tab).
Using Turnstile in your project
Cloudstarter comes preinstalled with the @marsidev/react-turnstile (opens in a new tab) library which makes it easy to add Turnstile to your project.
First you need to import the TurnstileWidget
component and add it to your form component like this:
import { TurnstileWidget } from "@/lib/turnstile"
export default function MyForm() {
return (
<form action={signup}
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<TurnstileWidget />
<button type="submit">Submit</button>
</form>
)
}
Next you need to validate the Turnstile token on the server side. You can do this by using the turnstileVerify
function. Here is an example of how you can use it inside an server action:
import { turnstileVerify } from "@/lib/turnstile"
export async function signup(initialData, formData) {
let isValid = await turnstileVerify(formData.get("cf-turnstile-response"))
if (!isValid) {
return {
message: "There was an error. Please try again later.",
}
}
// Your signup logic here
}
That's it! You have successfully added Turnstile to your project.\
Customizing Turnstile Widget
You can read more about customizing Turnstile Widget from the @marsidev/react-turnstile
docs (opens in a new tab)