If you're experiencing an issue on the Backend side, your first step should be to ensure that the required environment variables are set in your .env.local
file:
NEXT_PUBLIC_RECAPTCHA_SITE_KEY=<your-recaptcha-site-key>
RECAPTCHA_SECRET=<your-recaptcha-secret-key>
To handle reCAPTCHA validation, create a new API route in your Next.js project by adding a new file named validateRecaptcha.js
inside the pages/api
directory. Implement a function in this file to verify the reCAPTCHA response key with the secret key. You can accomplish this by utilizing the fetch function to make a POST request to the reCAPTCHA API:
// pages/api/validateRecaptcha.js
export default async function handler(req, res) {
const { recaptchaResponse } = req.body;
const secretKey = process.env.RECAPTCHA_SECRET;
const response = await fetch(
`https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${recaptchaResponse}`,
{
method: "POST",
}
);
const data = await response.json();
if (data.success) {
res.status(200).json({ success: true });
} else {
res.status(400).json({ success: false });
}
}
Update the handleSubmit
function in your Contact component to submit the reCAPTCHA response key to the API route and verify the response:
async function handleSubmit(e) {
e.preventDefault();
const recaptchaResponse = await recaptchaRef.current.executeAsync();
recaptchaRef.current.reset();
// ...proceed with handling your form data
const response = await fetch("/api/validateRecaptcha", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ recaptchaResponse }),
});
if (response.ok) {
// reCAPTCHA validation successful
fetch("/api/email", {
method: "post",
body: JSON.stringify(formData),
});
alert(
`Thank you for sending a message \${name}! I will get back to you soon.`
);
} else {
// reCAPTCHA validation failed
alert("reCAPTCHA validation failed. Please try again.");
}
}
Ensure that you have included a reference to the ReCAPTCHA
component in your Contact component with the correct sitekey
prop equal to your NEXT_PUBLIC_RECAPTCHA_SITE_KEY
environment variable:
const recaptchaRef = useRef();
// ...
<ReCAPTCHA
ref={recaptchaRef}
sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
/>
These adjustments should enable proper server-side reCAPTCHA validation in your application. Upon form submission, the reCAPTCHA response key will be sent to the /api/validateRecaptcha
endpoint for verification using the assigned secret key. If validation is successful, the form data will proceed to the /api/email
endpoint as intended.
This implementation utilizes reCAPTCHA v2 Invisible, but similar modifications can be made to support reCAPTCHA v3 integration.