title: Next.js how to implement react-google-recaptcha in my contact form
body: <p>I am trying to implement Google Recaptcha on my contact form in Next.js. It does popup the challenge when needed, but sends the form anyway.
  Here's my code so far:</p>
  <pre><code>  // Recaptcha
    const recaptchaRef = useRef();
  
    // Form validation
    const [validated, setValidated] = useState(false);
  
    // Reset form
    const formRef = useRef();
    const handleReset = () =&gt; {
      formRef.current.reset();
      setValidated(false);
    };
  
    // Thank you Message
    const [thankYouMessage, setThankYouMessage] = useState(false);
  
    // Form submit handler
    async function handleSubmit(e) {
      e.preventDefault();
      e.stopPropagation();
  
      // Execute the reCAPTCHA when the form is submitted
      recaptchaRef.current.execute();
  
      const formData = new FormData();
  
      Array.from(e.currentTarget.elements).forEach((field) =&gt; {
        if (!field.name) return;
        formData.append(field.name, field.value);
      });
  
      await fetch(process.env.NEXT_PUBLIC_WORDPRESS_CF7_ENDPOINT, {
        body: formData,
        method: &quot;POST&quot;,
      })
        .then((response) =&gt; response.json())
        .then((response) =&gt; {
          if (response.status === &quot;mail_sent&quot;) {
            setThankYouMessage(!thankYouMessage);
          } else if (response.status === &quot;mail_failed&quot;) {
            alert(&quot;Message failed to send.&quot;);
          }
        });
  
      setValidated(true);
      handleReset();
      recaptchaRef.current.reset();
    }
  </code></pre>
  <p>And on the form:</p>
  <pre><code>  &lt;Form
      ref={formRef}
      validated={validated}
      onSubmit={handleSubmit}
    &gt;
      &lt;ReCAPTCHA
        ref={recaptchaRef}
        size=&quot;invisible&quot;
        sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
      /&gt;
  </code></pre>
  <p>This of course does not work because it sends the form anyway even if the recaptcha gets triggered.</p>
  <p>I've tried adding <code>onChange={onReCAPTCHAChange}</code> on <code>&lt;ReCAPTCHA /&gt;</code> but then get an error <code>Uncaught (in promise) ReferenceError</code>:</p>
  <pre><code>  const onReCAPTCHAChange = (captchaCode) =&gt; {
      // If the reCAPTCHA code is null or undefined indicating that
      // the reCAPTCHA was expired then return early
      if (!captchaCode) {
        return;
      }
      // Else reCAPTCHA was executed successfully so proceed with the
      // alert
      alert(`Hey, ${email}`);
      // Reset the reCAPTCHA so that it can be executed again if user
      // submits another email.
      recaptchaRef.current.reset();
    };
  </code></pre>