Back to all posts

Implementing Netlify Forms in Gridsome: A Complete Guide for Static Sites

One of the biggest challenges with static sites is handling form submissions without a server. Fortunately, Netlify offers a powerful forms solution that integrates seamlessly with static site generators like Gridsome. In this comprehensive guide, I'll walk you through implementing Netlify Forms in your Gridsome project, from basic setup to form submission handling.

Why Use Netlify Forms with Gridsome?

Netlify Forms provides several advantages for static site developers:

  • No server required: Process form submissions without managing your own backend
  • Spam protection: Built-in spam filtering with honeypot fields and optional reCAPTCHA
  • Form notifications: Receive email notifications for new submissions
  • Submission management: Access and manage submissions through the Netlify dashboard
  • Seamless integration: Works with static site generators like Gridsome with minimal configuration

Step 1: Creating the Form Markup

The first step is to add the form to your Gridsome template with the necessary Netlify attributes:

<template>
  <Layout>
    <div class="contact-page">
      <h1>Contact Us</h1>
 
      <form
        name="contact"
        method="post"
        @submit.prevent="handleSubmit"
        action="/success/"
        data-netlify="true"
        data-netlify-honeypot="bot-field"
      >
        <!-- Form name (required for Netlify) -->
        <input type="hidden" name="form-name" value="contact" />
 
        <!-- Honeypot field to prevent spam -->
        <div hidden>
          <label>
            Don't fill this out: <input name="bot-field" />
          </label>
        </div>
 
        <!-- Form fields -->
        <div class="form-group">
          <label for="name">Your Name</label>
          <input
            type="text"
            id="name"
            name="name"
            v-model="formData.name"
            required
          />
        </div>
 
        <div class="form-group">
          <label for="email">Your Email</label>
          <input
            type="email"
            id="email"
            name="email"
            v-model="formData.email"
            required
          />
        </div>
 
        <div class="form-group">
          <label for="message">Message</label>
          <textarea
            id="message"
            name="message"
            v-model="formData.message"
            required
          ></textarea>
        </div>
 
        <button type="submit" class="submit-button">Send Message</button>
      </form>
    </div>
  </Layout>
</template>

Let's break down the important attributes in this form:

  • data-netlify="true": This tells Netlify to process this form
  • data-netlify-honeypot="bot-field": Creates a honeypot field to catch spam bots
  • name="contact": Gives your form a name for identification in the Netlify dashboard
  • method="post": Specifies that form data should be sent as a POST request
  • action="/success/": The page to redirect to after successful submission

The hidden input with name="form-name" is crucial for Netlify to properly identify your form when using JavaScript to handle submissions.

Step 2: Setting Up the Form Data

Next, we need to set up the Vue component to handle the form data. Add this script section to your component:

<script>
export default {
  data() {
    return {
      formData: {
        name: '',
        email: '',
        message: ''
      },
      isSubmitting: false,
      submitError: null
    }
  },
  // Methods will be added in the next step
}
</script>

This creates a reactive formData object that will be bound to our form inputs using v-model. We also add state variables to track submission status.

Step 3: Handling Form Submission

Now we need to add the methods to handle form submission:

<script>
export default {
  data() {
    // Data properties from previous step
  },
  methods: {
    // Encode form data for submission
    encode(data) {
      return Object.keys(data)
        .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
        .join('&')
    },
 
    // Handle form submission
    async handleSubmit(e) {
      this.isSubmitting = true;
      this.submitError = null;
 
      try {
        await fetch('/', {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: this.encode({
            'form-name': 'contact',
            ...this.formData,
          }),
        });
 
        // Redirect to success page
        this.$router.push('/success');
      } catch (error) {
        this.submitError = 'There was a problem submitting your form. Please try again.';
        console.error('Form submission error:', error);
      } finally {
        this.isSubmitting = false;
      }
    }
  }
}
</script>

The encode method formats our form data properly for Netlify's form handling service. The handleSubmit method:

  1. Sets loading and error states
  2. Submits the form data to Netlify using the Fetch API
  3. Redirects to a success page or displays an error message
  4. Resets the loading state

Step 4: Creating a Success Page

You'll need to create a success page at the route specified in your form's action attribute. In Gridsome, you can create a file at src/pages/Success.vue:

<template>
  <Layout>
    <div class="success-page">
      <h1>Message Sent Successfully!</h1>
      <p>Thank you for contacting us. We'll respond to your message as soon as possible.</p>
      <g-link to="/" class="home-link">Return to Home</g-link>
    </div>
  </Layout>
</template>
 
<script>
export default {
  metaInfo: {
    title: 'Form Submitted Successfully'
  }
}
</script>

Step 5: Adding Styling (Optional)

To make your form look better, you can add some CSS:

<style scoped>
.form-group {
  margin-bottom: 1.5rem;
}
 
label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
}
 
input, textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}
 
textarea {
  min-height: 150px;
  resize: vertical;
}
 
.submit-button {
  background-color: #4a5568;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  font-size: 1rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}
 
.submit-button:hover {
  background-color: #2d3748;
}
</style>

Advanced Netlify Forms Features

Netlify Forms offers several advanced features you can implement:

File Uploads

To allow file uploads, add the netlify-files attribute and an input with type="file":

<form data-netlify="true" data-netlify-files="true">
  <input type="file" name="resume" />
</form>

Form Notifications

Configure email notifications for form submissions in your Netlify dashboard:

  1. Go to Site settings > Forms > Form notifications
  2. Add email addresses to be notified
  3. Customize the notification template

reCAPTCHA Integration

For additional spam protection, enable reCAPTCHA:

  1. Go to Site settings > Forms > Spam filters
  2. Enable reCAPTCHA
  3. Add the data-netlify-recaptcha="true" attribute to your form
  4. Include the reCAPTCHA element: <div data-netlify-recaptcha="true"></div>

Troubleshooting Common Issues

Forms Not Detected by Netlify

If Netlify isn't detecting your form:

  1. Ensure your form has the data-netlify="true" attribute
  2. Make sure the form has a name attribute
  3. Include a hidden input with name="form-name" and the value set to your form's name
  4. Deploy your site again to trigger form detection

Form Submissions Not Working

If submissions aren't working:

  1. Check browser console for errors
  2. Verify that you're encoding the form data correctly
  3. Ensure the form name in your fetch request matches the form's name attribute
  4. Check that you're using the correct content type header

Conclusion

Implementing Netlify Forms in your Gridsome site provides a powerful, serverless solution for handling form submissions. By following this guide, you can create fully functional contact forms, feedback forms, or any other type of form your static site needs.

The combination of Gridsome's static site generation and Netlify's form handling creates a fast, secure, and user-friendly experience without the complexity of managing your own server-side form processing.

For more information, check out the official Netlify Forms documentation.


Did you find this article helpful? Follow me for more web development tips and solutions to common challenges.