npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-recaptcha-v3

v1.5.0

Published

🤖 Next.js hook to add Google ReCaptcha to your application

Downloads

91,476

Readme

Straightforward solution for using ReCaptcha in your Next.js application.

npm package Bundle Size type definition License: MIT

🗜️ Tiny and Tree-Shakable

🥰 Written in TypeScript

🐅 Highly customizable

😎 Uses next/script component

Install

yarn add next-recaptcha-v3

or

npm install next-recaptcha-v3 --save

Pure ESM package

This package is now pure ESM. It cannot be require()'d from CommonJS.

Generate reCAPTCHA Key

To use ReCaptcha, you need to generate a reCAPTCHA_site_key for your site's domain. You can get one here.

You can either add generated key as a Next.js env variable

NEXT_PUBLIC_RECAPTCHA_SITE_KEY="GTM-XXXXXXX"

or pass it directly to the ReCaptchaProvider using reCaptchaKey attribute.

Getting Started

Wrap your application with ReCaptchaProvider. It will load ReCaptcha script to your document.

import { ReCaptchaProvider } from "next-recaptcha-v3";

const MyApp = ({ Component, pageProps }) => (
  <ReCaptchaProvider reCaptchaKey="[GTM-XXXXXXX]">
    <Component {...pageProps} />
  </ReCaptchaProvider>
);

ReCaptchaProvider uses Next.js Script to add ReCaptcha script to the document.

ReCaptchaProvider Props

| Prop | Type | Default | Required | Description | | --------------- | -------- | ----------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | reCaptchaKey | string | | ? | Your reCAPTCHA key, get one from here | | useEnterprise | boolean | false | | Set to true if you use ReCaptcha Enterprise | | useRecaptchaNet | boolean | false | | Set to true if you want to use recaptcha.net to load ReCaptcha script. docs | | language | string | | | Optional Language Code |

You must pass reCaptchaKey if NEXT_PUBLIC_RECAPTCHA_SITE_KEY env variable is not defined.

All extra props are passed directly to the Script tag, so you can use all props from the next/script documentation.

Accessing global context props

You can access global grecaptcha object, script's loading state and other props by calling useReCaptcha hook:

import { useReCaptcha } from "next-recaptcha-v3";

const {
  /** reCAPTCHA_site_key */
  reCaptchaKey,
  /** Global ReCaptcha object */
  grecaptcha,
  /** Is ReCaptcha script loaded */
  loaded,
  /** Is ReCaptcha script failed to load */
  error,
  /** Other hook props */
  ...otherProps
} = useReCaptcha();

reCAPTCHA Enterprise

If you're using reCAPTCHA Enterprise, add useEnterprise to your ReCaptchaProvider. Checkout official quickstart guide here.

import { ReCaptchaProvider } from "next-recaptcha-v3";

const MyApp = ({ Component, pageProps }) => (
  <ReCaptchaProvider useEnterprise>
    <Component {...pageProps} />
  </ReCaptchaProvider>
);

Usage

When invoked, ReCaptcha will analyze the user's behavior and create a one-time token. It can only be used once and is only valid for a couple of minutes, so you should generate it just before the actual validation.

Send the resulting token to the API request to your server. You can then decrypt the token using the ReCaptcha /siteverify API and ignore the call if it came from a bot.

  1. React Hook: useReCaptcha (recommended approach)

Use executeRecaptcha function returned from the useReCaptcha hook to generate token. Add a unique action name to better understand at what moment the token was generated.

🛈 Note: Actions might contain only alphanumeric characters, slashes, and underscores. Actions must not be user-specific.

import { useState, useCallback } from "react";
import { useReCaptcha } from "next-recaptcha-v3";

const MyForm = () => {
  const [name, setName] = useState("");

  // Import 'executeRecaptcha' using 'useReCaptcha' hook
  const { executeRecaptcha } = useReCaptcha();

  const handleSubmit = useCallback(
    async (e) => {
      e.preventDefault();

      // Generate ReCaptcha token
      const token = await executeRecaptcha("form_submit");

      // Attach generated token to your API requests and validate it on the server
      fetch("/api/form-submit", {
        method: "POST",
        body: {
          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>
  );
};
  1. ReCaptcha component

Alternatively, you can also generate token by using ReCaptcha component.

import { useEffect, useState } from "react";
import { ReCaptcha } from "next-recaptcha-v3";
import { validateToken } from "./utils";

const MyPage = () => {
  const [token, setToken] = useState<string>(null);

  useEffect(() => {
    if (token) {
      // Validate token and make some actions if it's a bot
      validateToken(token);
    }
  }, [token]);

  return (
    <>
      <ReCaptcha onValidate={setToken} action="page_view" />
      <h1>Hello</h1>
    </>
  );
};
  1. withReCaptcha HOC
import { useEffect, useState } from "react";
import { withReCaptcha, WithReCaptchaProps } from "next-recaptcha-v3";
import { validateToken } from "./utils";

interface MyPageProps extends WithReCaptchaProps {}

const MyPage: React.FC<MyPageProps> = ({ loaded, executeRecaptcha }) => {
  const [token, setToken] = useState<string>(null);

  useEffect(() => {
    if (loaded) {
      const generateToken = async () => {
        const newToken = await executeRecaptcha("page_view");
        setToken(newToken);
      };
      generateToken();
    }
  }, [loaded, executeRecaptcha]);

  useEffect(() => {
    if (token) {
      // Validate token and make some actions if it's a bot
      validateToken(token);
    }
  }, [token]);

  return <h1>Hello</h1>;
};

export default withReCaptcha(MyPage);

Helpful links

TypeScript

The module is written in TypeScript and type definitions are included.

Contributing

Contributions, issues and feature requests are welcome!

Show your support

Give a ⭐️ if you like this project!

LICENSE

MIT