”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何使用 Resend 和 Zod 在 Next.js 中创建动态电子邮件联系表单

如何使用 Resend 和 Zod 在 Next.js 中创建动态电子邮件联系表单

发布于2024-08-16
浏览:824

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.

How to Create Dynamic Email Contact Form in Next.js Using Resend and 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.

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

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

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

Here, click on the API Keys section

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

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

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

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: '[email protected]',
      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: '[email protected]',
  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.?

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

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.

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

...

        

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

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

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

Here, in the above code firstly we added a Form Component. This is the main Form component from Ant Design. It has the following props:

{/* Form items */}
  • form: Links the form to the form object created using Form.useForm().
  • name: Gives the form a name, in this case, "contact".
  • onFinish(we'll declare this function in our next section): Specifies the function to be called when the form is submitted successfully.
  • layout: Sets the form layout to "vertical".
  • className: Applies CSS classes for styling.

Then, we added a Form Items. Each Form.Item represents a field in the form. Let's look at the "name" field as an example.

} placeholder="Your Name" size="large" />
  • name: Specifies the field name.
  • rules: An array of validation rules. Here, it's set as required.
  • The Input component is used for text input, with a user icon prefix and a placeholder.

Similarly, we have Email and other fields.

} placeholder="Your Email" size="large" />

This field has an additional rule to ensure the input is a valid email address.

Subject and Message Fields: These are similar to the name field, with the message field using a TextArea component for multi-line input.

Then, we have a Submit Button to submit our form


This is the submit button for the form. It's disabled when isSubmitting (we'll add this state in our next section) is true, and its text changes to "Sending..." during submission.

Form Submission Logic

So, in the logic part, we have a few things to do:

  • Setting up Zod schema for form validation
  • Adding new states
  • and, implementing a onFinish function

We'll start with setting up our schema first.

// Zod schema for form validation
const contactSchema = z.object({
  name: z.string().min(4, 'Name must be at least 4 characters').max(50, 'Name must not exceed 50 characters'),
  email: z.string().email('Invalid email address').regex(/^[\w-\.] @([\w-] \.) [\w-]{2,4}$/, "Email must be a valid format"),
  subject: z.string().min(5, 'Subject must be at least 5 characters').max(100, 'Subject must not exceed 100 characters'),
  message: z.string().min(20, 'Message must be at least 20 characters').max(1000, 'Message must not exceed 1000 characters'),
});

type ContactFormData = z.infer;

This part defines a Zod schema for form validation. As we already learned, Zod is a TypeScript-first schema declaration and validation library. The contactSchema object defines the structure and validation rules for the contact form:

  • name: Must be a string between 4 and 50 characters.
  • email: Must be a valid email address and match the specified regex pattern.
  • subject: Must be a string between 5 and 100 characters.
  • message: Must be a string between 20 and 1000 characters.

The ContactFormData type is inferred from the Zod schema, providing type safety for the form data.

Now, let's add 2 new states and implement our onFinish function.

const ContactPage: React.FC = () => {
  const [form] = Form.useForm();
  const [isSubmitting, setIsSubmitting] = React.useState(false);

  const onFinish = async (values: ContactFormData) => {
    setIsSubmitting(true);
    try {
      contactSchema.parse(values);

      const response = await fetch('/api/v1/send', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      if (!response.ok) {
        message.error('Failed to send message. Please try again.');
        setIsSubmitting(false); 
      }

      const data = await response.json();

      if (data.message === 'success') {
        message.success('Message sent successfully!');
        setIsSubmitting(false);
        form.resetFields();
      } else {
        throw new Error('Failed to send message');
      }
    } catch (error) {
      if (error instanceof z.ZodError) {
        error.errors.forEach((err) => {
          message.error(err.message);
          setIsSubmitting(false);
        });
      } else {
        message.error('Failed to send message. Please try again.');
        setIsSubmitting(false);
      }
    } finally {
      setIsSubmitting(false);
    }
  };

This part defines the ContactPage functional component:

  • It uses the Form.useForm hook to create a form instance.
  • It manages a isSubmitting state to track form submission status.
  • The onFinish function is called when the form is submitted:
  1. It sets isSubmitting to true.
  2. It uses contactSchema.parse(values) to validate the form data against the Zod schema.
  3. If validation passes, it sends a POST request to /api/v1/send with the form data.
  4. It handles the response, showing success or error messages accordingly.
  5. If there's a Zod validation error, it displays the error message.
  6. Finally, it sets isSubmitting back to false.

This setup ensures that the form data is validated on both the client-side (using Antd's form validation) and the server-side (using Zod schema validation) before sending the data to the server. It also manages the submission state and provides user feedback through success or error messages.

And, this is the complete code of our contact-form file ?

"use client";

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 { Container } from 'app/components/container';
import Paragraph from 'antd/es/typography/Paragraph';

const { TextArea } = Input;
const { Text } = Typography;

// Zod schema for form validation
const contactSchema = z.object({
  name: z.string().min(4, 'Name must be at least 4 characters').max(50, 'Name must not exceed 50 characters'),
  email: z.string().email('Invalid email address').regex(/^[\w-\.] @([\w-] \.) [\w-]{2,4}$/, "Email must be a valid format"),
  subject: z.string().min(5, 'Subject must be at least 5 characters').max(100, 'Subject must not exceed 100 characters'),
  message: z.string().min(20, 'Message must be at least 20 characters').max(1000, 'Message must not exceed 1000 characters'),
});

type ContactFormData = z.infer;

const ContactPage: React.FC = () => {
  const [form] = Form.useForm();
  const [isSubmitting, setIsSubmitting] = React.useState(false);

  const onFinish = async (values: ContactFormData) => {
    setIsSubmitting(true);
    try {
      contactSchema.parse(values);

      const response = await fetch('/api/v1/send', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      if (!response.ok) {
        message.error('Failed to send message. Please try again.');
        setIsSubmitting(false); 
      }

      const data = await response.json();

      if (data.message === 'success') {
        message.success('Message sent successfully!');
        setIsSubmitting(false);
        form.resetFields();
      } else {
        throw new Error('Failed to send message');
      }
    } catch (error) {
      if (error instanceof z.ZodError) {
        error.errors.forEach((err) => {
          message.error(err.message);
          setIsSubmitting(false);
        });
      } else {
        message.error('Failed to send message. Please try again.');
        setIsSubmitting(false);
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
      

Get in Touch

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

} placeholder="Your Name" size="large" /> } placeholder="Your Email" size="large" /> } placeholder="Subject" size="large" />
); }; export default ContactPage;

Testing

Till now, we're all set, now it's time to run and test our application.

Start your server:

yarn dev

First, let's try to hit the endpoint without filling out the form. As expected, the API doesn't get called, and we receive error messages.

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

Now, let's fill out the form

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

and hit the send button. It's in process.

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

Here we go, the message is sent. The sender receives a notification saying "Message sent," and the form is also refreshed.

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

The receiver also gets the message?

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

And that's it. We have successfully built an email contact form in Next.js using Resend and Zod.

Conclusion

In this article, we built a contact form using Next.js and implemented features like form validation with Zod and email functionality with Resend. We start by setting up the Next.js project, configuring necessary dependencies, and managing environment variables for secure API access.

Then, we designed the email template, set up an API route for handling email submissions, and implemented the frontend form with Ant Design components.

If you want to see a live preview of it, you can check it out here. I have implemented the same form in my portfolio.

Thanks for reading this blog. If you learned something from it, please like and share it with your friends and community. I write blogs and share content on JavaScript, TypeScript, Open Source, and other web development-related topics. Feel free to follow me on my socials. I'll see you in the next one. Thank You :)

Twitter

LinkedIn

GitHub

版本声明 本文转载于:https://dev.to/shivamkatare/how-to-create-dynamic-email-contact-form-in-nextjs-using-resend-and-zod-50d?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何使用 JSTL 迭代 HashMap 中的 ArrayList?
    如何使用 JSTL 迭代 HashMap 中的 ArrayList?
    使用 JSTL 迭代 HashMap 中的 ArrayList在 Web 开发中,JSTL(JavaServer Pages 标准标记库)提供了一组标记来简化 JSP 中的常见任务( Java 服务器页面)。其中一项任务是迭代数据结构。要迭代 HashMap 及其中包含的 ArrayList,可以使...
    编程 发布于2024-11-05
  • Encore.ts — 比 ElysiaJS 和 Hono 更快
    Encore.ts — 比 ElysiaJS 和 Hono 更快
    几个月前,我们发布了 Encore.ts — TypeScript 的开源后端框架。 由于已经有很多框架,我们想分享我们做出的一些不常见的设计决策以及它们如何带来卓越的性能数据。 性能基准 我们之前发布的基准测试显示 Encore.ts 比 Express 快 9 倍,比 Fasti...
    编程 发布于2024-11-05
  • 为什么使用 + 对字符串文字进行字符串连接失败?
    为什么使用 + 对字符串文字进行字符串连接失败?
    连接字符串文字与字符串在 C 中,运算符可用于连接字符串和字符串文字。但是,此功能存在限制,可能会导致混乱。在问题中,作者尝试连接字符串文字“Hello”、“,world”和“!”以两种不同的方式。第一个例子:const string hello = "Hello"; const...
    编程 发布于2024-11-05
  • React 重新渲染:最佳性能的最佳实践
    React 重新渲染:最佳性能的最佳实践
    React高效的渲染机制是其受欢迎的关键原因之一。然而,随着应用程序复杂性的增加,管理组件重新渲染对于优化性能变得至关重要。让我们探索优化 React 渲染行为并避免不必要的重新渲染的最佳实践。 1. 使用 React.memo() 作为函数式组件 React.memo() 是一个高...
    编程 发布于2024-11-05
  • 如何实现条件列创建:探索 Pandas DataFrame 中的 If-Elif-Else?
    如何实现条件列创建:探索 Pandas DataFrame 中的 If-Elif-Else?
    Creating a Conditional Column: If-Elif-Else in Pandas给定的问题要求将新列添加到 DataFrame 中基于一系列条件标准。挑战在于在实现这些条件的同时保持代码效率和可读性。使用函数应用程序的解决方案一种方法涉及创建一个将每一行映射到所需结果的函数...
    编程 发布于2024-11-05
  • 介绍邱!
    介绍邱!
    我很高兴地宣布发布 Qiu – 一个严肃的 SQL 查询运行器,旨在让原始 SQL 再次变得有趣。老实说,ORM 有其用武之地,但当您只想编写简单的 SQL 时,它们可能会有点让人不知所措。我一直很喜欢编写原始 SQL 查询,但我意识到我需要练习——大量的练习。这就是Qiu发挥作用的地方。 有了 Q...
    编程 发布于2024-11-05
  • 为什么 CSS 中的 Margin-Top 百分比是根据容器宽度计算的?
    为什么 CSS 中的 Margin-Top 百分比是根据容器宽度计算的?
    CSS 中的 margin-top 百分比计算当对元素应用 margin-top 百分比时,必须了解计算方式执行。与普遍的看法相反,边距顶部百分比是根据包含块的宽度而不是其高度来确定的。W3C 规范解释:根据W3C 规范,“百分比是根据生成的框包含块的宽度计算的。”此规则适用于“margin-top...
    编程 发布于2024-11-05
  • 如何解决 CSS 转换期间 Webkit 文本渲染不一致的问题?
    如何解决 CSS 转换期间 Webkit 文本渲染不一致的问题?
    解决 CSS 转换期间的 Webkit 文本渲染不一致在 CSS 转换期间,特别是缩放元素时,Webkit 中可能会出现文本渲染不一致的情况浏览器。这个问题源于浏览器尝试优化渲染性能。一种解决方案是通过添加以下属性来强制对过渡元素的父元素进行硬件加速:-webkit-transform: trans...
    编程 发布于2024-11-05
  • 使用 Reactables 简化 RxJS
    使用 Reactables 简化 RxJS
    介绍 RxJS 是一个功能强大的库,但众所周知,它的学习曲线很陡峭。 该库庞大的 API 界面,再加上向反应式编程的范式转变,可能会让新手不知所措。 我创建了 Reactables API 来简化 RxJS 的使用并简化开发人员对反应式编程的介绍。 例子 我们将构建...
    编程 发布于2024-11-05
  • 如何在 Pandas 中查找多列的最大值?
    如何在 Pandas 中查找多列的最大值?
    查找 Pandas 中多列的最大值要确定 pandas DataFrame 中多列的最大值,可以采用多种方法。以下是实现此目的的方法:对指定列使用 max() 函数此方法涉及显式选择所需的列并应用 max() 函数: df[["A", "B"]] df[[&q...
    编程 发布于2024-11-05
  • CI/CD 入门:自动化第一个管道的初学者指南(使用 Jenkins)
    CI/CD 入门:自动化第一个管道的初学者指南(使用 Jenkins)
    目录 介绍 什么是 CI/CD? 持续集成(CI) 持续交付(CD) 持续部署 CI/CD 的好处 更快的上市时间 提高代码质量 高效协作 提高自动化程度和一致性 如何创建您的第一个 CI/CD 管道 第 1 步:设置版本控制 (GitHub) 第 2 步:选择 CI/CD 工具 ...
    编程 发布于2024-11-05
  • TypeScript 如何使 JavaScript 在大型项目中更加可靠。
    TypeScript 如何使 JavaScript 在大型项目中更加可靠。
    介绍 JavaScript 广泛应用于 Web 开发,现在也被应用于不同行业的大型项目中。然而,随着这些项目的增长,管理 JavaScript 代码变得更加困难。数据类型不匹配、运行时意外错误以及代码不清晰等问题可能会导致查找和修复错误变得困难。 这就是TypeScript介入的地...
    编程 发布于2024-11-05
  • 如何使用PHP的password_verify函数安全地验证用户密码?
    如何使用PHP的password_verify函数安全地验证用户密码?
    使用 PHP 解密加密密码许多应用程序使用密码哈希等加密算法安全地存储用户密码。然而,在验证登录尝试时,将输入密码与加密的存储版本进行比较非常重要。加密问题password_hash 使用 Bcrypt,一种一元加密算法方式哈希算法,意味着加密的密码无法逆转或解密。这是一项安全功能,可确保即使数据库...
    编程 发布于2024-11-05
  • 学习 Vue 部分 构建天气应用程序
    学习 Vue 部分 构建天气应用程序
    深入研究 Vue.js 就像在 DIY 工具包中发现了一个新的最喜欢的工具——直观、灵活,而且功能强大得惊人。我接触 Vue 的第一个副业项目是一个天气应用程序,它教会了我很多关于框架功能以及一般 Web 开发的知识。这是我到目前为止所学到的。 1. Vue 入门:简单与强大 Vue...
    编程 发布于2024-11-05
  • NFT 预览卡组件
    NFT 预览卡组件
    ?刚刚完成了我的最新项目:使用 HTML 和 CSS 的“NFT 预览卡组件”! ?查看并探索 GitHub 上的代码。欢迎反馈! ? GitHub:[https://github.com/khanimran17/NFT-preview-card-component] ?现场演示:[https://...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3