❮ Back to Journal

How to add forms to your Gridsome site with Netlify forms

In order to implement the form functionality we need to start by adding the form to our template tag:

      <input type="hidden" name="form-name" value="contact" />
      <p hidden>
        	Don’t fill this out: <input name="bot-field" />
      <div class="sender-info">
      <label for="name" class="label" >Your name</label>
      <input type="text" name="name" v-model="formData.name" />
          <label for="email">Your email</label>
          <input type="email" name="email" v-model="formData.email" />

      <div class="message-wrapper">
        <label for="message">Message</label>
        <textarea name="message" v-model="formData.message"></textarea>
      <button type="submit">Submit form</button>

We have also included a honeypot input that will lure bots that are trying to send us spam, into filling out a special hidden field that will be caught by Netlify and automatically being rejected.

Next step is to add our `formData` variable that will hold our data that will be sent to Netlify, this is binded to our inputs to automatically update `formData` when the input is changed.

    data() {
      return {
      	formData: {},

Last step is to add our submit handler to send the data to Netlify. This is done by listening to the form submit action and using fetch to post the data in `formData`. We also have a encode method that will make sure our data is properly formatted when we post it.

In this example shown below we are redirecting the user to the route `/success` if the post was successful, this can be changed into any action you want. But in this case you need to make sure you have a page setup on that route to present a success message for the user.

    methods: {
      encode(data) {
        return Object.keys(data)
          .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
      handleSubmit(e) {
        fetch('/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: this.encode({
          'form-name': e.target.getAttribute('name'),
        .then(() => this.$router.push('/success'))
        .catch(error => alert(error))

Read more: https://www.netlify.com/docs/form-handling/