Set Up Forms

·view .md ↗·chatgpt ↗·claude ↗

To set up Netlify forms, follow these steps:

  1. Enable automatic form detection
  • In your project dashboard, go to Forms and enable Enable form detection.
  • From the next deploy on, Netlify will scan the project for forms.
  1. Form integration in code
  • Create a <form> component including the following parameters:
    • A unique name attribute for the form
    • netlify or data-netlify="true"
    • method="POST"
    • A hidden form-name field with the same value as the name attribute
    • A honeypot for spam prevention
  • Basic template:
    <form 
      @submit.prevent="handleSubmit" 
      name="Contact" 
      data-netlify="true" 
      netlify-honeypot="hpfield" 
      method="POST"
    >
      <input type="hidden" name="form-name" value="Contact">
      <input type="text" name="name" required>
      <input type="email" name="email" required>
      <button type="submit">Send</button>
    </form>
    
    • The form-name value must match the form's name attribute, "contact" in the template case.
    • Each field must include a name attribute so Netlify can record its value.
  1. Submit handling with JS
  • To avoid refreshing or redirecting the page when the form is submitted, you can intercept the submit event and send the data with fetch.
  • Basic example with JavaScript:
    const handleSubmit = async (event) => {
    
      const form = event.target;
      const formData = new FormData(form);
      
      try {
        const response = await fetch("/", {
          method: 'POST',
          body: formData,
          headers: {
            'Accept': 'application/json',
          }
        });
        if (response.ok) {
          console.log('Form submitted successfully');
        } else {
          throw new Error(`Error: ${response.statusText}`);
        }
      } catch (error) {
          console.log("Error: " + error.message);
      }
    };
    
    • Once the method is created, attach it to the form's submit event using @submit.prevent.
  1. Usage management and notifications
  • After deploy, the form will automatically appear in the project's Forms section.
  • Go to Form notifications to add submission notifications.