/

How to Integrate ReCaptcha into a Next.js Form

How to Integrate ReCaptcha into a Next.js Form

tags: [“Next.js”, “ReCaptcha”, “form validation”, “spam protection”, “Google”]

ReCaptcha is a powerful tool provided by Google to combat spam and abuse in online forms. By adding ReCaptcha to your Next.js form, you can ensure that only real users can submit the form, while blocking bots and automated spam. In this tutorial, we will guide you through the process of integrating ReCaptcha into your Next.js form.

Getting Started with ReCaptcha

Before you can add ReCaptcha to your Next.js form, you need to create an account on the Google ReCaptcha website (https://www.google.com/recaptcha). Once you have created an account, add your site domain and obtain a site key and a site secret.

Storing ReCaptcha Secret

To securely store your ReCaptcha secret, create a .env file in your Next.js project and store the secret there like this:

1
RECAPTCHA_SECRET=<your-secret-key>

Installing the Required Package

Next, you will need to install the react-google-recaptcha package using npm. Open your terminal and run the following command:

1
npm install react-google-recaptcha

This package will provide the necessary components and functionality to integrate ReCaptcha into your Next.js form.

Integrating ReCaptcha into Your Form

Now, locate the page where you have your form in your Next.js project. Import the ReCAPTCHA component from the react-google-recaptcha package by adding the following line at the top of your file:

1
import ReCAPTCHA from 'react-google-recaptcha'

Next, add the ReCAPTCHA component to your form JSX by inserting the following line inside your form:

1
<ReCAPTCHA size="normal" sitekey="<YOUR SITE KEY>" />

Make sure to replace <YOUR SITE KEY> with the site key obtained from the ReCaptcha website.

Validating ReCaptcha Server-Side

To make the ReCaptcha validation useful, you need to validate it server-side. If you are using a Next.js API route for form submission, follow these steps:

  1. In your API route file, add a validateCaptcha method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const validateCaptcha = (response_key) => {
return new Promise((resolve, reject) => {
const secret_key = process.env.RECAPTCHA_SECRET

const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`

fetch(url, {
method: 'post'
})
.then((response) => response.json())
.then((google_response) => {
if (google_response.success === true) {
resolve(true)
} else {
resolve(false)
}
})
.catch((err) => {
console.log(err)
resolve(false)
})
})
}
  1. In your API route file, add the following code before processing the form submission:
1
2
3
4
if (!(await validateCaptcha(req.body['g-recaptcha-response']))) {
return res.redirect(`/captcha`)
}
delete req.body['g-recaptcha-response']

This code will validate the ReCaptcha response from the form submission. If the response is not valid, the user will be redirected to a /captcha page.

Frontend Validation

To enhance user experience, you can also add frontend form validation to prompt users to complete the ReCaptcha field before submitting the form. Here is an example of how to add frontend validation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<form
method='post'
action='/api/new'
enctype='multipart/form-data'
onSubmit={event => {
if (grecaptcha.getResponse() === '') {
event.preventDefault()
alert("Please click 'I'm not a robot' before submitting the form.")
}
}}
>
{/* form fields */}
<button type="submit">Submit</button>
</form>

By including this validation, the form will not be submitted unless the ReCaptcha checkbox has been clicked.

Congratulations! You have successfully added ReCaptcha to your Next.js form, providing an additional layer of security and preventing spam submissions.