How to Create a Contact Form with Netlify Forms and Next.js

As a web developer, one of the most common features you‘ll need to implement is a contact form. It allows visitors to your website to easily send you a message without leaving the site. However, properly handling form submissions can often require a backend server and database.

Luckily, Netlify provides a powerful form handling solution that integrates seamlessly with static sites and frontend frameworks like Next.js. In this in-depth tutorial, we‘ll walk through how to create a contact form using Netlify Forms, first with plain HTML and then with a Next.js app.

What are Netlify Forms?

Netlify Forms is a built-in feature of Netlify‘s hosting platform that allows you to accept form submissions without needing a backend server. You simply add a few attributes to your HTML tag, and Netlify will automatically detect and handle the form submissions.

When a user submits the form, the data is sent directly to Netlify‘s servers where it is processed and stored. You can then view and manage the form submissions through the Netlify web interface or API.

Benefits of Using Netlify Forms

There are several key advantages to using Netlify Forms over a traditional backend form handler:

  1. Easy setup – No need to code a backend or database. Just add a few HTML attributes and you‘re ready to accept submissions.

  2. Spam filtering – Netlify provides a built-in honeypot field and optional reCAPTCHA integration to help prevent spam submissions.

  3. Notification options – Get notified of new submissions via email, Slack, or webhook. You can also forward submissions to other services.

  4. Generous free tier – Netlify‘s free plan includes 100 form submissions per month, with higher limits on paid plans.

  5. Manage submissions in Netlify – You can view, export, and delete form submissions right from the Netlify dashboard.

Now that we understand what Netlify Forms are and why you might want to use them, let‘s dive into actually building a contact form.

Part 1: Create a Basic HTML Contact Form

We‘ll start by creating a pure HTML contact form to demonstrate the core Netlify Forms functionality. In Part 2, we‘ll integrate this into a Next.js app.

Step 1: Code the HTML form

Create a new HTML file and add the following form code:

<form name="contact" method="post" data-netlify="true">
  <p>
    <label>Name: <input type="text" name="name" /></label>   
  </p>
  <p>
    <label>Email: <input type="email" name="email" /></label>
  </p>
  <p>
    <label>Message: <textarea name="message"></textarea></label>
  </p>
  <p>
    <button type="submit">Send</button>
  </p>
</form>

The key things to note:

  • The form tag must have a name attribute which will identify the form in Netlify
  • Add the data-netlify="true" attribute to the form tag to enable Netlify‘s form handling
  • Each form field should have a name attribute which will be used as the field name in the submission data

Step 2: Deploy to Netlify

Push your HTML file to a Git repository and deploy it to Netlify. You can do this through the Netlify web interface by connecting your Git provider and selecting the repository.

Configure the build settings by setting the publish directory to where your HTML file is located (e.g. the root for a single HTML file).

Step 3: Configure form in Netlify

Once your site is deployed, navigate to the Forms tab in the Netlify site dashboard. You should see your contact form listed with the name you gave it in the HTML.

Click on the form to view its settings. Here you can set up email notifications, integrate with other services, configure spam filtering options, and more.

Step 4: Test form and view submissions

Visit your deployed site and fill out and submit the contact form. You should be redirected to a Netlify default success page.

Back in the Netlify dashboard, navigate to the Submissions tab for your form. You should see the submission you just made with all the field data.

You‘ve now successfully created a working contact form with Netlify!

Part 2: Add Contact Form to Next.js App

Now let‘s look at adding our contact form to a Next.js app. The process is largely the same, with a few extra considerations for the Next.js build process.

Step 1: Create Next.js app

First, create a new Next.js app using create-next-app:

npx create-next-app my-app
cd my-app

Step 2: Add HTML form to page

Open the index.js file in the pages directory and replace it with the following:

import Head from ‘next/head‘

export default function Home() {
  return (
    <div>
      <Head>
        <title>Contact Us</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main>


        <form name="contact" method="post" data-netlify="true">
          <p>
            <label>Name: <input type="text" name="name" /></label>   
          </p>
          <p>
            <label>Email: <input type="email" name="email" /></label>
          </p>
          <p>
            <label>Message: <textarea name="message"></textarea></label>
          </p>
          <p>
            <button type="submit">Send</button>
          </p>
        </form>
      </main>
    </div>
  )
}

This adds the same HTML form from Part 1 to the homepage of the Next.js app.

Step 3: Configure Next.js build for Netlify

To deploy a Next.js app to Netlify, we need to configure the build settings appropriately.

Open the package.json file and add the following to the scripts section:

"scripts": {
  ...
  "export": "next export"
}

This export script will generate a static HTML version of our Next.js app that Netlify can serve.

Step 4: Deploy to Netlify

Push your Next.js app to a Git repository and deploy it to Netlify the same way as the plain HTML site.

In the build settings, set the build command to npm run build && npm run export and the publish directory to out.

Step 5: Test form and view submissions

Once the Next.js app is deployed, test out the contact form and confirm the submissions come through in the Netlify dashboard just like with the plain HTML form.

Bonus: Display Success Message

Rather than redirecting to a Netlify page after a successful submission, we can display a success message on the same page. Here‘s how to implement that in our Next.js app:

First, add a success state variable to track if the form was submitted successfully:

import { useState } from ‘react‘

export default function Home() {
  const [success, setSuccess] = useState(false);

  ...

Then update the form tag like so:

<form 
  name="contact"
  method="post"
  data-netlify="true"
  onSubmit={() => setSuccess(true)}
  action="/?success=true"
>

This will set success to true and add ?success=true to the URL on submission.

Finally, add the following code below the form to display the message:

{success && (
  <p style={{ color: ‘green‘ }}>
    Thank you for contacting us! We will get back to you shortly.
  </p>
)}

Now when a user submits the form, they will stay on the same page and see a success message instead of being redirected.

Advanced Features

Netlify Forms offers some additional features beyond the basics we‘ve covered:

Spam Prevention

Netlify has two main options for preventing spam submissions on your forms:

  1. Honeypot field – Netlify automatically includes a hidden honeypot field in your form. This helps prevent basic bot spam. You can customize the field name in the form settings.

  2. reCAPTCHA 2 – For more robust spam prevention, you can add reCAPTCHA 2 to your form by including the appropriate script tag and a data-netlify-recaptcha="true" attribute on your form element.

Integrations

Netlify integrates with a variety of third-party services to enable more advanced form workflows. Some popular options:

  • Zapier – Netlify offers a Zapier integration that allows you to connect your form submissions to over 2000 other web services. For example, you could add form submissions to a Google Sheet or a CRM.

  • Slack – Get a Slack notification every time someone submits a form on your site. Simply enter a Slack webhook URL in the form notifications settings.

  • Email – In addition to Netlify‘s built-in email notifications, you can also forward submissions to any email address.

Best Practices

Here are a few tips for getting the most out of Netlify Forms:

  • Use clear labels and field names to make the form easy to fill out and the submission data easy to understand.
  • Take advantage of the built-in spam filtering options to minimize junk submissions.
  • Set up email notifications or integrations to ensure you are alerted to new submissions promptly.
  • Regularly check the Netlify dashboard and export or delete old submissions to stay within your plan limits.

Additional Resources

Conclusion

Netlify Forms are a powerful and easy-to-use solution for adding contact forms or other types of forms to your static site or frontend framework app. The generous free tier, built-in spam protection, and notification/integration options make it a great choice for many web projects.

In this tutorial, we walked through creating a basic contact form in plain HTML and integrating it into a Next.js app. We also looked at some of the more advanced features and best practices.

I hope this in-depth guide has been helpful for understanding and implementing Netlify Forms in your own web projects. As always, feel free to reach out with any questions or feedback!

Similar Posts