Google Recaptcha implementation within minutes in your Angular project

Davut Gürbüz
2 min readAug 10, 2022

If you haven’t tried Google’s captcha service yet, let’s see how we can implement it within minutes using ngx-recaptcha in an angular project.

Step 1 -Get a Google captcha key

We need to visit below address and fill the form as seen below. Domain name addresses are important if you would like to restrict your captcha for certain domains. i.e. localhost, yoursite.com, yourtestenv.local.. you shall enter without the schema.

You may also set the difficulty and other options online.

https://www.google.com/recaptcha/admin/create

Step 2 -Install Captcha into your Angular App

You may use ngx-captcha and follow its official guide at https://www.npmjs.com/package/ngx-captcha. Just as an example, I’ll demonstrate my use case here below . Then, you may enhance it to protect your application from brute force attacks by developing your own strategy.

npm install ngx-captcha

After installation make sure you’ve `NgxCaptchaModule` under `app.module.ts` imports.

Step 3- Develop a strategy to display the captcha

Adding below code to your `form group` will show captcha by default, but solving `I’m not-a-robot` problems at every login attempt can be annoying after some time.

// this will immediately make captcha as required
recaptcha: [‘’, Validators.required]

So, the implementation below is designed to show it after a login failure. You can also consider using `FormArray API` in order to add form elements dynamically. However, I believe my implementation is simpler for this demo use case.

//your login.component.ts //We'll use this reference to enable captcha later
@ViewChild('captchaElem', { static: false }) captchaElem: ReCaptcha2Component;
// kepcheHidden variable will help us to hide/view captcha control
kepceHidden:boolean=true;
siteKey:any="siteKey_you_got_from_google";ngOnInit() {this.loginForm = this.formBuilder.group({username: [‘’, Validators.required],
password: [‘’, Validators.required],
recaptcha: this.formBuilder.control(‘’)
});
//your login.component.html, under form group elements<div class=”form-group “>
<ngx-recaptcha2 #captchaElem [hidden]=”kepceHidden”
[siteKey]=”siteKey”
[useGlobalDomain]=”false”
formControlName=”recaptcha”>
</ngx-recaptcha2>
</div>

After having the initial setup and UI, we can enable it after an unsuccessful login attempt and refresh the captcha for each login failure.

// Where you're handling a failing attempt.
if(status=='401'){
this.error = ‘Username or Password do not match.’;
this.kepceHidden=false;
//get a reference of captcha form control using `get` or @ViewChild
this.loginForm.get(‘recaptcha’).setValidators(Validators.required);
this.captchaElem.resetCaptcha();
}

Enjoy it.

--

--