For static websites, such as those on Gatsby, when handling form submissions, you either need a server to use a third-party form service. The Gatsby docs do a pretty good job in explaining how to build a contact form and it provides options for form submissions. I'm going to assume that you already have your html form set up, you're using Getform for it, and now you're here because you need to add Google reCAPTCHA.
If you were like me, it was pretty straightforward and easy in setting up a contact form with Getform on a Gatsby website. However, within days, I was already receiving spam. Looks like the Akismet spam filtering wasn't able to filter these ones out, and it was time to implement Google reCAPTCHA.
How to add Google reCAPTCHA
The below instructions are for Google reCAPTCHA v2.
Prerequisites
Steps
1. Get API keys for Google reCAPTCHA.
- Go to Google reCAPTCHA and click on "Admin Console".
- Create (+) to register a new site and select v2 with the "I'm not a robot" checkbox.
- Add your domain, along with
localhost
. - Accept the terms and submit.
- Save the site key and secret key somewhere safe.
2. Install the gatsby-plugin-recaptcha
plugin and add it to your gatsby-config.
// console
npm install --save gatsby-plugin-recaptcha
// gatsby-config.js
plugins: [`gatsby-plugin-recaptcha`];
This will inject the script for the reCAPTCHA library between the <head>
tags.
3. (optional) Add the site key as an environment variable to .env.development
and to your CI/CD.
Since it's the site key, this step doesn't matter too much, but I did so for maintainability and management purposes.
4. Add the reCAPTCHA element with the site key to your html form between the <form>
tags.
// pages/contact.tsx
<div class="g-recaptcha" data-sitekey="YOUR reCAPTCHA SITE KEY" />
If you had the site key as an environment variable, it would look like this:
// pages/contact.tsx
<div
class="g-recaptcha"
data-sitekey={process.env.GATSBY_GOOGLE_RECAPTCHA_SITE_KEY}
/>
I added the element just before my buttons for clearing and submitting the form, as it will be displayed like this:
5. Add the secret key to your Getform endpoint.
- Go to Getform and click on the form endpoint under "All" on the left sidebar.
- Click on the lighting bolt icon at the top right for "Automation" settings.
- Add the action "Secure endpoint with Google reCAPTCHA".
- Add the secret key and click "Complete".
- Click on "Save" at the top right to save your form settings.
6. Run gatsby develop
if it's not running already, and you should now see the reCAPTCHA element appear on your form.
Now I can look forward to getting messages from real visitors!
Top comments (0)