How to use Google reCAPTCHA in Node.js and Express Framework :: Aug 16 2015

Today i was searching for a good library to work with reCAPTCHA version 2 in nodejs , but unfortunatly i did'nt find any,

so i start writing new library and publish it for public use with MIT license at : https://www.npmjs.com/package/recaptcha2

to install it you can easily use npm with package.json or npm install recaptcha2

after installation as you know you should have site key and secret key from google for your domain ,

if you don't , you can get one in : https://www.google.com/recaptcha/intro/index.html

after that include this in your html file :

<script src='https://www.google.com/recaptcha/api.js'></script>

then in your node program init library main object like :

reCAPTCHA=require('recaptcha2')

recaptcha=new reCAPTCHA({
  siteKey:'your-site-key',
  secretKey:'your-secret-key'
})

 

now if you want to use it in express.js you can simply use it in your request function like :

function submitForm(req,res){
  recaptcha.validateRequest(req)
  .then(function(){
    // validated and secure
    res.json({formSubmit:true})
  })
  .catch(function(errorCodes){
    // invalid
    res.json({formSubmit:false,errors:recaptcha.translateErrors(errorCodes)});// translate error codes to human readable text
  });
}

if you want to use it in another frameworks or native node.js you can use it like :

function submitForm(req,res){
  recaptcha.validateRequest(req)
  .then(function(){
    // validated and secure
    res.json({formSubmit:true})
  })
  .catch(function(errorCodes){
    // invalid
    res.json({formSubmit:false,errors:recaptcha.translateErrors(errorCodes)});// translate error codes to human readable text
  });
}

 

for more details if you are not familiar with javascript Promises , submited recaptcha value checked first, if it was authorized then section will execute , if not catch section will execute and you will receive errors as an array .

 

if you need more specification you can check main document at :

https://github.com/fereidani/recaptcha2

i'm looking forward to hear your comments .

have a nice day .