How I integrated Google reCAPTCHA with my React+Django-based portfolio
I encountered the same problem when I tried to render a Contact Me form in my portfolio as shown in the following image.
So, it’s really easy to run a script here with validated data and ruin my database. That’s where reCAPTCHA comes into the picture. reCAPTCHA is a free service with AI support from Google so it is pretty obvious that it can protect your website from these spam requests. So following are the steps you can follow to integrate one in your app too.
- Get Keys
Visit My reCAPTCHA where, after signing in, you get an option to register a new site.
i. Label: Label is just an identifier to identify your key for future reference because it gives you the option to have multiple keys for different websites.
ii. reCAPTCHAv2: I go for reCAPTCHAv2 because I found a Google-reCAPTCHA v2 npm package to integrate with my React app
After providing the domain you want to run your app on (you can also put
localhost) and registering, the admin dashboard provides you with two keys.
For the frontend, I found react-google-recaptcha, the package most suitable for my use case.
i. Add this package to your project.
$ yarn add react-google-recaptcha
ii. Use the component in the JS file.
key is the key provided by the captcha you need to verify on the backend.
Now, let us go to the server with the data we just posted. The backend doesn’t consist of anything other than making a post request to Google with the key obtained from frontend, Your secret site key, and optionally the user’s IP address. I have used the requests PyPI package for the purpose.
The code snippet is a part of the view which is written in Django and Django REST Framework. You may have a different backend stack but the idea remains the same, i.e. to make a POST request to https://www.google.com/recaptcha/api/siteverify, with these parameters. We have ignored the other parameters in Google’s response, you can check them out here.
Hopefully, this article will help you filter out spam responses in your forms.