reCAPTCHA v. 3 returning the same token on the second calls with different action

222 views Asked by At

I'm using Google's reCAPTCHA v.3 in a React application and I've encountered an issue where window.grecaptcha.enterprise.execute(reCaptchaKey, { action }) returns the same token on the second call even when the action changes. However, on the third call, it returns a new token as expected.

Here's a snippet of my code:

export const useReCaptcha = ({ reCaptchaKey, action, isSubmit }: UseReCaptchaProps): string => {
  const [token, setToken] = useState<string>('');
  const [scriptLoaded, setScriptLoaded] = useState<boolean>(false);

  useEffect(() => {
    const script = document.createElement('script');
    script.src = `https://www.google.com/recaptcha/enterprise.js?render=${reCaptchaKey}`;
    script.onload = () => {
      setScriptLoaded(true);
    };
    script.onerror = () => {
      console.error('Failed to load reCAPTCHA script');
      setToken(RECAPTCHA_ERROR_MESSAGE);
    };
    document.head.appendChild(script);

    return () => {
      document.head.removeChild(script);
    };
  }, []);

  useEffect(() => {
    if (isSubmit && scriptLoaded) {
      setToken('');
      window.grecaptcha.enterprise.ready(async () => {
        try {
          const reCaptchaToken = await window.grecaptcha.enterprise.execute(reCaptchaKey, { action });
          setToken(reCaptchaToken);
        } catch (error) {
          console.error(error);
          setToken(RECAPTCHA_ERROR_MESSAGE);
        }
      });
    }
  }, [isSubmit, scriptLoaded, reCaptchaKey, action]);

  return token;
};

I've ensured that the action is unique for each call, but I'm still getting the same token on the second call. Is there a workaround for this issue? Any help would be appreciated.

0

There are 0 answers