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-turnstile

v1.0.0

Published

Cloudflare Turnstile integration for Next.js applications

Downloads

382

Readme

Next-Turnstile

A type-safe, feature-rich integration of Cloudflare Turnstile for Next.js applications. This package provides both client and server-side components for seamless CAPTCHA integration.

npm version License: MIT

Features

  • 🔒 Type-safe: Full TypeScript support
  • 🎨 Customizable: Extensive styling and behavior options
  • 🧪 Sandbox Mode: Built-in support for development testing
  • Server Validation: Easy token verification
  • 📱 Responsive: Works across all device sizes
  • 🔄 Auto-reload: Configurable token refresh
  • 🌙 Theme Support: Light, dark, and auto themes
  • 🌐 i18n Ready: Multiple language support

Installation

# npm
npm install next-turnstile

# yarn
yarn add next-turnstile

# pnpm
pnpm add next-turnstile

# bun
bun add next-turnstile

Quick Start

Client-Side Usage

import { Turnstile } from "next-turnstile";

function MyForm() {
  const handleVerify = (token: string) => {
    // Handle the verification token
    console.log("Verification successful:", token);
  };

  return (
    <Turnstile siteKey="your-site-key" onVerify={handleVerify} theme="light" />
  );
}

Server-Side Validation

import { validateTurnstileToken } from "next-turnstile";

async function validateToken(token: string) {
  try {
    const result = await validateTurnstileToken({
      token,
      secretKey: process.env.TURNSTILE_SECRET_KEY,
    });

    if (result.success) {
      // Token is valid
      return true;
    }
  } catch (error) {
    console.error("Validation failed:", error);
  }
  return false;
}

API Reference

Turnstile Component Props

| Prop | Type | Default | Description | | ---------------- | --------------------------------------------- | -------------------- | ----------------------------------- | | siteKey | string | Required | Your Cloudflare Turnstile site key | | onVerify | (token: string) => void | - | Callback when verification succeeds | | onError | (error: unknown) => void | - | Callback when an error occurs | | onExpire | () => void | - | Callback when the token expires | | onLoad | () => void | - | Callback when the widget loads | | theme | 'light' \| 'dark' \| 'auto' | 'auto' | Widget theme | | size | 'normal' \| 'compact' | 'normal' | Widget size | | appearance | 'always' \| 'execute' \| 'interaction-only' | 'always' | When to show the widget | | retry | 'auto' \| 'never' | 'auto' | Retry behavior on failure | | retryInterval | number | 8000 | Milliseconds between retries | | refreshExpired | 'auto' \| 'manual' \| 'never' | 'auto' | Token refresh behavior | | language | string | - | Widget language code | | id | string | 'turnstile-widget' | Container element ID | | className | string | - | Additional CSS classes | | sandbox | boolean | false | Enable sandbox mode |

Server Validation Options

| Option | Type | Required | Description | | ---------------- | --------- | -------- | ------------------------- | | token | string | Yes | The token from the client | | secretKey | string | Yes | Your Turnstile secret key | | remoteip | string | No | User's IP address | | idempotencyKey | string | No | Unique request identifier | | sandbox | boolean | No | Enable sandbox mode |

Advanced Usage

With Form Submission

import { Turnstile } from "next-turnstile";

export default function Form() {
  const [token, setToken] = useState<string>();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token) return;

    const response = await fetch("/api/submit", {
      method: "POST",
      body: JSON.stringify({ token }),
      headers: { "Content-Type": "application/json" },
    });

    // Handle response...
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" required />
      <Turnstile
        siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY!}
        onVerify={setToken}
      />
      <button type="submit" disabled={!token}>
        Submit
      </button>
    </form>
  );
}

Server Action Validation

import { validateTurnstileToken } from "next-turnstile";

async function submitForm(formData: FormData) {
  "use server";

  const token = formData.get("cf-turnstile-response");
  if (!token || typeof token !== "string") {
    return { error: "No token provided" };
  }

  const result = await validateTurnstileToken({
    token,
    secretKey: process.env.TURNSTILE_SECRET_KEY!,
  });

  if (!result.success) {
    return { error: "Invalid token" };
  }

  // Process form submission...
}

Development Mode

During development, you can use sandbox mode to test without real credentials:

<Turnstile
  siteKey="1x00000000000000000000AA"
  sandbox={process.env.NODE_ENV === "development"}
  onVerify={handleVerify}
/>

Dark Mode Support

<Turnstile
  siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY!}
  theme="dark"
  onVerify={handleVerify}
/>

With Custom Styling

<Turnstile
  siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY!}
  className="my-turnstile-widget"
  onVerify={handleVerify}
/>

<style>
  .my-turnstile-widget {
    margin: 1rem 0;
    /* Note: Internal widget styling is limited by Turnstile */
  }
</style>

Development and Contributing

  1. Clone the repository
  2. Install dependencies:
    pnpm install
  3. Start development:
    pnpm dev

License

MIT © Jed Patterson

Credits

Built with ❤️ using: