Le0Developer / react-turnstile

A very simple React library for Cloudflare Turnstile.
https://turnstile-demo.pages.dev/
MIT License
106 stars 15 forks source link

How to use the Turnstile component correctly #22

Closed NickWoodward closed 9 months ago

NickWoodward commented 9 months ago

Hi,

Sorry to be a pain, but I'm struggling to understand how the example code works and was hoping you had a spare moment to help me out please?

Afaik the turnstile element normally injects a key value pair into the form object, and then it gets validated on the server. Is the /turnstile route here that same route that the form would have been submitted to? IE should I be adding more form data to the request body?

Thanks, appreciate any time you might be able to spare!

Nick


      sitekey="1x00000000000000000000AA"
      onVerify={(token) => {
        fetch("/turnstile", {
          method: "POST",
          body: JSON.stringify({ token }),
        }).then((response) => {
          if (!response.ok) turnstile.reset();
        });
      }}
    />```
Le0Developer commented 9 months ago

The example is for standalone usage - outside of a form. You can still use it in a form as you usually would.

NickWoodward commented 9 months ago

Ah, so I can remove that onVerify function, place the component inside my form, and it should inject the cf-token-response key/value pair into the FormData as usual?

Le0Developer commented 9 months ago

Yes

NickWoodward commented 9 months ago

Yeah I just tested it out and it worked great. Thank you so much for creating this :)

NickWoodward commented 9 months ago

Ah, I may have jumped the gun, it's actually not adding the token as I thought, I made a mistake :/

So you're saying this should work, right?

import Turnstile, { useTurnstile } from "react-turnstile";

export const TurnstileWidget = () => {
  const turnstile = useTurnstile();
  return (
    <Turnstile
      sitekey="1x00000000000000000000AA"
    />
  );
};

  <form onSubmit={(e) => {e.preventDefault(); onNext()}} >
    <Summary/>
    <Button 
      type="submit" 
    >
      Submit
    </Button>
    <TurnstileWidget />
  </form>;```
Le0Developer commented 9 months ago

That should work. The form may be submitted before the Turnstile challenge was solved or your onNext function may not pick up the input element for some reason.