How to Add CleanTalk Bot Detector
The CleanTalk Bot Detector helps protect your forms from spam by automatically detecting and blocking bot submissions.
Step 1: Add the Bot Detector Script to HTML Header
Add the CleanTalk Bot Detector script to the <head> section of your index.html file:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Your Site Title</title>
<!-- Add CleanTalk Bot Detector script -->
<script src="https://fd.cleantalk.org/ct-bot-detector-wrapper.js"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
Step 2: Update Your Form Component
To collect the ct_bot_detector_event_token from the form, you need to:
2.1. Import required React hooks
import { useState, useRef } from 'react'
2.2. Add a form ref to access the form element
const formRef = useRef(null)
2.3. Create a function to get the bot detector token
function getBotDetectorToken() {
if (!formRef.current) return ''
const tokenField = formRef.current.querySelector('input[name="ct_bot_detector_event_token"]')
return tokenField ? tokenField.value : ''
}
2.4. Update your form submission handler
In your handleSubmit function, get the token before submitting:
async function handleSubmit(e) {
e.preventDefault()
// Get the bot detector token from the hidden field
const botToken = getBotDetectorToken()
const formData = { ...values, ct_bot_detector_event_token: botToken }
// Continue with form submission...
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
})
}
2.5. Attach the ref to your form element
return (
<form ref={formRef} onSubmit={handleSubmit}>
{/* Your form fields */}
</form>
)
Step 3: Add Token Validation (Optional)
Add validation to ensure the token is present before form submission:
function validate(values) {
const errors = {}
// ... other validations
if (!values.ct_bot_detector_event_token) {
errors.ct_bot_detector_event_token = 'Bot detector event token is required'
}
return errors
}
How It Works
- The CleanTalk script (ct-bot-detector-wrapper.js) automatically injects a hidden input field with name="ct_bot_detector_event_token" into all forms on the page.
- When the form is submitted, the getBotDetectorToken() function retrieves the token value from the hidden field.
- The token is included in the form data sent to your server.
- Your backend can verify the token with CleanTalk's API to validate the submission and block spam.
- See https://github.com/CleanTalk/react-antispam for a complete implementation example.
Backend Integration
When submitting forms, make sure your backend receives and validates the ct_bot_detector_event_token.