在本博客的第一部分中探讨了如何使用 NextAuth.js(Auth.js) 在 Next.js 14 中实现身份验证系统后,采取下一步以确保用户信息的有效性至关重要:电子邮件验证。
此过程不仅是我们应用程序安全性的额外步骤,也是确保用户与平台之间的交互合法且安全的重要组成部分。
在第二部分中,我们将重点关注通过发送电子邮件来集成电子邮件验证、使用 Resend 发送电子邮件以及 React Email 创建有吸引力且实用的电子邮件模板。
确保您的项目已经实现了博客第一部分中描述的身份验证系统。这包括正确配置 Next.js 14 和 NextAuth。
安装项目中需要的依赖项。这次我们将使用pnpm
您可以使用您选择的包管理器。
pnpm add resend react-email @react-email/components
2. 为项目创建以下结构:
... ├── emails/ │ └── verification-template.tsx ... ├── src/ │ ├── actions/ │ │ ├── email-actions.tsx │ │ └── auth-actions.tsx │ ├── app/ │ │ ... │ │ ├── (primary)/ │ │ │ ├── auth/ │ │ │ │ └── verify-email/ │ │ │ │ └── page.tsx │ │ │ ├── layout.tsx │ │ │ └── page.tsx │ │ │ ... │ ├── components/ │ │ └── auth/ │ │ ├── signin-form.tsx │ │ ├── signup-form.tsx │ │ ... │ ... │ ├── utils.ts │ ... ... ├── .env ...
React Email 允许您使用 JSX 创建电子邮件模板,这有助于创建具有吸引力且与您的品牌一致的电子邮件。
让我们创建一个基本的电子邮件模板作为 React 组件。在这种情况下,我们将创建将发送给用户以确认其电子邮件的模板。
emails/verification-template.tsx
:
// Import React and necessary components from @react-email/components import * as React from 'react'; import { Body, Button, Container, Head, Hr, Html, Img, Preview, Section, Text } from '@react-email/components'; import { getBaseUrl } from '@/utils'; // Obtain the base URL using the imported function const baseUrl = getBaseUrl(); // Define the properties expected by the VerificationTemplate component interface VerificationTemplateProps { username: string; emailVerificationToken: string; } // Define the VerificationTemplate component that takes the defined properties export const VerificationTemplate = ({ username, emailVerificationToken }: VerificationTemplateProps) => ( <Html> <Head /> <Preview>Preview text that appears in the email client before opening the email.</Preview> <Body style={main}> <Container style={container}> <Img src='my-logo.png' alt='My SaaS' style={logo} /> <Text style={title}>Hi {username}!</Text> <Text style={title}>Welcome to Starter Kit for building a SaaS</Text> <Text style={paragraph}>Please verify your email, with the link below:</Text> <Section style={btnContainer}> {/* Button that takes the user to the verification link */} <Button style={button} href={`${baseUrl}/auth/verify-email?token=${emailVerificationToken}`} > Click here to verify </Button> </Section> <Hr style={hr} /> <Text style={footer}>Something in the footer.</Text> </Container> </Body> </Html> ); // Styles applied to different parts of the email for customization const main = { backgroundColor: '#020817', color: '#ffffff', fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif', }; const container = { margin: '0 auto', padding: '20px 0 48px', }; ...
该组件创建一个包含样式和动态内容的 HTML 电子邮件模板。
属性被定义为接收username
y emailVerificationToken
。这些属性用于为用户自定义电子邮件并生成验证链接。
为了验证和测试模板,React Email 提供了一个命令来本地运行服务器,该服务器将公开我们在电子邮件文件夹中创建的模板。
我们在package.json
中创建脚本来运行服务器。
{ "scripts": { "dev": "email dev" } }
2. 我们执行脚本,这将在localhost
上运行服务器;我们将看到如下所示的屏幕,其中包含创建的所有模板。
在我们的例子中,我们只有一个模板。如下所示,我们预览了将发送给用户的电子邮件。
... # resend RESEND_API_KEY="re_jYiFaXXXXXXXXXXXXXXXXXXX"
4. 要创建发送电子邮件的功能,我们可以在api/
文件夹内创建端点并发出http
请求,但是,在这种情况下,我们将利用服务器操作潜力来完成此操作。
actions/email-actions.ts
:
'use server' import React from 'react' import { Resend } from 'resend' // Creates an instance of Resend using the API KEY const resend = new Resend(process.env.RESEND_API_KEY) // Defines the data structure for an email. interface Email { to: string[] // An array of email addresses to which to send the email. subject: string // The subject of the email. react: React.ReactElement // The body of the email as a React element. } export const sendEmail = async (payload: Email) => { const { error } = await resend.emails.send({ from: 'My SaaS <[email protected]>', // Defines the sender's address. ...payload, // Expands the contents of 'payload' to include 'to', 'subject', and 'react'. }) if (error) { console.error('Error sending email', error) return null } console.log('Email sent successfully') return true }
注意:要在免费开发中进行测试,您必须使用电子邮件“[email protected]”作为发件人,否则,您必须添加自定义域。
5. 新用户注册时发送邮件。
actions/auth-actions.ts
:
... import { sendEmail } from './email-actions' import VerificationTemplate from '../../emails/verification-template' // Import a utility function to generate a secure token. import { generateSecureToken } from '@/utils' export async function registerUser(user: Partial<User>) { try { // Creates a new user in the database with the provided data. // Passwords are hashed using bcrypt for security. const createdUser = await prisma.user.create({ data: { ...user, password: await bcrypt.hash(user.password as string, 10), } as User, }) // Generates a secure token to be used for email verification. const emailVerificationToken = generateSecureToken() // Updates the newly created user with the email verification token. await prisma.user.update({ where: { id: createdUser.id, }, data: { emailVerificationToken, }, }) // Sends a verification email to the new user using the sendEmail function. await sendEmail({ to: ['your Resend registered email', createdUser.email], subject: 'Verify your email address', react: React.createElement(VerificationTemplate, { username: createdUser.username, emailVerificationToken }), }) return createdUser } catch (error) { console.log(error) if (error instanceof Prisma.PrismaClientKnownRequestError) { if (error.code === 'P2002') { // Returns a custom error message if the email already exists in the database. return { error: 'Email already exists.' } } } return { error: 'An unexpected error occurred.' } } }
创建用户并生成验证令牌后,该函数会向新用户发送一封电子邮件。
此电子邮件是使用VerificationTemplate
React 组件构建的,并使用用户名和验证令牌进行个性化设置。此步骤对于验证用户的电子邮件地址是否有效并由用户控制至关重要。
电子邮件发送给用户后,将有一个链接将他带回该网站。为了验证电子邮件,为此,我们需要创建页面。
(primary)/auth/verify-email/page.tsx
:
/* All imports */ // Defines the prop types for the VerifyEmailPage component. interface VerifyEmailPageProps { searchParams: { [key: string]: string | string[] | undefined } } export default async function VerifyEmailPage({ searchParams }: VerifyEmailPageProps) { let message = 'Verifying email...' let verified = false if (searchParams.token) { // Checks if a verification token is provided in the URL. // Attempts to find a user in the database with the provided email verification token. const user = await prisma.user.findUnique({ where: { emailVerificationToken: searchParams.token as string, }, }) // Conditionally updates the message and verified status based on the user lookup. if (!user) { message = 'User not found. Check your email for the verification link.' } else { // If the user is found, updates the user record to mark the email as verified. await prisma.user.update({ where: { emailVerificationToken: searchParams.token as string, }, data: { emailVerified: true, emailVerificationToken: null, // Clears the verification token. }, }) message = `Email verified! ${user.email}` verified = true // Sets the verified status to true. } } else { // Updates the message if no verification token is found. message = 'No email verification token found. Check your email.' } return ( <div className='grid place-content-center py-40'> <Card className='max-w-sm text-center'> <CardHeader> <CardTitle>Email Verification</CardTitle> </CardHeader> <CardContent> <div className='w-full grid place-content-center py-4'> {verified ? <EmailCheckIcon size={56} /> : <EmailWarningIcon size={56} />} </div> <p className='text-lg text-muted-foreground' style={{ textWrap: 'balance' }}> {message} </p> </CardContent> <CardFooter> {verified && ( // Displays a sign-in link if the email is successfully verified. <Link href={'/auth/signin'} className='bg-primary text-white text-sm font-medium hover:bg-primary/90 h-10 px-4 py-2 rounded-lg w-full text-center'> Sign in </Link> )} </CardFooter> </Card> </div> ) }
成功验证用户的电子邮件后,我们将看到以下消息。
现在,我们将在用户想要登录但尚未验证其电子邮件时实施最后一次验证。
components/auth/sigin-form.tsx
:
... async function onSubmit(values: InputType) { try { setIsLoading(true) const response = await signIn('credentials', { redirect: false, email: values.email, password: values.password, }) if (!response?.ok) { // if the email is not verified we will show a message to the user. if (response?.error === 'EmailNotVerified') { toast({ title: 'Please, verify your email first.', variant: 'warning', }) return } toast({ title: 'Something went wrong!', description: response?.error, variant: 'destructive', }) return } toast({ title: 'Welcome back! ', description: 'Redirecting you to your dashboard!', }) router.push(callbackUrl ? callbackUrl : '/') } catch (error) { console.log({ error }) toast({ title: 'Something went wrong!', description: "We couldn't create your account. Please try again later!", variant: 'destructive', }) } finally { setIsLoading(false) } } ...
就是这样! 🎉
用户将能够验证他的电子邮件并在我们的应用程序中完成注册。
🧑💻
我们已经知道如何使用 React Email 和 Resend 创建和发送电子邮件。此过程允许您利用 React 知识高效地设计电子邮件,同时保持熟悉且高效的工作流程。
您可以尝试使用不同的组件和属性来创建完全适合您的项目需求的电子邮件。
想与作者联系吗?
喜欢通过𝕏与世界各地的朋友联系。
也发布在这里