ghostdevv / svelte-turnstile

A lightweight Svelte component for Cloudflare Turnstile
https://svelte-turnstile.pages.dev/
MIT License
163 stars 10 forks source link

Turnstile + Svelte Kit + Svelte forms lib #8

Closed gaurishhs closed 1 year ago

gaurishhs commented 1 year ago

Hi! I'm usign SvelteKit and Svelte forms lib and i'm unable to get the cf-turnstile-response field in the handleSubmit function.. What can i do?

ghostdevv commented 1 year ago

I am not familiar with that library myself, do you have an example of how you are trying to use it with Turnstile? @gaurishhs

gaurishhs commented 1 year ago

Its a simple library you can just copy paste any code snippet from their website and try using Turnstile with it the snippets can be found here https://svelte-forms-lib-sapper-docs.vercel.app/

ghostdevv commented 1 year ago

I took a look and you are right it doesn't seem to pick up the cf-turnstile-response field. You should make an issue on that library's GitHub for that.

As a workaround you can use the turnstile-callback event:

<script lang="ts">
    let turnstileResponse: string | undefined;

    const { form, handleChange, handleSubmit } = createForm({
      onSubmit: values => {
        // use turnstileResponse
        // ...
      }
    });
</script>

<form //... >
    <Turnstile on:turnstile-callback={event => turnstileResponse = event.detail.token} />
    // ...
</form>

Alternatively you can bind the form element to a variable and then get the token off that, for example:

<script lang="ts">
    let formElement: HTMLFormElement;

    function getTurnstileResponse(form: HTMLFormElement) {
        const data = new FormData(form);
        return data.get('cf-turnstile-response') ?? undefined;
    }

    const { form, handleChange, handleSubmit } = createForm({
      onSubmit: values => {
        const response = getTurnstileResponse(formElement);
        // ...
      }
    });
</script>

<form bind:this={formElement} ...
gaurishhs commented 1 year ago

Thanks...