How I integrated Google reCAPTCHA with my React+Django-based portfolio
JavaScript and the browser console have already provided a lot of power to the client side of a webpage. Anyone with a little knowledge of JavaScript can flood your database with fake entries if it’s just an information collecting form, leaving you with nothing but a ton of validated data, nearly impossible to filter out. Generally, it is a lot of fun for the person running scripts and it provides him with a boundless source of happiness so ethics can be ruled out as a guard for your database. Even I try to run JavaScript scripts wherever possible 😜
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 putlocalhost
) and registering, the admin dashboard provides you with two keys.
2. Frontend
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.
Component:
Function:
Here, key
is the key provided by the captcha you need to verify on the backend.
Submit Function:
You can check out more props to pass to react-google-recaptcha (or here).
3. 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.
Happy Rendering!