Setup reCaptcha in Angular

How to setup reCaptcha in Angular using ng-reCaptcha

Setting up reCaptcha becomes necessary to provide good security to front end applications. In this article we are going to be setting up reCaptcha in Angular.

Here are going to be using a library called called ng-recaptcha. Setting up reCaptcha in Angular is made simple using ng-recaptcha library. Follow below steps to setup reCaptcha.

  1. Install ng-recaptcha library using command

    npm install ng-recaptcha --save
    
  2. To setup reCaptcha we need to get siteKey from google reCaptcha site. You can it from here

  3. Fill the details. Provide your domain name.

    For development purposes also provide domain name localhost along with you production domain. Once you push to production remove localhost.

  1. Once we obtain the site key, we need to add below tag in angular html file.

    <re-captcha (resolved)="reCaptchaResolved($event)" siteKey="{{siteKey}}"></re-captcha>
    
  2. In your NgModule , add RecaptchaModule under imports.

  3. If siteKey is correct it should display the reCaptcha.

  4. If we want capture reCaptcha event, then we can use the resolved event to attach a method. We can do further business logic here. In our example we defined it as (resolved)="reCaptchaResolved($event)".

    FYI , In our component ts file we have define reCaptchaResolved method.

Add reCaptcha without ng-recaptcha

We don’t need use ng-recaptcha to setup recaptcha in Angular. ng-recaptcha just makes it easier.

To implement reCaptcha without using ng-recaptcha we need to follow below mentioned steps,

  1. Add below div in your angular html file,

    <div class="g-recaptcha" data-sitekey="{{sitekey}}" data-callback="reCaptchaResolved" id="capcha_element"></div>
    
  2. Add below code in the ts file

    declare var grecaptcha: any;
    
    grecaptcha.render('capcha_element',{'sitekey': this.siteKey});
    
  3. Now finally in your index.html add below script tag,

    <script src='https://www.google.com/recaptcha/api.js'></script>
    
  4. After this recaptcha should be visible

Change language in recaptcha

  1. Google reCaptcha will detect browser language and change the language according to the browser setting.

  2. But if you want to change language explicitly, you can do it in index.html. Add hl parameter in the script src tag, for example if we want to change language to french then you need edit script tag to as shown below.

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

Following the above mentioned steps we can easily setup reCaptcha in an Angular application.

For more articles on Angular check here.