Skip to content

Repository files navigation

@captchaapi/react

React hook for captchaapi.eu - EU-hosted, GDPR-compliant proof-of-work CAPTCHA. No cookies, no tracking, no Google.

Wraps the widget's programmatic window.captchaapi.solve() API with React state and unmount-safe abort handling. Built for controlled submit handlers in SPA setups such as Inertia, where the declarative data-captcha form attribute does not apply.

Why captchaapi.eu

  • EU-hosted (Hetzner Nuremberg) - GDPR-compliant by default, no data ever leaves the EU.
  • Proof-of-work - invisible to legitimate visitors, no friction puzzles to solve.
  • Server-side verification - your backend confirms each response with captchaapi.eu over a single call, secured by your secret key.

Requirements

  • React 18 or 19
  • The captcha.js widget loaded on the page (see below)

Installation

npm install @captchaapi/react

Load the widget once in your layout, before your app bundle:

<script>window.CAPTCHA_SITE_KEY = 'pk_live_...';</script>
<script src="https://captchaapi.eu/captcha.js" defer></script>

The site key is public and belongs in the browser. The secret key stays on your server and is only used to verify responses. Get both from the project dashboard.

If your site enforces a Content Security Policy, allow the widget and its API calls:

script-src https://captchaapi.eu;
connect-src https://captchaapi.eu;

Usage

Call solve() in your submit handler and send the resolved string to your backend as captchaapi_response:

import { useCaptcha } from '@captchaapi/react';

export default function ContactForm() {
    const { solve, solving, error } = useCaptcha();

    async function handleSubmit(event) {
        event.preventDefault();

        let response;
        try {
            response = await solve();
        } catch {
            return; // error state is set, render it below
        }

        // Add your framework's CSRF token here if the endpoint expects one
        // (Laravel: the X-XSRF-TOKEN header or a _token field).
        await fetch('/contact', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ captchaapi_response: response }),
        });
    }

    return (
        <form onSubmit={handleSubmit}>
            {error && <p>Verification failed ({error.code}), please try again.</p>}
            <button type="submit" disabled={solving}>Send</button>
        </form>
    );
}

With Inertia

Merge the response into the form payload via transform():

import { useForm } from '@inertiajs/react';
import { useCaptcha } from '@captchaapi/react';

export default function Newsletter() {
    const form = useForm({ email: '' });
    const { solve, solving } = useCaptcha();

    async function submit(event) {
        event.preventDefault();

        let response;
        try {
            response = await solve();
        } catch {
            return;
        }

        form
            .transform((data) => ({ ...data, captchaapi_response: response }))
            .post('/newsletter');
    }

    return (
        <form onSubmit={submit}>
            <input
                type="email"
                value={form.data.email}
                onChange={(event) => form.setData('email', event.target.value)}
            />
            {form.errors.captchaapi_response && <span>{form.errors.captchaapi_response}</span>}
            <button type="submit" disabled={form.processing || solving}>Subscribe</button>
        </form>
    );
}

On the Laravel side, validate the field with the captchaapi/laravel package and its ValidCaptcha rule. Validation failures land in form.errors like any other field, nothing Inertia-specific is needed on the server.

API

useCaptcha()

Returns an object with:

Property Type Description
solve () => Promise<string> Runs one challenge and PoW cycle, resolves with the captchaapi_response value. Rejects with a CaptchaError.
solving boolean True while a solve() call is in flight.
error CaptchaError | null Last error, cleared when the next solve() starts.

Each resolved value verifies exactly once on the server. Never reuse it across submissions - call solve() again for every submit.

An in-flight solve() is aborted automatically when the component unmounts or when solve() is called again before the previous call settled.

The hook is SSR-safe: it only touches window inside solve(), which runs from event handlers, never during render.

CaptchaError

Extends Error with:

Property Type Description
code string Widget error code, for example rate_limited, network_error, missing_site_key. widget_not_loaded means the captcha.js script tag is missing.
retryAfter number | null Seconds to wait when code is rate_limited, otherwise null.

Testing your components

Mock the widget global in your test setup:

window.captchaapi = {
    solve: vi.fn().mockResolvedValue('token.12345'),
};

Security

See SECURITY.md for how to report vulnerabilities. This package never handles your secret key; verification always happens on your server.

License

MIT, see LICENSE.

About

React hook for captchaapi.eu proof of work CAPTCHA

Topics

Resources

Security policy

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages