### 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 ``` ### Props | Prop | Type | Description | Required | | ------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------- | | `siteKey` | `string` | sitekey for your website | ✅ | | `theme` | `'light' | 'dark' | 'auto'` | colour theme of the widget (defaults to `auto`) | | | `size` | `'normal' | 'flexible' | 'invisible' | 'compact'` | size of the widget (defaults to `normal`) | | | `action` | `string` | A string that can be used to differentiate widgets, returned on validation | | | `cData` | `string` | A string that can attach customer data to a challange, returned on validation | | | `tabIndex` | `number` | Used for accessibility (defaults to `0`) | | | `responseField` | `boolean` | if true the response token will be a property on the form data (default `true`) | | | `responseFieldName` | `string` | the `name` of the input which will appear on the form data (default `cf-turnstile-response`) | | | `retry` | `'auto' | 'never'` | should the widget automatically retry to obtain a token if it did not succeed (default `auto`) | | | `retryInterval` | `number` | if `retry` is true, this controls the time between attempts in milliseconds (default `8000`) | | | `language` | `SupportedLanguage | 'auto'` | the language turnstile should use (default `auto`) | | | `execution` | `'render' | 'execute'` | controls when to obtain the token of the widget (default `render`) | | | `appearance` | `'always' | 'execute' | 'interaction-only'` | controls when the widget is visible. (default `always`) | | For more information about some of the props and a list of `SupportedLanguage`'s [checkout the Cloudflare Documentation](https://developers.cloudflare.com/turnstile/get-started/client-side-rendering/#configurations). ### Deprecated Props - `forms` renamed to `responseField` - `formsField` renamed to `responseFieldName` ``` -------------------------------- ### Validate Turnstile Token Server-Side Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md Use this function to verify the Turnstile token on your backend. It requires the token and your secret key. Ensure your secret key is handled securely, for example, using environment variables. ```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 { // Return the status success: data.success, // Return the first error if it exists error: data['error-codes']?.length ? data['error-codes'][0] : null, }; } ``` -------------------------------- ### SvelteKit Server Load and Actions for Login Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md Handles form loading and submission on the server. It validates the Turnstile token using a secret key before processing the form data. ```javascript import { fail, message, setError, superValidate } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import { schema } from './schema.ts'; 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'], SECRET_KEY, ); if (!success) { return setError( form, 'cf-turnstile-response', 'Invalid turnstile, please try again', ); } return message(form, 'Success!'); }, }; ``` -------------------------------- ### Use Cloudflare Test Site Keys Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Utilize these predefined test site keys from Cloudflare to simulate different Turnstile scenarios during development. This allows testing of always-passing, always-blocking, and interactive challenge modes without affecting production. ```svelte ``` -------------------------------- ### Basic Turnstile Component Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Render the Turnstile verification widget with automatic script loading and token management. Ensure you replace 'YOUR_SITE_KEY' with your actual Cloudflare Turnstile site key. ```svelte ``` -------------------------------- ### Basic Svelte Turnstile Integration Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md Import and use the Turnstile component in your Svelte application. Ensure you replace 'SITE_KEY' with your actual Cloudflare Turnstile site key. ```svelte ``` -------------------------------- ### SvelteKit Login Form with Turnstile Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md Integrate Turnstile into a SvelteKit login form using form actions. The `cf-turnstile-response` is automatically submitted with the form data. The server-side action then calls the `validateToken` function. ```svelte {#if form?.error}

{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 ``` -------------------------------- ### Configure Turnstile Component Properties Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Use this snippet to configure various properties of the Turnstile component, such as theme, size, execution mode, appearance, retry behavior, language, action, custom data, and event callbacks. Ensure you replace 'YOUR_SITE_KEY' with your actual Cloudflare site key. ```svelte console.log('Token:', e.detail.token)} on:error={(e) => console.error('Error:', e.detail.code)} on:before-interactive={() => console.log('Challenge starting')} on:after-interactive={() => console.log('Challenge completed')} on:unsupported={() => console.log('Browser not supported')} /> ``` -------------------------------- ### Manually Resetting Svelte Turnstile Source: https://github.com/ghostdevv/svelte-turnstile/blob/main/README.md Demonstrates how to manually reset the Turnstile widget by binding to the 'reset' prop and calling it from a button click. ```svelte ``` -------------------------------- ### Turnstile with Event Callbacks Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Handle various Turnstile verification events such as successful verification, errors, timeouts, and token expiration using Svelte's event handling. The 'callback' event provides the verification token and pre-clearance status. ```svelte ``` -------------------------------- ### SvelteKit Form Actions with Turnstile Source: https://context7.com/ghostdevv/svelte-turnstile/llms.txt Use this for basic server-side validation of Turnstile tokens within SvelteKit's form actions. Ensure your TURNSTILE_SECRET_KEY is set in your environment variables. ```svelte {#if form?.error}

{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
{ // Required when using client side validation $form['cf-turnstile-response'] = event.detail.token; }} /> ``` -------------------------------- ### 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
{ $form['cf-turnstile-response'] = event.detail.token; }} /> {#if $errors['cf-turnstile-response']} {$errors['cf-turnstile-response']} {/if} {#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.