Next.js 是一個強大的全端框架,允許我們建立具有前端和後端功能的應用程式。它非常靈活,可用於從簡單的靜態網站到複雜的 Web 應用程式的所有內容。今天,我們將使用 Next.js 建立電子郵件聯絡表單。
表單是任何網站的關鍵部分,讓使用者與應用程式互動。無論是註冊、登入、提供回饋或收集數據,表單對於使用者體驗都至關重要。如果沒有表單,全端應用程式將無法正確收集和處理使用者輸入。
在本部落格中,我將向您展示如何使用 Next.js、Resend 和 Zod(用於表單驗證)建立電子郵件聯絡表單。我們將介紹設定項目、設計表單、處理表單提交以及建立單獨的 API 路徑。最後,您將了解如何建立表單並將其添加到您的 Next.js 應用程序,確保您的 Web 應用程式運作良好且易於使用。
那麼,事不宜遲,讓我們開始吧。
Resend 是開發人員的現代電子郵件 API。它旨在使從您的應用程式發送電子郵件變得簡單、可靠且可擴展。與傳統電子郵件服務不同,Resend 專為開發人員而構建,提供簡單的 API,可與各種程式語言和框架(包括 Next.js)無縫整合。
在我們的 Next.js 表單專案中,我們將使用 Resend 發送電子郵件。當使用者提交表單時,我們將使用 Resend 的 API 發送確認電子郵件或根據需要處理表單資料。
Zod 是一個強大的資料工具。它是一個 TypeScript 優先的庫,可以幫助您定義和檢查資料的形狀。將其視為為資料設定規則,然後在使用資料之前確保資料符合這些規則。
如果你正在使用 TypeScript(如果你沒有,你應該考慮它!),Zod 可以很好地使用它。它可以自動從您的模式推斷 TypeScript 類型,這可以節省大量時間。 TypeScript 在編譯時檢查類型,而 Zod 在執行時檢查類型。這意味著您可以捕獲可能透過靜態類型檢查的資料問題。您可以將 Zod 用於各種資料驗證場景,從簡單的表單輸入到複雜的 API 回應。
讓我們先設定具有所有必要依賴項的 Next.js 專案。我們將使用 TypeScript 實現類型安全,使用 Tailwind CSS 進行樣式設計,使用 Ant Design 進行 UI 元件,使用 Zod 進行表單驗證,並使用 Resend 進行電子郵件功能。
npx create-next-app@latest my-contact-form --typescript cd my-contact-form
yarn add antd zod resend react-icons
為了發送電子郵件,我們將使用重新發送,因此我們需要重新發送 API 金鑰。在啟動我們的伺服器之前,讓我們轉到重新傳送並取得我們的 API 金鑰。按一下此處前往重新傳送站點,然後按一下登入按鈕。
登入後,您將被重新導向到此頁面。在這裡,您將看到從表單收到的所有電子郵件。
在這裡,點擊 API 金鑰部分
然後,點選此產生 API 金鑰?按鈕
現在,複製該 API 金鑰並妥善保管。接下來,打開 VSCode 並在根資料夾中建立一個名為 .env 的新檔案。在那裡新增一個環境變數。
RESEND_API_KEY=yourapikeywillbehere
現在您也可以使用此命令運行伺服器。
yarn dev
讓我們從建立電子郵件範本開始。這將是當有人透過聯絡表單向您發送電子郵件時您收到的範本。
import * as React from 'react'; interface EmailTemplateProps { firstName: string; message: string; } export const EmailTemplate: React.FC<EmailTemplateProps> = ({ firstName, message, }) => ( <div> <h1>Hello, I am {firstName}!</h1> <p>You have received a new message from your Portfolio:</p> <p>{message}</p> </div> );
這個簡單的 React 元件定義了當有人提交聯絡表單時將發送的電子郵件的結構。它需要兩個屬性:firstName 和 message。此元件使用名字建立個人化問候語並顯示提交的訊息。
這裡。我們將了解如何使用 Resend API 實作電子郵件傳送功能。
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 <onboarding@resend.dev>', 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 }); } }
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:
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 <onboarding@resend.dev>', 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:
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 ?
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
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';
Now, let's create our UI, and then we'll move on to the logic. Our form will look something like this.?
In your page.tsx, after all the import statements, define a component and add a return statement first.
const ContactPage: React.FC = () => { return ( <div className="max-w-3xl w-full space-y-8 bg-white p-10 rounded-xl shadow-2xl"> /* our code will be here */ </div> ); }; export default ContactPage;
Currently, we have just a simple div with a few tailwind styling now, we'll first add our heading part.
... <div> <h2 className="mt-1 text-center text-3xl font-extrabold text-gray-900">Get in Touch</h2> <p className="mt-1 mb-4 text-center text-sm text-gray-600"> I'd love to hear from you! Fill out the form below to get in touch. </p> </div> ...
Now, let's add our input fields
... <Form form={form} name="contact" onFinish={onFinish} layout="vertical" className="mt-8 space-y-6" > <Form.Item name="name" rules={[{ required: true, message: 'Please input your name!' }]} > <Input prefix={<FaUser className="site-form-item-icon" />} placeholder="Your Name" size="large" /> </Form.Item> <Form.Item name="email" rules={[ { required: true, message: 'Please input your email!' }, { type: 'email', message: 'Please enter a valid email!' } ]} > <Input prefix={<MdMail className="site-form-item-icon" />} placeholder="Your Email" size="large" /> </Form.Item> <Form.Item name="subject" rules={[{ required: true, message: 'Please input a subject!' }]} > <Input prefix={<FaMessage className="site-form-item-icon" />} placeholder="Subject" size="large" /> </Form.Item> <Form.Item name="message" rules={[{ required: true, message: 'Please input your message!' }]} > <TextArea placeholder="Your Message" autoSize={{ minRows: 4, maxRows: 8 }} /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit" className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" disabled={isSubmitting} > {isSubmitting ? 'Sending...' : 'Send Message'} </Button> </Form.Item> </Form> ...
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 form={form} name="contact" onFinish={onFinish} layout="vertical" className="mt-8 space-y-6" > {/* Form items */} </Form>
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.
<Form.Item name="name" rules={[{ required: true, message: 'Please input your name!' }]} > <Input prefix={<FaUser className="site-form-item-icon" />} placeholder="Your Name" size="large" /> </Form.Item>
Similarly, we have Email and other fields.
<Form.Item name="email" rules={[ { required: true, message: 'Please input your email!' }, { type: 'email', message: 'Please enter a valid email!' } ]} > <Input prefix={<MdMail className="site-form-item-icon" />} placeholder="Your Email" size="large" /> </Form.Item>
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
<Form.Item> <Button type="primary" htmlType="submit" className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" disabled={isSubmitting} > {isSubmitting ? 'Sending...' : 'Send Message'} </Button> </Form.Item>
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.
So, in the logic part, we have a few things to do:
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<typeof contactSchema>;
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:
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<ContactFormData>(); 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:
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<typeof contactSchema>; const ContactPage: React.FC = () => { const [form] = Form.useForm<ContactFormData>(); 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 (); }; export default ContactPage;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" />
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.
Now, let's fill out the form
and hit the send button. It's in process.
Here we go, the message is sent. The sender receives a notification saying "Message sent," and the form is also refreshed.
The receiver also gets the message?
And that's it. We have successfully built an email contact form in Next.js using Resend and Zod.
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 :)
GitHub
以上是如何使用 Resend 和 Zod 在 Next.js 中建立動態電子郵件聯絡表單的詳細內容。更多資訊請關注PHP中文網其他相關文章!