$ xyruscodev7

Blog

Adding a Contact Form to Your Next.js Site

I recently had to build a portfolio site for an agency but I didn't want to use WordPress for it.

·7 min read
Next.jsNodemailerTutorial

I recently had to build a portfolio site for an agency but I didn't want to use WordPress for it. I've been spending quite a while in the Vercel Ecosystem and wanted to do this with Next.js. It proved to be kinda challenging though.

Setting Up

First, create your new Next.js project:

npx create-next-app@latest next-contact-form
cd next-contact-form

Next, install the required packages:

npm i flowbite flowbite-react axios nodemailer

Creating the Email Function

// lib/email.ts
import axios from 'axios';

export type Email = {
  email: string;
  subject: string;
  message: string;
}

export const sendEmail = async (email: Email) => {
  return axios({
    method: 'post',
    url: '/api/send-mail',
    data: email,
  });
};

The API Route

// pages/api/send-email.ts
import nodemailer from 'nodemailer';
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { email, subject, message } = req.body;

  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_PASS,
    },
  });

  await transporter.sendMail({
    from: email,
    to: process.env.EMAIL_USER,
    subject,
    text: message,
  });

  res.status(200).json({ message: 'Email sent' });
}

Conclusion

And there you have it — a working contact form in Next.js with Nodemailer. The key pieces are the API route for server-side email sending and the frontend form component.

Comments