Skip to content

fix: Prevent Turnstile widget from constantly reloading #142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions app/create/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import { Turnstile } from "@/components/ui/turnstile";
export default function CreateGistPage() {
// Get Turnstile site key - safe to use on client as it's a public key
const turnstileSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;
console.log("Turnstile Site Key:", turnstileSiteKey);
const router = useRouter();
const multiFileEditorRef = useRef<MultiFileEditorHandle>(null);
const [files, setFiles] = useState<FileData[]>(() => [
Expand Down Expand Up @@ -330,7 +329,6 @@ export default function CreateGistPage() {
onVerify={(token) => {
setTurnstileToken(token);
setIsTurnstileReady(true);
// Don't clear errors here - let them persist
}}
onError={() => {
setError(
Expand Down
21 changes: 18 additions & 3 deletions components/ui/turnstile.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ describe("Turnstile", () => {
expect.any(HTMLElement),
expect.objectContaining({
sitekey: "test-site-key",
callback: mockOnVerify,
"error-callback": mockOnError,
"expired-callback": mockOnExpire,
callback: expect.any(Function),
"error-callback": expect.any(Function),
"expired-callback": expect.any(Function),
theme: "auto",
size: "normal",
})
Expand All @@ -63,6 +63,21 @@ describe("Turnstile", () => {
// Check container exists
const turnstileContainer = container.querySelector(".cf-turnstile");
expect(turnstileContainer).toBeInTheDocument();

// Test that callbacks are properly forwarded
const renderCall = mockRender.mock.calls[0][1];

// Test onVerify callback
renderCall.callback("test-token");
expect(mockOnVerify).toHaveBeenCalledWith("test-token");

// Test onError callback
renderCall["error-callback"]("test-error");
expect(mockOnError).toHaveBeenCalledWith("test-error");

// Test onExpire callback
renderCall["expired-callback"]();
expect(mockOnExpire).toHaveBeenCalled();
});

it("applies custom theme and size", async () => {
Expand Down
38 changes: 20 additions & 18 deletions components/ui/turnstile.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState, memo } from "react";
import Script from "next/script";
import { cn } from "@/lib/utils";

Expand Down Expand Up @@ -34,7 +34,7 @@ declare global {
}
}

export function Turnstile({
export const Turnstile = memo(function Turnstile({
sitekey,
onVerify,
onError,
Expand All @@ -46,33 +46,34 @@ export function Turnstile({
const containerRef = useRef<HTMLDivElement>(null);
const widgetIdRef = useRef<string | null>(null);
const [isScriptLoaded, setIsScriptLoaded] = useState(false);
const isRenderedRef = useRef(false);

// Store callbacks in refs to avoid re-renders
const callbacksRef = useRef({ onVerify, onError, onExpire });
useEffect(() => {
if (!isScriptLoaded || !containerRef.current) return;
callbacksRef.current = { onVerify, onError, onExpire };
});

// Clean up any existing widget
if (widgetIdRef.current && window.turnstile) {
try {
window.turnstile.remove(widgetIdRef.current);
} catch {
// Widget might already be removed
}
}
useEffect(() => {
if (!isScriptLoaded || !containerRef.current || isRenderedRef.current)
return;

// Render new widget
// Render widget only once
if (window.turnstile && containerRef.current) {
try {
widgetIdRef.current = window.turnstile.render(containerRef.current, {
sitekey,
callback: onVerify,
"error-callback": onError,
"expired-callback": onExpire,
callback: (token: string) => callbacksRef.current.onVerify(token),
"error-callback": (error: string) =>
callbacksRef.current.onError?.(error),
"expired-callback": () => callbacksRef.current.onExpire?.(),
theme,
size,
});
isRenderedRef.current = true;
} catch (error) {
console.error("Failed to render Turnstile widget:", error);
onError?.("Failed to load verification widget");
callbacksRef.current.onError?.("Failed to load verification widget");
}
}

Expand All @@ -84,9 +85,10 @@ export function Turnstile({
} catch {
// Widget might already be removed
}
isRenderedRef.current = false;
}
};
}, [isScriptLoaded, sitekey, onVerify, onError, onExpire, theme, size]);
}, [isScriptLoaded, sitekey, theme, size]);

return (
<>
Expand All @@ -108,4 +110,4 @@ export function Turnstile({
/>
</>
);
}
});