How to Create Dynamic Email Contact Form in Next.js Using Resend and Zod

how-to-create-dynamic-email-contact-form-in-next.js-using-resend-and-zod

Introduction

Next.js is a powerful full-stack framework that allows us to build applications with both frontend and backend features. It’s very flexible and can be used for everything from simple static websites to complex web apps. Today, we will use Next.js to build an email contact form.

Forms are a key part of any website, letting users interact with the application. Whether it’s for signing up, logging in, giving feedback, or collecting data, forms are vital for user experience. Without forms, a full-stack application wouldn’t be able to gather and process user input properly.

In this blog, I will show you how to create an email contact form using Next.js, Resend, and Zod (for form validation). We will cover setting up the project, designing the form, handling form submissions, and creating a separate API route. By the end, you will know how to build and add forms to your Next.js apps, ensuring your web app works well and is easy to use.

So, without further delay, let’s get started.

What is Resend?

Resend is a modern email API for developers. It’s designed to make sending emails from your applications simple, reliable, and scalable. Unlike traditional email services, Resend is built with developers in mind, offering a straightforward API that integrates seamlessly with various programming languages and frameworks, including Next.js.

In our Next.js form project, we’ll use Resend to send emails. When a user submits the form, we’ll use Resend’s API to send a confirmation email or process the form data as needed.

What is Zod?

Zod is a powerful tool for your data. It’s a TypeScript-first library that helps you define and check the shape of your data. Think of it as setting rules for your data and then making sure the data matches those rules before you use it.

Zod

If you’re using TypeScript (and if you’re not, you should consider it!), Zod plays nicely with it. It can automatically infer TypeScript types from your schemas, which is a huge time-saver. While TypeScript checks types at compile-time, Zod does it at runtime. This means you can catch data issues that might slip through static type checking. You can use Zod for all sorts of data validation scenarios, from simple form inputs to complex API responses.

Project Setup

Let’s start by setting up our Next.js project with all the necessary dependencies. We’ll use TypeScript for type safety, Tailwind CSS for styling, Ant Design for UI components, Zod for form validation, and Resend for email functionality.

  • Create a new Next.js project with TypeScript:
npx create-next-app@latest my-contact-form --typescript
cd my-contact-form
  • Install additional dependencies:
yarn add antd zod resend react-icons

Setup Environment variables

For sending an email, we will use Resend, so we need the Resend API key. Before starting our server, let’s go to Resend and get our API keys. Click here to go to the Resend site, and click the sign-in button.

Resend Homepage

After signing in, you’ll be redirected to this page. Here, you’ll see all the emails you received from your form.

Resend  dashboard page after sign in

Here, click on the API Keys section

Resend  dashboard page after sign in

And, generate an API key by clicking on this 👇 button

Resend API keys Page

Now, copy that API key and keep it safe. Next, open VSCode and create a new file named .env in your root folder. Add an environment variable there.

RESEND_API_KEY=yourapikeywillbehere

Now you can also run your server using this command.

yarn dev

Email Template Component

Let’s start by creating an email template. This will be the template you receive when someone sends you an email via the contact form.

import * as React from 'react';

interface EmailTemplateProps {
  firstName: string;
  message: string;
}

export const EmailTemplate: React.FC = ({
  firstName,
  message,
}) => (
  

Hello, I am {firstName}!

You have received a new message from your Portfolio:

{message}

);

This simple React component defines the structure of the email that will be sent when someone submits the contact form. It takes two props: firstName and message. The component creates a personalized greeting using the first name and displays the submitted message.

Implementing Email Sending with Resend API

Here. we’ll see how to implement email-sending functionality using the Resend API.

The Code Structure

First, let’s look at where this code lives in our Next.js project:

app/
  ├── api/
  │   └── v1/
  │       └── send/
  │           └── route.ts

This structure follows Next.js 13’s App Router convention, where API routes are defined as route handlers within the app directory.

This is our complete API route code 👇

import { EmailTemplate } from 'app/components/email-template';
import { NextResponse } from 'next/server';
import { Resend } from 'resend';
import { v4 as uuid } from 'uuid';

const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(req: Request) {
  try {
    const { name, email, subject, message } = await req.json();

    const { data, error } = await resend.emails.send({
      from: 'Contact Form ',
      to: 'katare27451@gmail.com',
      subject: subject || 'New Contact Form Submission',
      reply_to: email,
      headers: {
        'X-Entity-Ref-ID': uuid(),
      },
      react: EmailTemplate({ firstName: name, message }) as React.ReactElement,
    });

    if (error) {
      return NextResponse.json({ error }, { status: 500 });
    }

    return NextResponse.json({ data, message: 'success' }, { status: 200 });
  } catch (error) {
    console.error('Error processing request:', error);
    return NextResponse.json({ error: 'Failed to process request' }, { status: 500 });
  }
}

Breaking Down the Code

Now, let’s examine each part of the code:

import { EmailTemplate } from 'app/components/email-template';
import { NextResponse } from 'next/server';
import { Resend } from 'resend';
import { v4 as uuid } from 'uuid';

These import statements bring in the necessary dependencies:

  • EmailTemplate: A custom React component for our email content(That we already built above.
  • NextResponse: Next.js utility for creating API responses.
  • Resend: The Resend API client.
  • uuid: For generating unique identifiers.
const resend = new Resend(process.env.RESEND_API_KEY);

Here, we initialize the Resend client with our API key. It’s crucial to keep this key secret, so we store it in an environment variable.

export async function POST(req: Request) {
  // ... (code inside this function)
}

This exports an async function named POST, which Next.js will automatically use to handle POST requests to this route.

const { name, email, subject, message } = await req.json();

We extract the form data from the request body. This assumes the client is sending a JSON payload with these fields.

const { data, error } = await resend.emails.send({
  from: 'Contact Form ',
  to: 'katare27451@gmail.com',
  subject: subject || 'New Contact Form Submission',
  reply_to: email,
  headers: {
    'X-Entity-Ref-ID': uuid(),
  },
  react: EmailTemplate({ firstName: name, message }) as React.ReactElement,
});

This is where we’ll get our emails! We use Resend’s send method to dispatch the email:

  • from: The sender’s email address.
  • to: The recipient’s email address.
  • subject: The email subject, using the provided subject or a default.
  • reply_to: Sets the reply-to address to the form submitter’s email.
  • headers: Includes a unique ID for tracking.
  • react: Uses our custom EmailTemplate component to generate the email content.
if (error) {
  return NextResponse.json({ error }, { status: 500 });
}

return NextResponse.json({ data, message: 'success' }, { status: 200 });

Here, we handle the response from Resend. If there’s an error, we return a 500 status with the error details. Otherwise, we send a success response.

catch (error) {
  console.error('Error processing request:', error);
  return NextResponse.json({ error: 'Failed to process request' }, { status: 500 });
}

This catch block handles any unexpected errors, logs them, and returns a generic error response.

And that’s it! We’ve set up our API route. The only thing left is to set up our logic and UI. Let’s do that too 💪

Contact Page Component

In your app directory, create a new folder named contact-form and inside this folder, create a file named page.tsx.

app/
  ├── contact-form/
  │   └── page.tsx

Imports and Dependencies

First, import all necessary components from Ant Design, Next.js, and React Icons. We also import Zod for form validation.

import React from 'react';
import { Form, Input, Button, message, Space, Divider, Typography } from 'antd';
import Head from 'next/head';
import { FaUser } from 'react-icons/fa';
import { MdMail } from 'react-icons/md';
import { FaMessage } from 'react-icons/fa6';
import { z } from 'zod';
import Paragraph from 'antd/es/typography/Paragraph';

UI Layout and Design

Now, let’s create our UI, and then we’ll move on to the logic. Our form will look something like this.👇

contact form ui

In your page.tsx, after all the import statements, define a component and add a return statement first.

const ContactPage: React.FC = () => {
  return (
      
/* our code will be here */
); }; export default ContactPage;

Currently, we have just a simple div with a few tailwind styling now, we’ll first add our heading part.

contact form ui

...

        

Get in Touch

I'd love to hear from you! Fill out the form below to get in touch.

...

Now, let’s add our input fields

contact form ui

 ...     
        
} placeholder="Your Name" size="large" /> } placeholder="Your Email" size="large" /> } placeholder="Subject" size="large" />

Previous Post
create-a-new-rails-7.2-project-with-bootstrap-theme-on-a-newly-set-up-wsl-(in-minutes)

Create a New Rails 7.2 Project with Bootstrap Theme on a Newly Set Up WSL (in Minutes)

Next Post
asme-foundation-wins-federal-grant-for-registered-apprenticeship-program-in-mechanical-engineering-technology

ASME Foundation Wins Federal Grant for Registered Apprenticeship Program in Mechanical Engineering Technology

Related Posts