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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@captigo/react

v0.2.0

Published

React 18+ components and hooks for Captigo — works with any CAPTCHA adapter

Readme

@captigo/react

React 18+ hooks and components for Captigo.

Provider-agnostic widgets: pass any CaptchaAdapter from @captigo/turnstile, @captigo/hcaptcha, or @captigo/recaptcha.


Installation

npm install @captigo/react @captigo/turnstile

@captigo/core is installed transitively via the adapter. Peer dependencies: react and react-dom 18+.


Quick start

Managed widget (visible, fires automatically)

For most use cases you just need the <Captcha> component. Create an adapter from your provider package and pass it as a prop — the component handles the full mount/unmount lifecycle.

import { Captcha } from "@captigo/react";
import { turnstile } from "@captigo/turnstile";
import { useState } from "react";

// Create the adapter once, outside the component.
const adapter = turnstile({ siteKey: "0x4AAAAAAA..." });

export function ContactForm() {
  const [token, setToken] = useState<string | null>(null);

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      if (!token) return;
      submitForm(token);
    }}>
      <input name="email" type="email" />

      <Captcha
        adapter={adapter}
        onSuccess={(t) => setToken(t.value)}
        onExpire={() => setToken(null)}
      />

      <button type="submit" disabled={!token}>
        Send
      </button>
    </form>
  );
}

Interactive / invisible widget

For invisible CAPTCHAs (e.g. Turnstile with execution: "execute"), use a ref to get the CaptchaHandle and call execute() imperatively on submit.

import { Captcha } from "@captigo/react";
import type { CaptchaHandle } from "@captigo/react";
import { turnstile } from "@captigo/turnstile";
import { useRef } from "react";

const adapter = turnstile({
  siteKey: "0x4AAAAAAA...",
  execution: "execute", // invisible widget
});

export function LoginForm() {
  const captchaRef = useRef<CaptchaHandle>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Triggers the invisible challenge; resolves when done.
    const token = await captchaRef.current!.execute("login");

    await fetch("/api/login", {
      method: "POST",
      body: JSON.stringify({ token: token.value, ...formData }),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="username" />
      <input name="password" type="password" />

      {/* Invisible widget — renders nothing visible */}
      <Captcha ref={captchaRef} adapter={adapter} />

      <button type="submit">Log in</button>
    </form>
  );
}

Error and expiry handling

Use onError and onExpire to keep the UI in sync with the widget state. onExpire fires both when an issued token expires and when the challenge presentation times out.

<Captcha
  adapter={adapter}
  onSuccess={(t) => setToken(t.value)}
  onError={(err) => {
    console.error(err.code, err.message);
    setStatus("The CAPTCHA failed. Please try again.");
  }}
  onExpire={() => {
    setToken(null);
    setStatus("Token expired. Please complete the challenge again.");
  }}
/>

useCaptcha hook

Use the hook when you need direct access to the container ref (e.g. custom layouts) or want the token in component state without the <Captcha> wrapper.

import { useCaptcha } from "@captigo/react";
import { turnstile } from "@captigo/turnstile";

const adapter = turnstile({ siteKey: "0x4AAAAAAA..." });

export function CheckoutWidget() {
  const { containerRef, token, execute, reset } = useCaptcha(adapter, {
    onSuccess: (t) => console.log("Token:", t.value),
    onExpire: () => console.log("Token expired"),
  });

  return (
    <div>
      {/* Attach this ref to any div — the widget renders into it. */}
      <div ref={containerRef} />

      <p>{token ? "✓ Verified" : "Solve the challenge above"}</p>

      <button onClick={() => execute("checkout")} disabled={!!token}>
        Trigger challenge
      </button>

      <button onClick={reset}>Reset</button>
    </div>
  );
}

Server-side verification

Displaying a CAPTCHA is only half of the story — you must verify the token server-side before trusting it. This step is handled by the provider adapter, not by this React package.

// In an API route / server action:
import { adapter } from "./captcha.js"; // your shared adapter instance

export async function POST(request: Request) {
  const { token } = await request.json() as { token: string };

  const result = await adapter.verify(token, process.env.TURNSTILE_SECRET!);
  if (!result.success) {
    return Response.json({ error: "CAPTCHA failed" }, { status: 400 });
  }

  // Process the verified request...
}

See the @captigo/turnstile README for provider-specific verification options.

For Next.js App Router route handlers, consider @captigo/nextjs.


API reference

<Captcha>

<Captcha
  adapter={adapter}           // required: any CaptchaAdapter
  onSuccess={(token) => {}}   // called with CaptchaToken when solved
  onError={(err) => {}}       // called with CaptchaError on failure
  onExpire={() => {}}         // called when the token expires
  className="..."             // forwarded to the container <div>
  style={{...}}               // forwarded to the container <div>
  id="my-captcha"             // forwarded to the container <div>
  ref={captchaRef}            // optional: attach for imperative control
/>

CaptchaHandle (ref)

When a ref is attached, you get access to:

| Method | Description | |---|---| | execute(action?) | Trigger the challenge. Returns Promise<CaptchaToken>. | | reset() | Reset to unsolved state. | | getToken() | Returns the current CaptchaToken \| null. |


useCaptcha(adapter, options?)

const { containerRef, token, execute, reset } = useCaptcha(adapter, {
  onSuccess?: (token: CaptchaToken) => void,
  onError?: (error: CaptchaError) => void,
  onExpire?: () => void,
});

Returns:

| Property | Type | Description | |---|---|---| | containerRef | RefObject<HTMLDivElement> | Attach to the widget container <div>. | | token | CaptchaToken \| null | Current token. Triggers re-render on change. | | execute | (action?) => Promise<CaptchaToken> | Trigger the challenge. | | reset | () => void | Reset to unsolved state and clear the token. |


Important notes

Adapter identity

The adapter is used as the dependency in a useEffect. If you create the adapter inline inside a component, a new adapter is created on every render, which causes the widget to be destroyed and remounted on every render.

// ✗ Bad — new adapter on every render
function Form() {
  return <Captcha adapter={turnstile({ siteKey: "..." })} />;
}

// ✓ Good — stable adapter outside the component
const adapter = turnstile({ siteKey: "..." });
function Form() {
  return <Captcha adapter={adapter} />;
}

// ✓ Also good — useMemo for dynamic configs
function Form({ siteKey }: { siteKey: string }) {
  const adapter = useMemo(() => turnstile({ siteKey }), [siteKey]);
  return <Captcha adapter={adapter} />;
}

Callback identity

Unlike the adapter, onSuccess, onError, and onExpire callbacks can be passed as inline functions — they are stored in a ref internally and will not cause widget remounts.

React Strict Mode

The package is compatible with React Strict Mode. In development, effects run twice; the widget is destroyed and remounted, which is expected and harmless.


Documentation

@captigo/turnstile · Repository · Issues