Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs and Google Recaptcha

I am trying to implement a server-side validation for reCaptcha using Nestjs and I want to if I should implement this as a module or as a service for modules(such as a self written user authentication module) that would require the use of reCaptcha.

like image 220
Tahjyei Thompson Avatar asked Oct 19 '25 14:10

Tahjyei Thompson


1 Answers

I solved it by creating a seperate RecaptchaGuard.

// recaptcha.guard.ts
import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpService,
  ForbiddenException,
} from "@nestjs/common";

@Injectable()
export class RecaptchaGuard implements CanActivate {
  constructor(private readonly httpService: HttpService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const { body } = context.switchToHttp().getRequest();

    const { data } = await this.httpService
      .post(
        `https://www.google.com/recaptcha/api/siteverify?response=${body.recaptchaValue}&secret=${process.env.RECAPTCHA_SECRET}`
      )
      .toPromise();

    if (!data.success) {
      throw new ForbiddenException();
    }

    return true;
  }
}

Next you can simply apply the recaptcha guard on a controller.

// app.controller.ts
import { Controller, Post, UseGuard } from '@nestjs/common';
import { RecaptchaGuard } from './recaptcha.guard.ts'
    
@Controller()
export class AppController {

 @Post()
 @UseGuard(RecaptchaGuard)
 async postForm(){
  //
 }
}
like image 132
Robert-Jan Kuyper Avatar answered Oct 22 '25 07:10

Robert-Jan Kuyper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!