DEV Community

Cover image for Contact form and CAPTCHA backend in Open Source Cloud
Jonas Birmé
Jonas Birmé

Posted on

Contact form and CAPTCHA backend in Open Source Cloud

With an open source backend service for form collection and CAPTCHA handling you can implement a contact form with spam protection without developing your own backend services for this. These backend services are also available in Open Source Cloud so you don't have to host these backend services yourself either.

In this blog I will describe how you can quickly get a contact form where the message is sent to a Slack channel.

Image description

Create a Slack Bot

The Slack Bot will be the one posting the message to the channel in Slack. Visit https://api.slack.com/apps/ and create a new app with the permissions to post to the desired Slack channel.

Save the Slack Bot token as this will be used later in this tutorial.

Create form backend service in Open Source Cloud

Login to or signup for an account at Open Source Cloud.

Navigate to the Contact Form Service and click on the tab Service Secrets. Click on New Secret and add a secret that contains the Slack Bot token obtained earlier.

Image description

Create a contact form service by pressing the Create service button.

Image description

Give the service a name and select slack in the transport dropdown. Provide the service secret holding the token and enter the ID of the channel where the message should be posted.

Image description

When the service is up and running you can copy and save the URL to the contact form service.

Contact form example in React

Develop your contact form in your frontend application which in React could look something like this. Replace BACKEND-SERVICE-URL with the URL acquired above.

'use client';
import { Input, Textarea } from '@nextui-org/react';

export default function Page() {
  const handleSubmit = (formData: any) => {
    fetch(new URL('BACKEND-SERVICE-URL/contact'), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(formData).toString()
    });
  };

  return (
    <form action={handleSubmit}>
      <Input name="firstname" placeholder="First name" />
      <Input name="lastname" placeholder="Last name" />
      <Input name="email" placeholder="Your email" />
      <Textarea
        name="message"
        minRows={8}
        placeholder="Tell us a bit about what you want our help with"
      />
      <Input type="submit" value="Send" />
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

When the form is submitted you should now get a message in your Slack channel. To prevent spam-bots to misuse this form we need to add a CAPTCHA. CAPTCHA is an acronym that stands for "Completely Automated Public Turing test to tell Computers and Humans Apart."

To provide this functionality we will use an open source CAPTCHA backend service to generate and verify CAPTCHA. How it works is that you generate a CAPTCHA image that displays a text. Then you ask the user (human) to provide the text that he or she sees and the backend will verify that this was the text shown in the image.

Create CAPTCHA backend service in Open Source Cloud

Navigate to the CAPTCHA Service and click on the button Create service.

Image description

Give the service a name and once the service has started copy the URL to the service. Replace CAPTCHA-SVC-URL below with this URL.

Add CAPTCHA verification to your form

Extend the form we created above with the following code.

'use client';
import { Input, Textarea } from '@nextui-org/react'; 

export default function Page() {
  const [captchaSvg, setCaptchaSvg] = useState<string | null>(null);
  const [captchaId, setCaptchaId] = useState('');
  const [captcha, setCaptcha] = useState('');
  const [invalidCaptcha, setInvalidCaptcha] = useState(true);

  useEffect(() => {
    fetch(new URL('/captcha', 'CAPTCHA-SVC-URL'))
      .then((response) => response.json())
      .then((data) => {
        setCaptchaSvg(data.svg);
        setCaptchaId(data.id);
      });
  }, []);

  const onCaptchaChange = (value: string) => {
    setCaptcha(value);
    fetch(new URL('CAPTCHA-SVC-URL/verify/' + captchaId + '/' + value))
      .then((response) => {
        setInvalidCaptcha(!response.ok);
      })
      .catch(() => {
        setInvalidCaptcha(true);
      });
  };

  const handleSubmit = (formData: any) => {
    fetch(new URL('BACKEND-SERVICE-URL/contact'), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(formData).toString()
    });
  };

  return (
    <form action={handleSubmit}>
      <Input name="firstname" placeholder="First name" />
      <Input name="lastname" placeholder="Last name" />
      <Input name="email" placeholder="Your email" />
      <Textarea
        name="message"
        minRows={8}
        placeholder="Tell us a bit about what you want our help with"
      />
      {captchaSvg && (
      <Image src={captchaSvg} className="bg-white" alt="Captcha" />
      )}
      <Input
        name="captcha"
        placeholder="Enter the text from the image"
        description="This is used to prevent automated submissions."
        required
        maxLength={4}
        value={captcha}
        onValueChange={onCaptchaChange}
      />
      <Input type="submit" value="Send" isDisabled={invalidCaptcha} />
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

This was an example on how you can add to your web application a contact form with CAPTCHA verification that posts to a Slack channel without having to build or host your own backend services for it.

What is Open Source Cloud?

Open Source Cloud reduces the barrier to get started using open source and reduces the barrier for creators to make their software available as a service. Read more about why we developed it in this post.

Top comments (0)