Node.js: How to Programmatically Generate CAPTCHA (3 ways)

Updated: December 30, 2023 By: Guest Contributor Post a comment

Learn some different ways to generate captcha with the help of Node.js

Solution 1: Using svg-captcha Library

Description: The svg-captcha library generates SVG images as captchas, which are hard to be decoded by machines. It offers customization options for the difficulty level of the captcha via various options.

The process:

  1. Install svg-captcha using npm: npm install svg-captcha.
  2. Create a function to generate the captcha and return both the SVG image and the text.
  3. Expose an API endpoint if using in a web application so that the frontend can request for a new captcha.
  4. Validate captcha response from users when forms are submitted.

Example:

import svgCaptcha from 'svg-captcha';

const createCaptcha = () => {
    return svgCaptcha.create();
};

const { data: svg, text } = createCaptcha();
console.log(svg);
console.log('Captcha Text:', text);

Pros: Easy to use; High level of customization; Does not require any external services.

Cons: SVG might not be supported by all clients; Need to handle storage and validation of captcha texts on the server side.

Solution 2: Using Captcha as a Service (e.g., reCAPTCHA)

Description: Utilizing Google’s reCAPTCHA service provides a way to implement captchas without directly generating them. It provides enhanced security and is constantly updated by Google to resist new types of bot attacks. Implementation is straightforward with verification happening through Google’s servers.

Here’re the steps:

  1. Register your site with Google reCAPTCHA and acquire site and secret keys
  2. Add the reCAPTCHA script to your frontend.
  3. Include the site key in an HTML div with the class g-recaptcha.
  4. On form submission, send the reCAPTCHA response token to your backend.
  5. Verify the user’s response using the secret key with a POST request to Google’s API.

Example:

import axios from 'axios';

const verifyCaptcha = async (token) => {
    const secretKey = 'YOUR_SECRET_KEY';
    try {
        const response = await axios.post(`https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${token}`);
        return response.data.success;
    } catch (error) {
        console.error('Error verifying CAPTCHA:', error);
        return false;
    }
};

// Usage
const token = 'user-response-token';
const isVerified = await verifyCaptcha(token);
console.log('Captcha Verified:', isVerified);

Pros: High security; Easy for users; Maintained by Google.

Cons: Dependent on third-party service; Potentially less privacy for users; Network latency during verification.

Solution 3: Generating Custom Image CAPTCHA

Description: Creating a custom image captcha involves generating images on the server-side with a noise background and text overlay. This solution will require the use of an image-processing library like Jimp to draw images and overlay texts on the image.

Below are the steps to follow:

  1. Install Jimp: npm install jimp.
  2. Create a function to generate a random text string for the captcha.
  3. Use Jimp to create an image with a noisy background and overlay the captcha text.
  4. Serve the resulting image through an HTTP server.
  5. Validate the submitted captcha text.

Example:

import Jimp from 'jimp';

const generateCaptchaImage = async () => {
    const image = new Jimp(200, 50, 0xffffffff);
    const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK);
    const text = Math.random().toString(36).substring(2, 8);
    image.print(font, 10, 10, text);
    image.write('captcha.png');
    return { image: 'captcha.png', text };
};

const captcha = await generateCaptchaImage();
console.log('Captcha Image:', captcha.image);
console.log('Captcha Text:', captcha.text);

Pros: No reliance on third-party services; Full control over captcha appearance and complexity.

Cons: Requires additional logic for image generation and captcha verifications; Becomes progressively harder to maintain effectiveness against sophisticated bots.

Conclusion

Implementing a captcha in a Node.js application can be approached in several ways. The svg-captcha library provides a straightforward path for generating visual captchas. Using captcha as a service like Google’s reCAPTCHA offers a hands-off approach with high security but involves third-party dependencies. Custom image captcha creation enables full control but may require more complex setup and maintenance. Each solution has pros and cons that are worth considering to cater to different use cases and requirements.