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.

Download the BotDetect Java CAPTCHA Library and run this example

Download Location

The React Basic CAPTCHA code example is included in the examples/simple-api/bdc4-simple-api-react-captcha-example.war file of the download package. When deploying (unpacking) the file you will see the following main source code files:


import React, { Component } from 'react';
import { HashRouter } from 'react-router-dom'
import BaseLayout from './BaseLayout.jsx';
import { captchaSettings } from 'reactjs-captcha';

class App extends Component {

  constructor(props) {

      captchaEndpoint: '/bdc4-simple-api-react-captcha-example/botdetectcaptcha'

  render() {
    return (
        <BaseLayout />

export default App;

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.


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

class Basic extends React.Component {

  constructor(props) {

  componentDidMount() {
    // UI captcha validation on blur event by using the custom 'validatecaptcha' event
    // and checking the 'event.detail' variable to either show error messages
    // or check captcha code input field status when form is submitted
    document.getElementById('captchaCode').addEventListener('validatecaptcha', function (event) {
      // display or remove error message
      let isCaptchaCodeCorrect = event.detail;

      if (isCaptchaCodeCorrect) {
        document.getElementsByClassName('captcha-code-error')[0].innerHTML = '';
      } else {
        document.getElementsByClassName('captcha-code-error')[0].innerHTML = 'Incorrect code';

  basicFormSubmit(event) {
    // captcha id for validating captcha at server-side
    let captchaId = this.captcha.getCaptchaId();

    // captcha code input value for validating captcha at server-side
    let captchaCode = this.captcha.getCaptchaCode();

    let postData = {
      captchaId: captchaId,
      captchaCode: captchaCode

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


  render() {
    return (
      <section id="main-content">
        <form id="basicForm" method="POST" onSubmit={this.basicFormSubmit.bind(this)}>
          <div id="form-messages"></div>

          <Captcha styleName="reactBasicCaptcha" ref={(captcha) => {this.captcha = captcha}} />

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

          <div className="error captcha-code-error"></div>

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

export default Basic;

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.