This code is to be deployed to a Heroku app. The frontend form will then send the captcha data to the Heroku app and wait for a success response before submitting the form.
- Register your site/ get your reCaptcha keys here
- Create a new Heroku App
- In your new Heroku App, go to settings and create a new Config Var called
RECAPTCHA_SECRET
and enter your secret key in the value field - Deploy this code to your Heroku app via the Heroku CLI or hook up the GitHub repository via the Deploy tab in your Heroku App
- After you deploy your app, your app url should display 'reCaptcha verification'
- Add captcha script tag
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
- Add captcha element to form
<div class="g-recaptcha" data-sitekey="YOUR_RECAPTCHA_PUBLIC_SITE_KEY_HERE"></div>
- Add form event listener to send reCaptca data to Heroku server:
var form = document.querySelector('#contact-form');
form.addEventListener("submit", function(event) {
event.preventDefault();
event.stopPropagation();
var recaptcha = document.querySelector('#g-recaptcha-response').value;
fetch('HEROKU_APP_URL_HERE', {
method:'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-type':'application/json'
},
body:JSON.stringify({captcha: recaptcha})
})
.then((res) => res.json())
.then((data) => {
console.log(data);
if(data.success) {
// Submit form if success status returned
form.submit();
} else {
// Handle error messages
}
});
}, false);