paint-brush
Next.js 14'te NextAuth.js, Yeniden Gönderme ve E-postayla Tepki Verme ile E-posta Doğrulaması Nasıl Gönderilirby@ljaviertovar
2,701
2,701

Next.js 14'te NextAuth.js, Yeniden Gönderme ve E-postayla Tepki Verme ile E-posta Doğrulaması Nasıl Gönderilir

L Javier Tovar12m2024/04/02
Read on Terminal Reader

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.
featured image - Next.js 14'te NextAuth.js, Yeniden Gönderme ve E-postayla Tepki Verme ile E-posta Doğrulaması Nasıl Gönderilir
L Javier Tovar HackerNoon profile picture
0-item
1-item

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.


Next.js'de Yeniden Gönderme ve Ract E-posta Entegrasyonu

Kurulum

  1. Projede ihtiyaç duyulan bağımlılıkları yükleyin. Bu sefer pnpm kullanacağız, siz istediğiniz paket yöneticisini kullanabilirsiniz.


 pnpm add resend react-email @react-email/components




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, username ve emailVerificationToken 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.


Ş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.


  1. Sunucuyu çalıştırmak için package.json dosyasında script oluşturuyoruz.


 { "scripts": { "dev": "email dev" } }


2. Komut dosyasını çalıştırıyoruz ve bu, sunucuyu localhost üzerinde çalıştıracaktır; Oluşturulan tüm şablonların olduğu aşağıdaki gibi bir ekran göreceğiz.


Yerel Tepki E-postası


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.


Eposta Doğrulama


Yeniden Gönder ile E-posta Gönderme

  1. Oluşturmak Hesabı yeniden gönder .
  2. Yeni bir tane oluştur API ANAHTARI .
  3. API KEY .env dosyasına ekleyin.


 ... # resend RESEND_API_KEY="re_jYiFaXXXXXXXXXXXXXXXXXXX"


4. E-posta gönderme işlevini oluşturmak için api/ klasörü içinde uç noktalar oluşturup http isteklerinde bulunabiliriz ancak bu durumda bunu sunucu eylemleri potansiyelinden yararlanarak yapacağız.


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 }


Not: Ücretsiz geliştirmeyi test etmek için gönderen olarak "[email protected]" 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 VerificationTemplate 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.


Başarıyla kaydoldum


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.


Belirteci doğrulama sayfası


Ş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) } } ... 


Eposta Doğrulama


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.


Burada da yayınlandı