google-recaptcha-v3
TypeScript icon, indicating that this package has built-in type declarations

1.0.5 • Public • Published

React Google Recaptcha V3

Install:

npm i google-recaptcha-v3

Import to React:

import { useGoogleRecaptcha } from "google-recaptcha-v3";

Use in React

import React from "react";
import { useGoogleRecaptcha } from "google-recaptcha-v3"

const YourComponent = () => {
  const siteKey = "YOUR_SITE_KEY";
  const action = "submit";
  const { token } = useGoogleRecaptcha(siteKey, action);
  // You can use token to send request to API
  return (
    <div>
     

    </div>
  );
};

export default YourComponent;

Use as components :

import React, { useState } from 'react';
import { ReCaptchaComponent } from "google-recaptcha-v3"


const MyForm: React.FC = () => {
  const [token, setToken] = useState<string>('');

  const handleVerify = (token: string) => {
    setToken(token);
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    console.log('Form submitted with token:', token);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" id="name" name="name" required />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input type="email" id="email" name="email" required />
      </div>
      <ReCaptchaComponent
        siteKey="YOUR_RECAPTCHA_SITE_KEY"
        action="submit_form"
        onVerify={handleVerify}
      />
      <button type="submit" disabled={!token}>Submit</button>
    </form>
  );
};

export default MyForm;

Next :

Verify recaptcha token from React with Nestjs Back-End :

Create RecaptchaMiddleware by CMD :

nest generate middleware recaptcha

Add Sample code to RecaptchaMiddleware :

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import axios from 'axios';

@Injectable()
export class RecaptchaMiddleware implements NestMiddleware {
  private key = 'YOUR_SITE_SECRET_KEY';
  async use(req: Request, res: Response, next: NextFunction) {
    const recaptchaToken = req.body.recaptchaToken;
    if (!recaptchaToken) {
      return res.status(400).json({ message: 'Missing recaptchaToken' });
    }

    try {
      const response = await axios.post(
        `https://www.google.com/recaptcha/api/siteverify?secret=${this.key}&response=${recaptchaToken}`,
        {},
      );

      const { success } = response.data;

      if (!success) {
        return res.status(401).json({ message: 'Invalid recaptchaToken' });
      }

      next();
    } catch (error) {
      console.error('Recaptcha verification error:', error);
      return res.status(500).json({ message: 'Internal Server Error' });
    }
  }
}

Author

Copyright 2024 mia nguyen x thind9xdev

Licensed under the MIT License

Package Sidebar

Install

npm i google-recaptcha-v3

Weekly Downloads

19

Version

1.0.5

License

MIT

Unpacked Size

10.8 kB

Total Files

8

Last publish

Collaborators

  • thind9xdev