0

I am using sitecore 10.3XM SXA with HeadlessNextJs also we are using sitecore forms. We have a requirement to implement Google Recaptcha in our Forms.So We have created a Custom Google Recaptcha Field following this blog.

https://sitecorescientist.com/2018/11/11/sitecore-9-forms-part-2-google-recaptcha-field/

but after implementing this we are facing this issue

Google Recaptcha: No renderer for form element type {71266376-735C-4942-8B39-2456857EC7E6}

enter image description here

2
  • Welcome to SSE. You have referred .Net MVC implementation and you are using it in headless app. I doubt that it would work directly. You will need some implementation on front end as well. As per error, it can't find rendering implementation to render your recaptcha. Can you elaborate on your Form implementation ? Commented Oct 13, 2023 at 6:45
  • sure, we have created a jssForm in our nextjs App as a component and use this rendering in the sitecore to implement the form here is the code snippent for the jssForm const JssForm = ({ fields, router }: { fields: never; router: NextRouter }) => { return ( <Form form={fields} sitecoreApiHost={' '} sitecoreApiKey={sitecoreApiKey} onRedirect={(url) => router.push(url)} /> ); }; Commented Oct 13, 2023 at 11:20

1 Answer 1

2

Install react-google-recaptcha Package

To use the ReCAPTCHA component, we need to install the react-google-recaptcha package. Run the following command in your project directory:

npm install react-google-recaptcha

Adding reCAPTCHA to the Contact Form

In the component where you have implemented the contact form, add the reCAPTCHA widget to the form. Update your ContactUsForm.tsx component as follows:

//...(Existing imports)
import ReCAPTCHA from 'react-google-recaptcha';

//...(Sitecore fields)
const FORM_DEFAULT: {
  [key: string]: string;
} = {
  firstName: '',
  lastName: '',
  message: '',
    captchaToken: '',
};

const ContactUsForm = ({ fields }: ContactUsFormProps): JSX.Element => {
  const [formData, setFormData] = useState(FORM_DEFAULT);
  const [successMsgCss, setSuccesssMsg] = useState(false);
// Create a ref for the reCAPTCHA widget
  const recaptcha: RefObject<ReCAPTCHA> = useRef(null);
// ... (Existing functions)

const formSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
            formData.recipient = fields.emailRecipient.value;
      formData.emailSubject = fields.emailSubject.value;
      fetch('/api/contact', {
        method: 'POST',
        headers: {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      })
        .then((response) => {
          console.log('response recieved');
          if (response.status === 200) {
            console.log('response succeeded');
            setSuccesssMsg(true);
            setFormData(FORM_DEFAULT);
                        recaptcha?.current?.reset();// reset recaptcha after submission
          }
        })
        .catch((error) => {
          console.error(error);
        });
    }
  };

const onCaptchaChange = (token: string | null) => {
    // Set the captcha token when the user completes the reCAPTCHA
    if (token) {
      formData.captchaToken = token;
    }
  };
return (
{/* ... (existing TSX markup) */}
    <div className="pr-15px pl-25px pt-50px pb-25px mx-auto max-w-1200px w-full">
      <div>
    {/* ... (existing form fields) */}
  {/* Add the reCAPTCHA widget */}
    <div className="pb-20px">
          <ReCAPTCHA
            size="normal"
            sitekey="YOUR_RECAPTCHA_SITE_KEY"
            onChange={onCaptchaChange}
            ref={recaptcha}
          />
        </div>
{/* ... (existing submit button) */}
      </form>
    </div>

Server-Side Verification

Update your API route (/pages/api/contact.ts) to validate the reCAPTCHA token received from the frontend:

//...existing imports
import axios from 'axios';

export default async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
// ... (existing transporter setup and mailData)
// Validate the reCAPTCHA token on the server-side

try {
    const response = await axios.post(
      `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${req.body.captchaToken}`
    );
    if (response.data.success) {
//reCaptcha verification successfull
transporter.sendMail(mailData, function (err, info) {
        if (err) {
          console.log(err);
          res.status(500).send('Internal Server Error');
        } else {
          console.log('successful');
          console.log(info);
          res.status(200).end();
        }
      });
    } else {
      // reCAPTCHA verification failed
      res.status(400).send('reCAPTCHA verification failed.');
    }
  } catch (error) {
    console.error(error);
    res.status(500).send('Internal server error');
  }
}

More information you can find here: https://www.getfishtank.com/blog/securing-nextjs-contact-form-using-google-recaptcha

1
  • Thanks ! but we are using sitecore forms we don't have ContactUs.tsx Commented Oct 13, 2023 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.