Written by: Geoffrey Callaghan
what is a form honeypot
What Is A Form Honeypot
A form honeypot is a technique used to prevent automated bots from submitting forms on websites. The idea is to include a form field that is hidden from human users but visible to bots. Since bots typically fill out all form fields, including hidden ones, this can help distinguish between legitimate submissions and spam.
Add a Hidden Field: Add a form field to your form that is either hidden via CSS or placed out of sight. Human users won’t see it and thus won’t fill it out, but bots will typically fill it out.
Validate Submission: When the form is submitted, check if the hidden field has been filled out. If it has, treat the submission as spam and discard it.
Here is a basic example of implementing a honeypot field in an HTML form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Honeypot Example</title>
<style>
.honeypot {
display: none;
}
</style>
</head>
<body>
<form action="/submit" method="POST" onsubmit="return checkHoneypot()">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<!-- Honeypot field -->
<div class="honeypot">
<label for="honeypot">Leave this field empty:</label>
<input type="text" id="honeypot" name="honeypot">
</div>
<button type="submit">Submit</button>
</form>
<script>
function checkHoneypot() {
var honeypot = document.getElementById('honeypot').value;
if (honeypot) {
// Honeypot field is filled out, likely a bot
console.log('Bot detected.');
return false; // Prevent form submission
}
return true; // Allow form submission
}
</script>
</body>
</html>
While the client-side validation helps to reduce spam, server-side validation is crucial for security. Here’s an example using Node.js and Express:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/submit', (req, res) => {
if (req.body.honeypot) {
// Honeypot field is filled out, likely a bot
console.log('Bot detected.');
res.status(400).send('Bot detected.');
} else {
// Process the form submission
console.log('Form submitted successfully:', req.body);
res.status(200).send('Form submitted successfully.');
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
A honeypot is a simple yet effective technique to help mitigate spam form submissions. It’s best used in combination with other methods like CAPTCHA, rate limiting, and server-side validation to provide robust protection against spam and automated form submissions.