@@ -104,7 +104,7 @@ async function validateToken(token: string, secret: string) {
104104}
105105```
106106
107- ## SvelteKit Example
107+ ## SvelteKit Example (Svelte 5)
108108
109109In SvelteKit we can use form actions to easily setup a form with a captcha:
110110
@@ -150,6 +150,87 @@ export const actions = {
150150};
151151```
152152
153+ ## Superforms Example (Svelte 5)
154+
155+ ` routes/login/schema.ts `
156+
157+ ``` ts
158+ import { z } from " zod" ;
159+
160+ export const schema = z .object ({
161+ ... , // other fields
162+ " cf-turnstile-response" : z .string ().nonempty (' Please complete turnstile' )
163+ });
164+ ```
165+
166+ ` routes/login/+page.svelte `
167+
168+ ``` svelte
169+ <script lang="ts">
170+ import { zodClient } from 'sveltekit-superforms/adapters';
171+ import { superForm } from 'sveltekit-superforms';
172+ import { Turnstile } from 'svelte-turnstile';
173+ import { schema } from './schema.ts';
174+
175+ let { data } = $props();
176+
177+ // Call this to reset the turnstile
178+ let reset = $state<() => void>();
179+
180+ const { enhance, message } = superForm(data.form, {
181+ validators: zodClient(schema),
182+ onUpdated() {
183+ // When the form is updated, we reset the turnstile
184+ reset?.();
185+ },
186+ });
187+ </script>
188+
189+ <form method="POST" use:enhance>
190+ <Turnstile
191+ siteKey={PUBLIC_TURNSTILE_SITE_KEY}
192+ bind:reset />
193+ </form>
194+ ```
195+
196+ ` routes/login/+page.server.js `
197+
198+ ``` js
199+ import { fail , message , setError , superValidate } from ' sveltekit-superforms' ;
200+ import { zod } from ' sveltekit-superforms/adapters' ;
201+ import { schema } from ' ./schema.ts' ;
202+
203+ export const load = async () => {
204+ const form = await superValidate (zod (schema));
205+ return { form };
206+ };
207+
208+ export const actions = {
209+ default: async ({ request }) => {
210+ const form = await superValidate (request, zod (schema));
211+ if (! form .valid ) return fail (400 , { form });
212+
213+ const { success } = await validateToken (
214+ form .data [' cf-turnstile-response' ],
215+ SECRET_KEY
216+ );
217+
218+ if (! success) {
219+ return setError (
220+ form,
221+ ' cf-turnstile-response' ,
222+ ' Invalid turnstile, please try again' ,
223+ );
224+ }
225+
226+ return message (form, ' Success!' );
227+ },
228+ };
229+
230+ ```
231+
232+ This example uses the [ Superforms onUpdated event] ( https://superforms.rocks/concepts/events ) to reset the Turnstile widget. Additionally, it automatically adds the Turnstile response token to the form data.
233+
153234# Resetting
154235
155236If you need to manually reset the widget, you can do so by binding to the ` reset ` prop. For example:
0 commit comments