2 steps to add invisible reCaptcha to your contact form

With React, AWS Lambda, SES & API Gateway

In this post we will go throw 2 steps to enable Google invisible reCAPTCHA v2 in our contact form. This is a follow up tutorial from the 7 steps to build a serverless contact form. If you haven't seen that tutorial go ahead and do so as we will be building on top of the existing code.

What are we building?
  1. Use

    react-google-recaptcha
    to add a React component for invisible reCAPTCHA v2

    to our contact form.

  2. We will update the existing Lambda function to accept and verify the Client's response.

  3. Upon validation we will send out the email using AWS SES.

Before we start, you will need to have the following:
  • An AWS account

  • Sign up for an API key pair. We will use the site key on the

    <ReCAPTCHA />
    component and the secret key to verify the client's request in the Lambda function.

Step 1: Setup your Form with Invisible reCaptcha

In the codesanbox bellow we are import the ReCAPTCHA component and then create a reference

recaptchaRef = React.createRef()
. Then we add the component just above the submit button with the reference and paste the sitekey. Now we need to pass the recaptcha validation token in our request. We can extract the token from the
recaptchaRef
. In our request it should something look like this
"g-recaptcha-response": recaptchaRef.current.getValue()

Step 2: Verifying the client's response in our AWS Lambda function.

We are now going to modify the Lambda function from the previous tutorial by capturing and verify the client's response token and subsequently send out the email. To do so, we'll make a call to the

async
function
handleValidateRecaptchaToken
and wait for the result. This function triggers a Post https request to
https://www.google.com/recaptcha/api/siteverify
with the following parameters:

  1. secret: This is the secret key which you should have got when you Sign up for an API key pair. Go ahead and add that as an environment variable so you can use it in your lambda function like this:

    process.env.RECAPTCHA_SECRET_KEY

  2. response: The client response token provided by the reCAPTCHA on our contact form.

Notice that we are now waiting for the

valitationResponse
before we trigger the
handleSendEmail
function.

Thats it!

Your form should now be able to validate your users requests before sending out the email in your inbox 🎉.