How SSR Works with Turnstile
The library handles SSR automatically by:- Checking for
windowanddocumentavailability before accessing them - Deferring script injection until the client-side hydration
- Using React’s lifecycle methods to ensure proper timing
Next.js App Router
With Next.js 13+ App Router, you need to mark components using Turnstile as client components.Why ‘use client’?
Turnstile requires browser APIs likewindow and document to:
- Inject the Cloudflare script dynamically
- Render the widget into the DOM
- Handle user interactions
'use client' directive tells Next.js to render this component on the client side.
Next.js Pages Router
With the Pages Router, no special configuration is needed:Manual Script Injection
For better control over script loading in SSR environments, you can inject the script manually:Script Loading Strategies
Next.js provides several strategies for loading external scripts:beforeInteractive: Load before page becomes interactive (recommended for Turnstile)afterInteractive: Load after page becomes interactivelazyOnload: Load during idle time
Remix
In Remix, components are server-rendered by default. Mark your Turnstile component as client-only:ClientOnly component:
Handling Hydration Mismatches
If you encounter hydration warnings, ensure the component is only rendered on the client:Script Loading in SSR
The library automatically handles script injection, but you can monitor the loading state:Content Security Policy (CSP)
When using SSR with CSP headers, ensure you allow Cloudflare’s domains:next.config.js:
Server-Side Validation
After receiving the token on the client, validate it server-side:Best Practices
Always use 'use client' in Next.js App Router
Always use 'use client' in Next.js App Router
The Turnstile component requires browser APIs and must be a client component.
Prevent hydration mismatches
Prevent hydration mismatches
Use
useState and useEffect to ensure the component only renders on the client if you encounter issues.Use beforeInteractive for critical forms
Use beforeInteractive for critical forms
Load the Turnstile script early for forms that are immediately visible.
Configure CSP headers properly
Configure CSP headers properly
Include Cloudflare’s domains in your Content Security Policy.