Home  Express   Creating a ...

Creating a custom CAPTCHA using express and svg-captcha

Creating a custom CAPTCHA system involves generating challenges that are easy for humans to solve but difficult for bots. A common approach is to generate a random string and present it to the user as an image, then verify the user's input against the generated string.

Here’s a step-by-step guide to implementing a basic custom CAPTCHA system in Node.js:

  1. Install Required Packages: You’ll need express for the server, svg-captcha for generating CAPTCHA images, and body-parser for handling POST requests.

    npm install express svg-captcha body-parser
    
  2. Create the Server: Set up an Express server to handle the CAPTCHA generation and verification.

  3. Generate CAPTCHA: Use svg-captcha to create CAPTCHA images.

  4. Verify CAPTCHA: Store the CAPTCHA text in the session and verify the user’s input against it.

Here’s the complete code to create a simple custom CAPTCHA system:

Step 1: Setup the Server

Create a file named server.js:

const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const svgCaptcha = require('svg-captcha');

const app = express();
const PORT = 3000;

// Middleware to parse JSON and URL-encoded data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

// Middleware for session handling
app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false } // Set secure to true in production
}));

// Route to generate CAPTCHA
app.get('/captcha', (req, res) => {
  const captcha = svgCaptcha.create();
  req.session.captcha = captcha.text; // Store CAPTCHA text in session
  res.type('svg');
  res.status(200).send(captcha.data); // Send CAPTCHA image as SVG
});

// Route to verify CAPTCHA
app.post('/verify-captcha', (req, res) => {
  const { captcha } = req.body;
  if (captcha === req.session.captcha) {
    res.send('CAPTCHA verification successful!');
  } else {
    res.send('CAPTCHA verification failed!');
  }
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Step 2: Create an HTML Form

Create a file named index.html to test the CAPTCHA:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Custom CAPTCHA</title>
</head>
<body>
  <h1>Custom CAPTCHA Example</h1>
  <form id="captcha-form" action="/verify-captcha" method="POST">
    <div id="captcha-container"></div>
    <input type="text" name="captcha" placeholder="Enter CAPTCHA" required>
    <button type="submit">Submit</button>
  </form>

  <script>
    async function loadCaptcha() {
      const response = await fetch('/captcha');
      const captchaSvg = await response.text();
      document.getElementById('captcha-container').innerHTML = captchaSvg;
    }

    document.addEventListener('DOMContentLoaded', loadCaptcha);
  </script>
</body>
</html>

Step 3: Run the Server

Run the server:

node server.js

Open your browser and navigate to http://localhost:3000/index.html to see the CAPTCHA in action.

Published on: Jun 29, 2024, 02:26 PM  
 

Comments

Add your comment