'use client' import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react' /** Minimal shape of the global Turnstile API we rely on. */ interface TurnstileApi { render: (element: HTMLElement, options: Record) => string reset: (widgetId?: string) => void remove: (widgetId?: string) => void } declare global { // eslint-disable-next-line no-var interface Window { turnstile?: TurnstileApi } } const SCRIPT_SRC = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit' let scriptPromise: Promise | null = null function loadTurnstileScript(): Promise { if (typeof window === 'undefined') return Promise.resolve() if (window.turnstile) return Promise.resolve() if (scriptPromise) return scriptPromise scriptPromise = new Promise((resolve, reject) => { const existing = document.querySelector( `script[src="${SCRIPT_SRC}"]` ) if (existing) { existing.addEventListener('load', () => resolve()) existing.addEventListener('error', () => reject(new Error('Turnstile failed to load'))) return } const script = document.createElement('script') script.src = SCRIPT_SRC script.async = true script.defer = true script.onload = () => resolve() script.onerror = () => reject(new Error('Turnstile failed to load')) document.head.appendChild(script) }) return scriptPromise } export interface TurnstileHandle { reset: () => void } export interface TurnstileProps { siteKey: string onVerify: (token: string) => void onExpire?: () => void onError?: () => void appearance?: 'always' | 'execute' | 'interaction-only' /** Widget language. Defaults to `'auto'`. */ language?: string className?: string } /** * Self-contained Cloudflare Turnstile widget. Loads the CF script once * (explicit-render mode), mounts the widget, and exposes `reset()` via ref. * No design-system dependency. */ export const Turnstile = forwardRef(function Turnstile( { siteKey, onVerify, onExpire, onError, appearance, language, className }, ref ) { const containerRef = useRef(null) const widgetIdRef = useRef(null) // Always call the latest callbacks without re-rendering the widget. const callbacksRef = useRef({ onVerify, onExpire, onError }) callbacksRef.current = { onVerify, onExpire, onError } useImperativeHandle( ref, () => ({ reset: () => { if (widgetIdRef.current && window.turnstile) { window.turnstile.reset(widgetIdRef.current) } }, }), [] ) useEffect(() => { let cancelled = false loadTurnstileScript() .then(() => { if (cancelled || widgetIdRef.current) return if (!containerRef.current || !window.turnstile) return widgetIdRef.current = window.turnstile.render(containerRef.current, { sitekey: siteKey, callback: (token: string) => callbacksRef.current.onVerify(token), 'expired-callback': () => callbacksRef.current.onExpire?.(), 'error-callback': () => callbacksRef.current.onError?.(), appearance: appearance ?? 'always', language: language ?? 'auto', }) }) .catch(() => callbacksRef.current.onError?.()) return () => { cancelled = true if (widgetIdRef.current && window.turnstile) { try { window.turnstile.remove(widgetIdRef.current) } catch { /* widget already gone */ } widgetIdRef.current = null } } }, [siteKey, appearance, language]) return
})