next-recaptcha-v3

repository·master·Indexed 41 days ago

https://github.com/snelsi/next-recaptcha-v3

A lightweight, tree-shakable Next.js hook and component library for integrating Google ReCaptcha v3. Version 2.0.0-beta.2 provides a ReCaptchaProvider for configuration, a useReCaptcha hook for token generation, a declarative ReCaptcha component, and a withReCaptcha Higher-Order Component (HOC). It utilizes the next/script component for optimized script loading and supports ReCaptcha Enterprise and custom language codes.

Tokens
5.8K
Snippets
18
Records
22
Agent score
51%

What's inside next-recaptcha-v3

  1. Configure ReCaptchaProvider

    master

    To use ReCaptcha, wrap your application with ReCaptchaProvider. This component uses next/script to load the ReCaptcha script into your document.

    You can provide your site key in two ways:

    1. Set the NEXT_PUBLIC_RECAPTCHA_SITE_KEY environment variable.
    2. Pass the reCaptchaKey prop directly to ReCaptchaProvider.
    import { ReCaptchaProvider } from "next-recaptcha-v3";
    
    const MyApp = ({ Component, pageProps }) => (
      <ReCaptchaProvider reCaptchaKey="[GTM-XXXXXXX]">
        <Component {...pageProps} />
      </ReCaptchaProvider>
    );
  2. Access the global grecaptcha object

    master

    The reCAPTCHA library is exposed via a global grecaptcha object. This object provides access to standard reCAPTCHA functionality and, if using reCAPTCHA Enterprise, an enterprise property.

    // Standard reCAPTCHA
    grecaptcha.render(...);
    
    // reCAPTCHA Enterprise
    grecaptcha.enterprise.render(...);
  3. Generate ReCaptcha tokens with useReCaptcha

    master

    To protect a form or action, use executeRecaptcha from the useReCaptcha hook to generate a token just before your API request. Send this token to your server to be validated via the ReCaptcha /siteverify API.

    import { useState, useCallback } from "react";
    import { useReCaptcha } from "next-recaptcha-v3";
    
    const MyForm = () => {
      const [name, setName] = useState("");
      const { executeRecaptcha } = useReCaptcha();
    
      const handleSubmit = useCallback(
        async (e) => {
          e.preventDefault();
    
          // Generate ReCaptcha token with an action name
          const token = await executeRecaptcha("form_submit");
    
          // Send token to your server for validation
          fetch("/api/form-submit", {
            method: "POST",
            body: JSON.stringify({
              data: { name },
              token,
            }),
          });
        },
        [executeRecaptcha, name],
      );
    
      return (
        <form onSubmit={handleSubmit}>
          <input name="name" value={name} onChange={(e) => setName(e.target.value)} />
          <button type="submit">Submit</button>
        </form>
      );
    };
  4. Use the withReCaptcha Higher-Order Component (HOC)

    master

    The withReCaptcha HOC injects ReCaptcha context props directly into your component. This is useful when you want to avoid using hooks inside the component body or when working with class components.

    import { useEffect, useState } from "react";
    import { withReCaptcha, WithReCaptchaProps } from "next-recaptcha-v3";
    
    interface MyPageProps extends WithReCaptchaProps {}
    
    const MyPage: React.FC<MyPageProps> = ({ isLoaded, executeRecaptcha }) => {
      const [token, setToken] = useState<string | null>(null);
    
      useEffect(() => {
        if (isLoaded) {
          const generateToken = async () => {
            const newToken = await executeRecaptcha("page_view");
            setToken(newToken);
          };
          generateToken();
        }
      }, [isLoaded, executeRecaptcha]);
    
      return <h1 onClick={() => console.log(token)}>Hello</h1>;
    };
    
    export default withReCaptcha(MyPage);
  5. Generate ReCaptcha tokens with the ReCaptcha component

    master

    You can use the <ReCaptcha /> component to trigger token generation via an onValidate callback. This is useful for declarative token management.

    import { useEffect, useState } from "react";
    import { ReCaptcha } from "next-recaptcha-v3";
    
    const MyPage = () => {
      const [token, setToken] = useState<string | null>(null);
    
      useEffect(() => {
        if (token) {
          // Perform server-side validation logic here
          console.log("Token generated:", token);
        }
      }, [token]);
    
      return (
        <>
          <ReCaptcha onValidate={setToken} action="page_view" />
          <h1>Hello</h1>
        </>
      );
    };
  6. Use the useReCaptcha hook

    master

    The useReCaptcha hook is the recommended way to access the ReCaptcha context. It provides access to the global grecaptcha object, the loading state, and the executeRecaptcha function used to generate tokens.

    Returned properties:

    • reCaptchaKey: The site key being used.
    • grecaptcha: The global ReCaptcha object.
    • isLoaded: true if the ReCaptcha script has been loaded.
    • isError: true if an error occurred during loading.
    • error: The error object if loading failed.
    • executeRecaptcha: A function to generate a one-time token. It accepts an action name (alphanumeric, slashes, and underscores only; must not be user-specific).
    import { useReCaptcha } from "next-recaptcha-v3";
    
    const { 
      reCaptchaKey, 
      grecaptcha, 
      isLoaded, 
      isError, 
      error, 
      executeRecaptcha 
    } = useReCaptcha();
  7. ReCaptchaProvider Props Reference

    master

    The ReCaptchaProvider component accepts the following props:

    PropTypeDefaultRequiredDescription
    reCaptchaKeystring?Your reCAPTCHA key. Required if NEXT_PUBLIC_RECAPTCHA_SITE_KEY is not defined.
    useEnterprisebooleanfalseSet to true if using ReCaptcha Enterprise.
    useRecaptchaNetbooleanfalseSet to true to use recaptcha.net to load the script.
    languagestringOptional Language Code.

    All extra props are passed directly to the underlying next/script component.

  8. Access reCAPTCHA state with useReCaptchaContext

    master

    To access the current loading state and configuration of reCAPTCHA within your component tree, use the useReCaptchaContext hook. This hook retrieves the context provided by ReCaptchaProvider.

    Context Properties

    The returned object contains the following properties:

    • reCaptchaKey: The site key being used.
    • language: The configured language code.
    • useEnterprise: Boolean indicating if Enterprise mode is active.
    • useRecaptchaNet: Boolean indicating if recaptcha.net is being used.
    • isLoaded: true if the reCAPTCHA script has successfully loaded.
    • isError: true if an error occurred during script loading.
    • error: The Error object if isError is true, otherwise null.
    import { useReCaptchaContext } from 'next-recaptcha-v3';
    
    const MyComponent = () => {
      const { isLoaded, isError, error } = useReCaptchaContext();
    
      if (isError) return <div>Error loading reCAPTCHA: {error?.message}</div>;
      if (!isLoaded) return <div>Loading reCAPTCHA...</div>;
    
      return <div>reCAPTCHA is ready to use!</div>;
    };
  9. Access reCAPTCHA functionality with the useReCaptcha hook

    master

    The useReCaptcha hook provides access to the reCAPTCHA instance within functional components. It returns an object containing the execute method, which you can call to trigger a reCAPTCHA verification and receive a token.

    import { useReCaptcha } from 'next-recaptcha-v3';
    
    const MyComponent = () => {
      const { execute } = useReCaptcha();
    
      const handleAction = async (actionName: string) => {
        const token = await execute(actionName);
        // Send token to your server for verification
      };
    
      return <button onClick={() => handleAction('login')}>Verify</button>;
    };
  10. Use the IReCaptcha interface methods

    master

    The IReCaptcha interface defines the core methods available on the global grecaptcha object for managing reCAPTCHA widgets.

    Methods

    • render(container: string | HTMLElement, parameters?: Parameters, inherit?: boolean): number Renders a reCAPTCHA widget into the specified container. Returns the unique widget ID.

    • reset(opt_widget_id?: number): void Resets the reCAPTCHA widget. If opt_widget_id is omitted, it resets the first widget created.

    • getResponse(opt_widget_id?: number): string Returns the response token for the specified widget ID.

    • execute(opt_widget_id?: number): PromiseLike<void> Programmatically invokes the reCAPTCHA check. Useful for invisible reCAPTCHA on non-button elements. If opt_widget_id is omitted, it uses the first widget.

    • execute(siteKey: string, action: Action): PromiseLike<string> Programmatically invokes the reCAPTCHA check and returns a promise that resolves with the token. Requires a siteKey and an Action object.

    • ready(callback: () => void): void Runs the provided callback as soon as the reCAPTCHA library has finished loading.

    // Example: Rendering and executing an invisible reCAPTCHA
    grecaptcha.ready(() => {
      const widgetId = grecaptcha.render('#container', {
        sitekey: 'YOUR_SITE_KEY',
        size: 'invisible'
      });
    
      // Later, trigger the check
      grecaptcha.execute(widgetId).then(() => {
        console.log('Check completed');
      });
    });