How to Prevent Bots From Submitting Forms

Code of Relevancy - Jan 2 '23 - - Dev Community

To prevent spam form submissions in Next.js, you can use a honeypot field. A honeypot field is an invisible field that is hidden from the user but visible to bots. When a bot fills out the form, it will also fill out the honeypot field, indicating that it is a spam submission.

You can follow these steps:

  1. Create a new form element in your Next.js page or component.
  2. Add a hidden input field to the form. This will be your honeypot.
  3. Give the honeypot input field a name that is not related to your form. For example, you can name it "favorite_color" or "email2".
  4. Set the value of the honeypot input field to an empty string.
  5. Add a validation function to your form that checks if the honeypot field has a value. If it does, the form submission is considered spam and can be discarded.
  6. If the honeypot field is empty, you can proceed with your form submission as normal.

Here's an example of how your form element might look with a honeypot input field:

<form onSubmit={handleSubmit}>
  <input type="text" name="name" placeholder="Name" />
  <input type="email" name="email" placeholder="Email" />
  <textarea name="message" placeholder="Message" />
  <input type="hidden" name="favorite_color" value="" />
  <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

In your form submission function, you can check the value of the honeypot field like this:

const handleSubmit = e => {
  e.preventDefault();
  const formData = new FormData(e.target);
  if (formData.get("favorite_color") !== "") {
    // Form submission is spam
    return;
  }
  // Form submission is valid, proceed with processing
}
Enter fullscreen mode Exit fullscreen mode

This is a simple way to create a honeypot in Next.js to protect your form from spam submissions. You can also consider using other spam prevention techniques such as CAPTCHAs or reCAPTCHAs.


Please consider following and supporting me by subscribing to my channel. Your support is greatly appreciated and will help me continue creating content for you to enjoy. Thank you in advance for your support!

YouTube
Discord
GitHub

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player