React CAPTCHA
The following tutorial will guide you on how to integrate the TrustCaptcha CAPTCHA solution into your Go backend to retrieve and evaluate the CAPTCHA verification result.
Preparation
Section titled “Preparation”You should have already completed the following steps before you start with CAPTCHA widget integration in your in React frontend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
Existing React website: You need a React website in which you want to integrate the TrustCaptcha CAPTCHA widget.
Integrate the CAPTCHA widget
Section titled “Integrate the CAPTCHA widget”Follow the steps below to integrate the TrustCaptcha CAPTCHA widget into your React frontend
1. Add dependency
Section titled “1. Add dependency”Add the CAPTCHA dependency to your React project.
npm i @trustcomponent/trustcaptcha-react2. Integrate CAPTCHA widget
Section titled “2. Integrate CAPTCHA widget”Insert the trustcaptcha-component into your HTML. It is important that the widget is located within a form element. Then set the required site-key. You can find this key in your CAPTCHA settings. Information on all other properties can be found in the CAPTCHA widget overview.
Important: Once the CAPTCHA has been solved, you will receive a so-called verification token. This is available as a hidden input field with the name tc-verification-token. You can also get the token via the JavaScript event captchaSolved of the trustcaptcha component. Then send the verification token to your backend and validate it there. You can find out more about this in result validation overview.
import {TrustcaptchaComponent} from "@trustcomponent/trustcaptcha-react";
function App() {
function handleSuccess(verificationToken) { // handle success }
function handleError(error) { // handle error }
return ( <div> <form>
<!-- your input fields -->
<TrustcaptchaComponent sitekey="<your_site_key>" onCaptchaSolved={event => handleSuccess(event.detail)} onCaptchaFailed={event => handleError(event.detail)} ></TrustcaptchaComponent>
<!-- further input fields / submit button -->
</form> </div> );}
export default App;Example implementation
Section titled “Example implementation”The following example shows a possible implementation of the TrustCaptcha CAPTCHA widget in a React frontend.
The complete example including source code can be found on Github.
import logo from './logo.svg';import './App.css';import {TrustcaptchaComponent} from "@trustcomponent/trustcaptcha-react";import {useRef, useState} from "react";import apiService from './apiService';
function App() {
const trustcaptchaRef = useRef(null); const [verificationResult, setVerificationResult] = useState(null); const [form, setForm] = useState({ message: '', verificationToken: null });
const handleInput = (e) => { const { name, value } = e.target; setForm(prevForm => ({ ...prevForm, [name]: value })); };
function solved(verificationToken) { console.log(`Verification-token: ${verificationToken}`); setForm(prevForm => ({ ...prevForm, verificationToken: verificationToken })); }
function failed(error) { console.error(error); }
const handleSubmit = (e) => { e.preventDefault(); apiService.postApi(form.verificationToken).then(verificationResult => setVerificationResult(verificationResult)); };
const resetCaptcha = () => { trustcaptchaRef.current.reset(); setForm({ message: '', verificationToken: null }); setVerificationResult(null); };
return ( <div> <div className="flex py-24 justify-center h-screen"> <div className="w-full max-w-lg space-y-4">
<img src={logo} height={400} alt="logo"/> <h1 className="text-3xl font-bold">React Sample</h1> Try TrustCaptcha.
<br/>
<form className="space-y-4" onSubmit={handleSubmit}> <div> <label htmlFor="message" className="block text-sm font-medium leading-6 text-gray-900">Message</label> <div className="mt-1"> <textarea rows="4" name="message" id="message" placeholder="Write a message ..." value={form.message} onChange={handleInput} className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"></textarea> </div> </div>
<TrustcaptchaComponent ref={trustcaptchaRef} sitekey="<your_site_key>" language="en" theme="light" tokenFieldName="tc-verification-token" onCaptchaSolved={event => solved(event.detail)} onCaptchaFailed={event => failed(event.detail)} ></TrustcaptchaComponent>
<button type="submit" className="w-full rounded-md bg-green-500 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-green-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-500 disabled:opacity-60 disabled:hover:bg-green-500" disabled={!form.verificationToken || verificationResult}>Send message </button> </form>
{verificationResult && <div className="space-y-4"> <div className="rounded-md bg-green-50 p-4 border border-green-500"> <strong>Message: </strong>{form.message}<br/> <strong>Passed: </strong>{verificationResult.verificationPassed.toString()}<br/> <strong>Reason: </strong>{verificationResult.reason}<br/> <strong>Score: </strong>{verificationResult.score}<br/> </div> <button type="button" className="w-full rounded-md bg-blue-500 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-blue-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500" onClick={() => resetCaptcha()}>Reset captcha</button> </div> }
</div> </div> </div> );}
export default App;const apiService = { postApi: async (verificationToken) => { const url = 'http://localhost:8080/api/example'; const options = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ verificationToken }), };
try { const response = await fetch(url, options); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } catch (error) { console.error('Error posting data', error); throw error; } },};
export default apiService;Next steps
Section titled “Next steps”Once you have integrated the TrustCaptcha widget into your frontend, please remember to check the verification token on the server side and evaluate the CAPTCHA result. You can find more information on this in result validation overview. We also recommend that you familiarize yourself with the following topics:
Security rules: You can find many security settings for your CAPTCHA in the CAPTCHA settings. These include, for example, authorized websites, CAPTCHA bypass for specific IP addresses, bypass keys, IP based blocking, geoblocking, individual difficulty and duration of the CAPTCHA, and much more. Learn more about the security rules.
Privacy & GDPR compliance: Include a passage in your privacy policy that refers to the use of TrustCaptcha. We also recommend that you enter into a data processing agreement with us to stay GDPR-compliant. Learn more about data protection.
Accessibility & UX: Customize TrustCaptcha to your website so that your website is as accessible as possible and offers the best possible user experience. More about accessibility.
Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.