Google reCAPTCHA is a free service that protects your website from spam and abuse. This guide walks through integrating reCAPTCHA v2 into a Node.js application using the Express framework.
Setup
First, register your site at Google reCAPTCHA to get your site key and secret key.
Install the verification module:
npm install recaptcha2
Server-side Verification
Create a middleware to verify the reCAPTCHA response:
var Recaptcha = require('recaptcha2');
var recaptcha = new Recaptcha({
siteKey: 'YOUR_SITE_KEY',
secretKey: 'YOUR_SECRET_KEY'
});
app.post('/submit', function(req, res) {
recaptcha.validate(req.body.recaptcha)
.then(function() {
// Verified - process the form submission
res.send('Verification successful');
})
.catch(function(error) {
// Invalid reCAPTCHA
res.status(400).send('Verification failed');
});
});
Client-side Integration
Add the reCAPTCHA widget to your HTML form:
<form action="/submit" method="POST">
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
<button type="submit">Submit</button>
</div>
<script src="https://www.google.com/recaptcha/api.js"></script>
Error Handling
The verification can fail for several reasons: invalid user input, expired tokens, or network issues. Always handle these cases gracefully and display appropriate feedback to the user.
Conclusion
Integrating reCAPTCHA into your Node.js application adds an important layer of protection against automated abuse. The recaptcha2 module simplifies the server-side verification process.