Bu blogun ilk bölümünde Next.js 14'te NextAuth.js(Auth.js) ile bir kimlik doğrulama sisteminin nasıl uygulanacağını araştırdıktan sonra, kullanıcı bilgilerinin geçerliliğini sağlamak için bir sonraki adımı atmak çok önemlidir: e-posta doğrulama. Bu süreç yalnızca uygulamamızın güvenliğinde ek bir adım değil, aynı zamanda kullanıcı ile platform arasındaki etkileşimlerin meşru ve güvenli olmasını sağlamak için önemli bir bileşendir. Bu ikinci bölümde, e-posta göndererek e-posta doğrulamayı entegre etmeye, e-posta göndermek için Yeniden Gönder'i kullanmaya ve çekici ve işlevsel e-posta şablonları oluşturmak için React E-postayı kullanmaya odaklanacağız. Başlangıç konfigürasyonu Projenizde blogun ilk bölümünde açıklanan kimlik doğrulama sisteminin zaten uygulandığından emin olun. Buna Next.js 14 ve NextAuth'un doğru yapılandırılması da dahildir. https://hackernoon.com/how-to-implement-authentication-in-nextjs-14-with-nextauthjs-shadcnui-react-hook-form-and-zod?embedable=true Next.js'de Yeniden Gönderme ve Ract E-posta Entegrasyonu Kurulum Projede ihtiyaç duyulan bağımlılıkları yükleyin. Bu sefer kullanacağız, siz istediğiniz paket yöneticisini kullanabilirsiniz. pnpm pnpm add resend react-email @react-email/components : e-posta göndermek için. Yeniden gönder : React ve TypeScript kullanarak güzel e-postalar oluşturmak için. E-postaya tepki ver 2. Proje için aşağıdaki yapıyı oluşturun: ... ├── 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 ile E-posta Şablonları Oluşturma React Email, markanızla ilgili çekici ve tutarlı e-postalar oluşturmanızı kolaylaştıran JSX'i kullanarak e-posta şablonları oluşturmanıza olanak tanır. React bileşeni olarak temel bir e-posta şablonu oluşturalım. Bu durumda kullanıcıya e-postasını onaylaması için gönderilecek şablonu oluşturacağız. : 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', }; ... Bu bileşen, stiller ve dinamik içerik içeren bir HTML e-posta şablonu oluşturur. Özellikler, ve alacak şekilde tanımlanır. Bu özellikler, kullanıcı için e-postayı özelleştirmek ve doğrulama bağlantısını oluşturmak için kullanılır. username emailVerificationToken Şablonu doğrulamak ve test etmek için React Email, e-postalar klasöründe oluşturduğumuz şablonları açığa çıkaracak bir sunucuyu yerel olarak çalıştırmak için bir komut sağlar. Sunucuyu çalıştırmak için dosyasında script oluşturuyoruz. package.json { "scripts": { "dev": "email dev" } } 2. Komut dosyasını çalıştırıyoruz ve bu, sunucuyu üzerinde çalıştıracaktır; Oluşturulan tüm şablonların olduğu aşağıdaki gibi bir ekran göreceğiz. localhost Bizim durumumuzda yalnızca bir şablonumuz var. Aşağıda görebileceğiniz gibi kullanıcıya gönderilecek e-postanın önizlemesini görüyoruz. Yeniden Gönder ile E-posta Gönderme Oluşturmak . Hesabı yeniden gönder Yeni bir tane oluştur . API ANAHTARI dosyasına ekleyin. API KEY .env ... # resend RESEND_API_KEY="re_jYiFaXXXXXXXXXXXXXXXXXXX" 4. E-posta gönderme işlevini oluşturmak için klasörü içinde uç noktalar oluşturup isteklerinde bulunabiliriz ancak bu durumda bunu sunucu eylemleri potansiyelinden yararlanarak yapacağız. 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 <onboarding@resend.dev>', // 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 } Not: Ücretsiz geliştirmeyi test etmek için gönderen olarak "onboarding@resend.dev" e-postasını kullanmanız gerekir, aksi takdirde özel bir alan adı eklemeniz gerekir. 5. Yeni bir kullanıcıyı kaydederken e-postayı gönderin. : 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.' } } } Kullanıcı oluşturulduğunda ve doğrulama jetonu oluşturulduktan sonra işlev, yeni kullanıcıya bir e-posta gönderir. Bu e-posta, kullanıcının adı ve doğrulama jetonuyla kişiselleştirilen React bileşeni kullanılarak oluşturulmuştur. Bu adım, kullanıcının e-posta adresinin geçerli olduğunu ve kullanıcı tarafından kontrol edildiğini doğrulamak için çok önemlidir. VerificationTemplate Belirteci Doğrulama Sayfası E-posta kullanıcıya gönderildiğinde, bu kullanıcıyı siteye geri götürecek bir bağlantıya sahip olacaktır. E-postayı doğrulamak için bunun için sayfayı oluşturmamız gerekiyor. : (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> ) } Kullanıcının e-postasını başarıyla doğruladıktan sonra aşağıdaki mesajı göreceğiz. Şimdi, kullanıcı oturum açmak istediğinde ve e-posta adresini henüz doğrulamadığında son doğrulamayı uygulayacağız. : 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) } } ... Bu kadar! 🎉 Kullanıcı e-postasını doğrulayabilecek ve uygulamamıza kaydını tamamlayabilecektir. 🧑💻 Buraya kopyala Çözüm React Email ve Resend'i kullanarak e-postaların nasıl oluşturulacağını ve gönderileceğini zaten biliyoruz. Bu süreç, tanıdık ve üretken bir iş akışını sürdürürken e-postaları verimli bir şekilde tasarlamak için React bilginizden yararlanmanıza olanak tanır. Projelerinizin ihtiyaçlarına mükemmel şekilde uyan e-postalar oluşturmak için farklı bileşenler ve özelliklerle denemeler yapabilirsiniz. Yazarla bağlantı kurmak ister misiniz? üzerinden dünyanın her yerindeki arkadaşlarla bağlantı kurmayı seviyorum. 𝕏 da yayınlandı Burada