paint-brush
Como enviar verificação de e-mail em Next.js 14 com NextAuth.js, reenviar e reagir e-mailpor@ljaviertovar
1,442 leituras
1,442 leituras

Como enviar verificação de e-mail em Next.js 14 com NextAuth.js, reenviar e reagir e-mail

por L Javier Tovar12m2024/04/02
Read on Terminal Reader

Muito longo; Para ler

Tendo explorado como implementar um sistema de autenticação em Next.js 14 com NextAuth.js(Auth.js) na primeira parte deste blog, é crucial dar o próximo passo para garantir a validade das informações do usuário: validação de email. Este processo não é apenas uma etapa adicional na segurança da nossa aplicação, mas um componente essencial para garantir que as interações entre o usuário e a plataforma sejam legítimas e seguras. Nesta segunda parte, focaremos na integração da validação de email através do envio de emails, usando Reenviar para envio de emails e React Email para criar modelos de email atraentes e funcionais.
featured image - Como enviar verificação de e-mail em Next.js 14 com NextAuth.js, reenviar e reagir e-mail
L Javier Tovar HackerNoon profile picture
0-item
1-item

Tendo explorado como implementar um sistema de autenticação em Next.js 14 com NextAuth.js(Auth.js) na primeira parte deste blog, é crucial dar o próximo passo para garantir a validade das informações do usuário: validação de email.


Este processo não é apenas uma etapa adicional na segurança da nossa aplicação, mas um componente essencial para garantir que as interações entre o usuário e a plataforma sejam legítimas e seguras.


Nesta segunda parte, focaremos na integração da validação de email através do envio de emails, usando Reenviar para envio de emails e React Email para criar modelos de email atraentes e funcionais.

Configuração inicial

Certifique-se de que seu projeto já possua o sistema de autenticação descrito na primeira parte do blog implementado. Isso inclui ter Next.js 14 e NextAuth configurados corretamente.


Integração de reenvio e recebimento de e-mail em Next.js

Configurando

  1. Instale as dependências necessárias no projeto. Desta vez usaremos pnpm você pode usar o gerenciador de pacotes de sua preferência.


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




2. Crie a seguinte estrutura para o projeto:


 ... ├── 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 ...


Criando modelos de email com React Email

React Email permite criar templates de email usando JSX, o que facilita a criação de emails atrativos e consistentes com sua marca.


Vamos criar um modelo de email básico como um componente React. Neste caso, criaremos o template que será enviado para o usuário confirmar seu email.


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', }; ...


Este componente cria um modelo de email HTML que inclui estilos e conteúdo dinâmico.


As propriedades são definidas para receber username e emailVerificationToken . Essas propriedades são usadas para personalizar o email do usuário e gerar o link de verificação.


Para validar e testar o template, o React Email fornece um comando para executar localmente um servidor que irá expor os templates que criamos dentro da pasta de emails.


  1. Criamos o script no package.json para executar o servidor.


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


2. Executamos o script e este executará o servidor em localhost ; veremos uma tela como a seguinte com todos os templates criados.


E-mail de reação local


No nosso caso, temos apenas um modelo. Como você pode ver abaixo, temos uma prévia do e-mail que será enviado ao usuário.


Verificação de e-mail


Envio de e-mails com reenvio

  1. Criar uma Reenviar conta .
  2. Crie um novo CHAVE API .
  3. Adicione a API KEY ao arquivo .env .


 ... # resend RESEND_API_KEY="re_jYiFaXXXXXXXXXXXXXXXXXXX"


4. Para criar a funcionalidade de envio de emails, poderíamos criar endpoints dentro da pasta api/ e fazer solicitações http , porém, nesta ocasião faremos isso aproveitando o potencial de ações do servidor.


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 }


Nota: Para testar em desenvolvimento livre, você deve usar como remetente o e-mail “[email protected]”, caso contrário, você terá que adicionar um domínio personalizado.


5. Envie o e-mail ao cadastrar um novo usuário.


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.' } } }


Depois que o usuário é criado e o token de verificação gerado, a função envia um email para o novo usuário.


Este email é construído usando o componente VerificationTemplate React, personalizado com o nome do usuário e token de verificação. Esta etapa é crucial para verificar se o endereço de e-mail do usuário é válido e controlado pelo usuário.


Inscrito com sucesso


Página para validar o token

Assim que o e-mail for enviado ao usuário, este conterá um link que o levará de volta ao site. Para validar o email, para isso precisamos criar a página.


(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> ) }


Após validar com sucesso o email do usuário, veremos a seguinte mensagem.


Página para validar o token


Agora, implementaremos uma última validação para quando o usuário deseja fazer login e ainda não verificou seu e-mail.


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


Verificação de e-mail


É isso! 🎉


O usuário poderá validar seu e-mail e finalizar seu cadastro em nosso aplicativo.


🧑‍💻 Reponha aqui

Conclusão

Já sabemos como criar e enviar emails usando React Email e Resend. Este processo permite que você aproveite seu conhecimento do React para criar e-mails com eficiência, mantendo um fluxo de trabalho familiar e produtivo.


Você pode experimentar diferentes componentes e propriedades para criar e-mails que atendam perfeitamente às necessidades de seus projetos.


Quer se conectar com o autor?


Adoro me conectar com amigos de todo o mundo em 𝕏 .


Também publicado aqui