React Basic CAPTCHA Code Example

  1. Client-side
  2. Server-side

I. Client-side

The React Captcha Basic code example shows the most basic source code required to protect a React application with BotDetect CAPTCHA and validate the user input. It can be used as a starting point when you first learn how to use BotDetect in your React application.


import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class Basic extends React.Component {

  constructor(props) {
      captchaEndpoint: '/bdc4-simple-api-react-captcha-example/botdetectcaptcha'

  componentDidMount() {
    const self = this;
    // a global variable that holds validation status of captcha input field,
    // use it for checking validation status when form is submitted
    this.isCorrectCaptchaCode = false;

    // UI captcha validation on blur event by using the custom 'validatecaptcha' event
    // and checking the 'isCorrect' variable to either show error messages
    // or check captcha code input field status when form is submitted
    document.getElementById('captchaCode').addEventListener('validatecaptcha', function (e) {
      // update validation status of captcha code input
      self.isCorrectCaptchaCode = e.detail;
      // display or remove error message
      if (e.detail) {
      } else {
        document.getElementById('captchaCode').value = 'Incorrect code';
        document.getElementById('submitButton').setAttribute('disabled', true);

  basicFormSubmit(event) {
    // get captcha client-side object
    const captcha = this.captcha.getInstance();
    const isCorrect = this.isCorrectCaptchaCode;
    if (isCorrect) {
      // captcha id for validating captcha at server-side
      const captchaId = captcha.captchaId;

      // captcha code input value for validating captcha at server-side
      const captchaCode = document.getElementById('captchaCode').value;

      const postData = {
        captchaId: captchaId,
        captchaCode: captchaCode
      const formMess = document.getElementById('form-messages');'/bdc4-simple-api-react-captcha-example/basic-captcha', postData)
        .then(response => {
          if ( {
            // captcha validation passed at server-side
            formMess.setAttribute('class', 'alert alert-success');
            formMess.innerHTML = 'CAPTCHA validation passed.';
          } else {
            // captcha validation failed at server-side
            formMess.setAttribute('class', 'alert alert-error');
            formMess.innerHTML = 'CAPTCHA validation falied.';
        }).catch(function (error) {
          throw new Error(error);

    } else {
      formMess.setAttribute('class', 'alert alert-error');
      formMess.innerHTML = 'Captcha code could not be empty.';

  render() {
    return (
      <section id="main-content">
        <form id="basicForm" method="POST" onSubmit={this.basicFormSubmit.bind(this)}>
          <div id="form-messages"></div>
          // show captcha image in form
          <Captcha styleName="reactBasicCaptcha" ref={(captcha) => {this.captcha = captcha}} />

            <span>Retype the characters from the picture:</span>
            <input name="captchaCode" id="captchaCode" data-correct-captcha/>

          <div className="error captchaCode"></div>

          <button type="submit" id="submitButton" disabled="disabled">Validate</button>

module.exports = Basic;

We first import the Captcha component in the React component and use captchaSettings.set() to configure BotDetect Java Captcha path in captchaEndpoint setting in constructor method.

In the React component render method, we add Captcha protection to the form by redering the Captcha component, set to styleName attribute a Captcha style name defined in botdetect.xml configuration file below, and use ref attribute as shown right above in order to access Captcha element and we will use it to get the BotDetect client-side object later when form is submitted in basicFormSubmit method.

Once we add data-correct-captcha attribute in the captcha code input element, BotDetect Captcha React component will then automatically validate captcha code on blue event in default. And to check the UI captcha validation result, we listen the custom validatecaptcha event, which will be fired on captcha code input blur event.

On form submit (basicFormSubmit method), we need to send captcha id value and captcha code visitors submitted to server-side to validate Captcha code once at server-side api. Once request finished, we always reload Captcha by calling reloadImage() function of captcha object. This is needed to generate the new captcha code for the current captcha id.

II. Serverside


<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns=""


In WEB-INF/botdetect.xml, we configure some captcha options for our React basic captcha. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

package com.captcha.botdetect.examples.reactjs.basic_form;

import com.captcha.botdetect.web.servlet.SimpleCaptcha;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BasicServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    Gson gson = new Gson();

    response.setContentType("application/json; charset=utf-8");

    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader());

    String captchaId = formDataObj.get("captchaId").getAsString();
    String captchaCode = formDataObj.get("captchaCode").getAsString();

    // validate captcha
    SimpleCaptcha captcha = SimpleCaptcha.load(request);
    boolean isHuman = captcha.validate(captchaCode, captchaId);

    if (isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here

    // the object that stores validation result
    BasicValidationResult validationResult = new BasicValidationResult();

    try {
      // write the validation result as json string for sending it back to client
    } catch(Exception ex) {
    } finally {

At server-side api, we will get captchaId and captchaCode values sent from client-side and use validate(captchaCode, captchaId) method of SimpleCaptcha instance to validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

package com.captcha.botdetect.examples.jquery.basic_form;

public class BasicValidationResult {
  private boolean success;

  public BasicValidationResult() {

  public boolean getSuccess() {
    return success;

  public void setSuccess(boolean success) {
    this.success = success;

This class is to store Captcha validation result and use it to convert to JSON string using Gson library in BasicServlet.

Please Note

React Captcha Component requires the new experimental Simple API that is currently available in BotDetect Java version (4.0.Beta3+) and BotDetect PHP version (4.2.0+). Click here to find out when the Simple API will be available in BotDetect ASP.NET.