·5 min read
Next.jsSecurityTutorial
In my last post, I walked through the steps of creating a contact form with Next.js and Nodemailer for email handling. However, as I continued to test it, I realized I hadn't considered spam prevention.
What is reCAPTCHA?
Google reCAPTCHA is a service that protects your site from bots by ensuring that the user interacting with your form is human.
Steps to Integrate
-
Get reCAPTCHA keys from Google — Head over to the reCAPTCHA admin console and register your site.
-
Install the library:
npm install react-google-recaptcha
- Add to your form:
import ReCAPTCHA from "react-google-recaptcha";
function ContactForm() {
const [captchaValue, setCaptchaValue] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
if (!captchaValue) {
alert("Please complete the captcha");
return;
}
// Submit form with captchaValue
};
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
<ReCAPTCHA
sitekey="YOUR_SITE_KEY"
onChange={setCaptchaValue}
/>
<button type="submit">Send</button>
</form>
);
}
- Verify on the server:
const verifyCaptcha = async (token) => {
const response = await fetch("https://www.google.com/recaptcha/api/siteverify", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `secret=${process.env.RECAPTCHA_SECRET}&response=${token}`,
});
const data = await response.json();
return data.success;
};
Conclusion
Adding reCAPTCHA is a simple but effective way to protect your forms from spam. The integration takes just a few minutes and saves you from cleaning up bot submissions.