How to verify recaptcha in Node.js server call ?
Google reCAPTCHA: reCAPTCHA is a CAPTCHA system that enables web hosts to distinguish between human and automated access to websites. This service is offered by Google.
There are two versions of reCAPTCHA offered by google:
- reCAPTCHA v3
- reCAPTCHA v2
In this article, we will see about reCAPTCHA v2.
- Register your site at google reCAPTCHA
- Submit HTML form.
- Get the response key in the Node.js server
- Re-verify the key and give response to user end.
Step 1: Register your site at google reCAPTCHA
Register your website at Google reCAPTCHA platform to get keys i.e. Site key and Secret key needed to code the HTML form.
Click here to go to Google reCAPTCHA website.
Step 2: Creating Google reCAPTCHA form in HTML
Here, We are going to create a simple HTML form with action as /submit, one input field, and a button. Meanwhile, we need to add google reCAPTCHA CDN in our HTML document and a div tag in the form to get reCAPTCHA in the HTML document.
CDN: <script src="https://www.google.com/recaptcha/api.js" async defer></script> DIV TAG: <div class="g-recaptcha" data-sitekey="your_site_key"></div>
Note: Your need to replace “your_site_key” with your Site Key.
Step 3: Node.js Server:
We have our form ready, let’s code our Server file. On the server-side, we are going to use two packages, one is express for the server as a web framework and another is isomorphic-fetch for http/https call.
Create new directory and generate package.json file in it. Use npm init command to generate the package.json file, its the best practice. Here is my package.json file for reference.
Now, Let’s code for Server file where HTML form will submit data.
Step 4: Verify the captcha:
In order to verify the captcha, We need to make a post request to the following URL.
- URL: https://www.google.com/recaptcha/api/siteverify?secret=<secret_key>&response=<response_key>
- secret_key: This key you will get from google console i.e. Secret Key.
- response_key: This key comes from the client-side when a user submits the form.
- g-recaptcha-response is the name of response key that browser will generate upon form submit. If its blank or null means user has not selected the captcha, so return the error.
- Your need to replace “your_secret_key” with your Secret Key.
Running the app:
To run the application, switch to the project folder and run the Node app using the command.
Go to localhost:4000 to view the app.
- When Captcha Verified
- When Captcha is not verify