Adding a Contact Form to your Next.js App

Kevin Green
The Couch
Published in
2 min readFeb 24, 2018

While building websites regardless of the platform we often need to add some form of contact form. If you’re using Mailchimp you generally don’t have to build something server side, and you can actually read my other article about RIMP (which is a react Mailchimp component).

However RIMP wasn’t enough in this case and I actually needed to send some information directly to an email account. For this we’ll utilize Nodemailer. And since these request need to be handled on the server we’ll have to add a server to our Next.js app. Next.js handles the server stuff out of the box, but in order to customize it we’ll have to extend it, Next.js has a bunch of examples of how to do this on github and you can read about the express implementation which we’ll be using (or look at the other examples if you don’t want to use express).

This is not a tutorial on using Next.js/express/React. We’ll assume you have working knowledge of these tools and frameworks.

This post was inspired by Przemslaw’s post about adding nodemailer to React, you can read his article about this subject as well.

Let’s first switch over to express, this requires us to create a server.js file in our root level of the application. We’ll also want to update our package.json file to read the server.js file instead of using the default Next.js implementation.

"scripts: {
"dev": "node server.js"
}

Now for our initial server setup:

You should now be able to run your application the same as you have been but now you can extend/customize the routing. We’ve also included body parser which we’ll use to read our form data.

Now let’s set up our Simple contact form, we’ll be using micro-form which is a super lightweight form library, you’re free to use whatever you’d like of course but the implementation is modeled around that library for context.

Next we’ll add our /api/contact route to server.js:

You should now be able to post a name and email to the server and log that response in terminal. Next let’s set up nodemailer and get that data actually going somewhere.

We’ll actually have to do a good deal of Google API configuration, hop over the Przemyslaw’s article and read the bit about setting up a project in Google’s API Console.

I also grabbed his nodemailer setup and I’ll post that here for reference:

Next we’ll hook it up to our server and then we’re all done:

And that’s it, you should now be sending mail from your app, I’ve tested this locally and on now.sh.

Using Sendgrid to send email

While I did manage to get the above working, the configuration is actually much simpler with sendgrid, to the point of which you only need to have an API key. You’ll want to install the middleware nodemailer-sendgrid-transport and configure as follows:

I found this solution to be cleaner, feel free to reference/use either however you’d like!

Cheers~

--

--