How jedpattersonn/next-turnstile works
Project Type and Purpose
• Type: Open-source npm package (not a standalone app).
• Purpose: Provide a type-safe React component (Turnstile) for embedding the Cloudflare Turnstile widget in Next.js apps, plus a server helper (validateTurnstileToken) for verifying tokens with Cloudflare.
File Structure
• src/client/Turnstile.tsx – the React component that:
– loads the external Turnstile script,
– renders the widget,
– handles lifecycle callbacks (onLoad, onVerify, onError, etc.).
• src/server/validate.ts – a helper that:
– constructs and sends the HTTP POST to Cloudflare’s site-verify endpoint,
– processes the JSON response (success, score, challenge_ts, hostname, etc.).
• src/types.ts – shared TypeScript types for component props and validation options/results.
• src/index.ts – single entry point that re-exports Turnstile and validateTurnstileToken.
• Config/build files (tsconfig.json, package.json, etc.) confirm it’s a library package.
Extract Architecture Insights from README
• Client-side usage is embedded in user’s Next.js pages or components.
• Server-side can be used in API routes or Next.js “server actions.”
• External dependency: Cloudflare Turnstile service (script + verification API).
Main Components & Interactions
a. Browser / Next.js Frontend
– Imports Turnstile component from this library.
– When rendered, the component loads Cloudflare’s script from https://challenges.cloudflare.com/turnstile/v0/api.js.
– Widget displays CAPTCHA; on success it emits a token via onVerify(token).
– The host application uses that token (e.g., stores in state, includes in form).
b. Next.js Server (API Route or Server Action)
– Receives the token from the client (e.g., via POST).
– Imports and calls validateTurnstileToken({ token, secretKey, … }).
– That function wraps a fetch to Cloudflare’s siteverify endpoint (https://challenges.cloudflare.com/turnstile/v0/siteverify).
– Returns a result object { success: boolean, … } back to the application logic.
c. External Service
– Cloudflare Turnstile
• Script delivery and widget host.
• Server-side verification API.
Architectural Patterns & Design Principles
• Separation of Concerns – client widget vs. server validation.
• Type Safety – shared TypeScript types for props and API responses.
• Pluggable Integration – consumers can style and hook into all lifecycle callbacks.
• Single Responsibility – Turnstile only handles UI and token generation; validateTurnstileToken only handles remote verification.