You are currently viewing How to Integrate Google reCAPTCHA v3 with NestJS in 3 Easy Steps

How to Integrate Google reCAPTCHA v3 with NestJS in 3 Easy Steps

Google’s reCAPTCHA is a widely used tool to protect your web applications from spam and abuse. In this blog post, we’ll walk through the steps to integrate reCAPTCHA v3 with your NestJS application.

Step 1: Set up reCAPTCHA and Obtain the Necessary Keys

First, you need to sign up for a reCAPTCHA v3 account on the Google reCAPTCHA website. Once you’ve registered your site, you’ll be provided with a Site Key and a Secret Key. These keys will be used to verify the reCAPTCHA token on the server-side.

Step 2: Implement the reCAPTCHA Verification Logic

Next, let’s create a utility function to handle the reCAPTCHA verification process. This function will take the reCAPTCHA token from the client, verify it with the Google reCAPTCHA API, and return the verification result.

// utils.ts
export const verifyRecaptcha = async (token: string) => {
  const secretKey = process.env.RECAPTCHA_SECRET_KEY;
  const verifyUrl = process.env.RECAPTCHA_VERIFY_URL;
  const minimumScore = 0.5;
  const expectedHostname = process.env.RECAPTCHA_EXPECTED_HOSTNAME;

  try {
    const response = await axios.post(verifyUrl, null, {
      params: {
        secret: secretKey,
        response: token,
      },
    });

    const { success, score, hostname } = response.data;

    if (!success) {
      throw new Error('Invalid captcha');
    }

    if (score < minimumScore) {
      throw new Error('Low captcha score');
    }

    if (expectedHostname && hostname !== expectedHostname) {
      throw new Error('Invalid hostname');
    }

    return true;
  } catch (error) {
    console.error('Error verifying reCAPTCHA:', error);
    return false;
  }
};Code language: JavaScript (javascript)

Step 3: Create a NestJS Guard to Protect Your Endpoints

Finally, let’s create a NestJS guard that will intercept the incoming requests and verify the reCAPTCHA token. This guard can be applied to your endpoints that you want to protect.

// recaptcha.guard.ts
import { BadRequestException, CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { verifyRecaptcha } from './utils';

@Injectable()
export class RecaptchaGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = request.headers['x-recaptcha-token'];
    if (!token) {
      throw new BadRequestException('Recaptcha token is required');
    }

    return await verifyRecaptcha(token);
  }
}Code language: TypeScript (typescript)

To use the guard, simply apply it to your controller:

// app.controller.ts
import { RecaptchaGuard } from './recaptcha.guard';

@Controller()
@UseGuards(RecaptchaGuard)
export class AppController {
  // Your controller methods
}
Code language: TypeScript (typescript)

That’s it! With these three steps, you’ve successfully integrated Google reCAPTCHA v3 into your NestJS application, adding an extra layer of protection against spam and abuse.

Have any questions, want to share your thoughts or just say Hi? I’m always excited to connect! Follow me on Twitter or LinkedIn for more insights and discussions. If you’ve found this valuable, please consider sharing it on your social media. Your support through shares and follows means a lot to me! 

Leave a Reply