Let's build a contact form with Next.js

Read Time:4 Minute, 43 Second

Most of the websites have a contact page where you can send a message to reach the owner. They look something like this:

In this article, we will create a similar form with React in Next.js. First, I will create a front-end part with the form, and then I will build an API route which will send the form to your email.

Setting up the application

First, let’s create a new Next.js project. We will create it in a contact-form folder, with JavaScript and ESLint enabled:

Enter fullscreen mode Exit fullscreen mode

This will create the folder and installs all the dependencies.

Now enter the folder (cd contact-form) and start the development server:

Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 to check the running application.

Creating the form

The main file where we are going to make changes is pages/index.js. Remove the original code inside the file and paste the following code:

Enter fullscreen mode Exit fullscreen mode

This code creates a form with the following fields:

  • email
  • first name
  • last name
  • phone number
  • message

All fields are required except for the message.

To add style to the form, replace the contents of styles/globals.css file with the following code:

Enter fullscreen mode Exit fullscreen mode

Our form should look something like this:

Styled form with Email, Phone, First name, Last name, and Message

Now we need to find a way to store the input entered by the user. I will use FormData which is natively supported in all current browsers. It loads fields from the form, so they can be then submitted to the server.

Inside the pages/index.js file, paste the following code (notice the new handleSubmit function):

Enter fullscreen mode Exit fullscreen mode

Now when you attempt to submit the form, you should see FormData in developer console.

Submitting the form to API

We will submit the form data to the API with [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) – no need for additional dependencies.

The form submission logic goes to the handleSubmit function. Here is the complete code in pages/index.js:

Enter fullscreen mode Exit fullscreen mode

The handleSubmit sends data inside a POST request to the /api/contact route. We also wrap the FormData object in URLSearchParams to send data as application/x-www-form-urlencoded which is automatically decoded by Next.js API routes handler.

Handling form submission in the API route

Now we need to handle the form submission on the server. We are going to use Next.js API routes for that. API routes are located in pages/api folder. Let’s create pages/api/contact.js file which corresponds to the API route /api/contact.

First inside the pages/api/contact.js file paste the following code to test if we receive the data on the server.

Enter fullscreen mode Exit fullscreen mode

Try submitting the form now, you should see the data logged on the terminal. And now we are getting to the juicy part.

Sending emails with SendGrid and Superface

When a user submits the contact form, we want to send the submitted information to the website owner. First, we need to pick some email providers and study their API and SDK. Or we can use Superface with any provider.

Superface makes API integrations super easy. We don’t have to deal with API docs, and I can use many providers behind the same interface. Furthermore, I can use more ready-made API use cases from the Superface catalog. It’s a tool worth having in your toolbox.

Set up SendGrid

I’m going to use SendGrid as an email provider with Superface. Create your account, get your API key with Full Access and verify Single Sender Verification.

On Superface side, pick the use case, i.e.: Send Email.

Superface integrations catalog include other use cases, like Send SMS Message, or Send Templated Message.

Sending emails from the API route

Superface use cases are consumed with OneSDK, so we will have to install it.

Enter fullscreen mode Exit fullscreen mode

On Superface in Send Email use case, select sendgrid as a provider. We can use most of the code from the example in our API route handler, we just need to pass data correctly from the request.

Send Email use case with SendGrid selected as a provider

Paste the following code into your pages/api/contact.js file:

Enter fullscreen mode Exit fullscreen mode

You can notice that we are referring to some environment variables in the code (for example process.env.SENDGRID_TOKEN). We can store these in .env files. In the root of your project, create a .env.local file with the following contents (make sure to edit values):

Enter fullscreen mode Exit fullscreen mode

Our app is ready. Run (or restart) the development server with npm run dev and try to submit the form!

Form filled with all fields filled in

Received email with the form submissions

Conclusion

We have learned how to create a form in Next.js, submit the form with FormData and fetch, handle the submission in the API route and send it through an email.

Further possible improvements include adding CAPTCHA or honeypot fields to prevent spam submissions, improving form data validation with checks of phone and email address, format the submission as HTML, or providing a nicer feedback to the user upon submissions.

Besides sending an email, we can do a lot more with submissions, like sending data to CRM or Slack, or handle newsletter subscriptions. But that’s for another time – follow our profile or sign up for our monthly newsletter, so you don’t miss our future tutorials.

Source: https://dev.to/superface/lets-build-a-contact-form-with-nextjs-3lao