### Install Svelte Turnstile
Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md
Install the svelte-turnstile package as a development dependency using npm.
```sh
npm install svelte-turnstile -D
```
--------------------------------
### Svelte Turnstile Component Usage
Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md
Demonstrates how to install and use the svelte-turnstile component in a Svelte application. It requires a siteKey obtained from Cloudflare.
```APIDOC
## Installation
```sh
npm install svelte-turnstile -D
```
## Basic Usage
The `Turnstile` component requires a `siteKey` prop. This key is obtained from your Cloudflare dashboard.
### Component
```svelte
{form?.error}
{/if} ``` ```javascript // Copy and paste the validateToken function from above here export const actions = { default: async ({ request }) => { const data = await request.formData(); const token = data.get('cf-turnstile-response'); // if you edited the formsField option change this const SECRET_KEY = '...'; // you should use $env module for secrets const { success, error } = await validateToken(token, SECRET_KEY); if (!success) return { error: error || 'Invalid CAPTCHA', }; // do something, the captcha is valid! }, }; ``` -------------------------------- ### Turnstile with Theme and Size Options Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Customize the appearance of the Turnstile widget using the 'theme' (light/dark/auto) and 'size' (normal/flexible/compact/invisible) props. The 'tabIndex' prop can be used to control focus order. ```svelte{form.error}
{/if} {#if form?.valid}Form submitted successfully!
{/if} ``` ```typescript import type { Actions } from './$types'; interface TokenValidateResponse { 'error-codes': string[]; success: boolean; action: string; cdata: string; } async function validateToken(token: string, secret: string) { const response = await fetch( 'https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ response: token, secret: secret }), }, ); const data: TokenValidateResponse = await response.json(); return { success: data.success, error: data['error-codes']?.length ? data['error-codes'][0] : null, }; } export const actions: Actions = { default: async ({ request }) => { const data = await request.formData(); const token = data.get('cf-turnstile-response') as string; const SECRET_KEY = process.env.TURNSTILE_SECRET_KEY; const { success, error } = await validateToken(token, SECRET_KEY); if (!success) { return { error: error || 'Invalid CAPTCHA' }; } // Process form data here return { valid: true }; }, }; ``` -------------------------------- ### HTML Form Integration Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Integrate Turnstile with traditional HTML forms to automatically include the verification token as a form field. Set 'responseField' to true and optionally specify 'responseFieldName'. ```svelte ``` -------------------------------- ### Zod Schema for Login Form Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md Defines the schema for the login form using Zod, including the required 'cf-turnstile-response' field. ```typescript import { z } from "zod"; export const schema = z.object({ ..., // other fields 'cf-turnstile-response': z.string().nonempty('Please complete turnstile') }); ``` -------------------------------- ### Svelte Component for Login Form with Turnstile Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md Integrates Svelte Turnstile into a Svelte component using SvelteKit Superforms. It binds to the reset function and captures the Turnstile token on callback. ```svelte ``` -------------------------------- ### Superforms Integration with Turnstile Component Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Integrate Turnstile within a sveltekit-superforms form. The `on:callback` event handler updates the form data with the Turnstile token, and `onUpdated` resets the widget. ```svelte {#if $message}{$message}
{/if} ``` -------------------------------- ### TypeScript Types for Svelte Turnstile Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Import and utilize TypeScript types provided by the svelte-turnstile library for Turnstile options like theme, size, and language. This enhances type safety and autocompletion during development. ```typescript import type { TurnstileTheme, TurnstileSize, TurnstileLanguage } from 'svelte-turnstile'; // Event types interface CallbackEvent { token: string; preClearanceObtained: boolean; } interface ErrorEvent { code: string; } ``` -------------------------------- ### Superforms Server-Side Validation with Turnstile Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Handle Turnstile token validation on the server using sveltekit-superforms. This function validates the token against the Turnstile API and returns success or error messages. ```typescript import { fail, message, setError, superValidate } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import { schema } from './schema'; async function validateToken(token: string, secret: string) { const response = await fetch( 'https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ response: token, secret: secret }), }, ); const data = await response.json(); return { success: data.success }; } export const load = async () => { const form = await superValidate(zod(schema)); return { form }; }; export const actions = { default: async ({ request }) => { const form = await superValidate(request, zod(schema)); if (!form.valid) return fail(400, { form }); const { success } = await validateToken( form.data['cf-turnstile-response'], process.env.TURNSTILE_SECRET_KEY, ); if (!success) { return setError( form, 'cf-turnstile-response', 'Invalid turnstile, please try again', ); } return message(form, 'Form submitted successfully!'); }, }; ``` -------------------------------- ### Superforms Integration with Turnstile Schema Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Define a Zod schema for Turnstile validation when using sveltekit-superforms. This ensures the Turnstile token is present and valid. ```typescript import { z } from 'zod'; export const schema = z.object({ name: z.string().min(1, 'Name is required'), email: z.string().email('Invalid email address'), 'cf-turnstile-response': z.string().nonempty('Please complete turnstile'), }); ``` -------------------------------- ### Server-Side Token Validation Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Validate the Turnstile token on your server by making a POST request to Cloudflare's siteverify endpoint. This function returns the validation success status and any error codes. ```typescript interface TokenValidateResponse { 'error-codes': string[]; success: boolean; action: string; cdata: string; } async function validateToken(token: string, secret: string) { const response = await fetch( 'https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', headers: { 'content-type': 'application/json', }, body: JSON.stringify({ response: token, secret: secret, }), }, ); const data: TokenValidateResponse = await response.json(); return { success: data.success, error: data['error-codes']?.length ? data['error-codes'][0] : null, }; } // Usage const { success, error } = await validateToken(token, 'YOUR_SECRET_KEY'); if (!success) { console.error('Validation failed:', error); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.