Restablecimiento de contraseñas y verificación de correo electrónico
Cree flujos seguros de recuperación de cuentas y verificación de correo electrónico mediante tokens de un solo uso, caducidad y correo transaccional para que los usuarios recuperen el acceso de forma segura.
Restablecimiento de contraseñas y verificación de correo electrónico es una lección gratuita de AI Powered SaaS: Stripe + Auth + Billing + Deploy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Powered SaaS: Stripe + Auth + Billing + Deploy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Reset & Verify?
Users forget passwords and mistype emails. A safe password reset flow lets them recover without support, and email verification confirms the address really belongs to them, cutting spam and fake accounts.
The Token Strategy
Both flows rely on a one-time token: a random, unguessable string emailed to the user. Possessing it proves control of the inbox.
import crypto from 'crypto';
const token = crypto.randomBytes(32).toString('hex');Storing the Token Hashed
Never store the raw token. Hash it before saving so a database leak cannot be used to reset accounts. Compare hashes when the user returns.
const hash = crypto.createHash('sha256').update(token).digest('hex');
await prisma.resetToken.create({
data: { userId, hash, expiresAt }
});Adding Expiry
Tokens must expire — usually 15 to 60 minutes. Store an expiresAt timestamp and reject tokens past it.
const expiresAt = new Date(Date.now() + 30 * 60 * 1000);Requesting a Reset
The user submits their email. Generate a token, save its hash, and email a link containing the raw token. Always respond the same way to avoid leaking which emails exist.
const link = process.env.APP_URL + '/reset?token=' + token;
await sendEmail(email, 'Reset your password', link);Sending Transactional Email
Use a provider like Resend or SendGrid for reliable delivery. Keep the message short with a clear single action.
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
await resend.emails.send({ to, subject, html });Verifying the Token
When the user opens the link, hash the incoming token, look it up, and check it is unused and unexpired.
const hash = crypto.createHash('sha256').update(token).digest('hex');
const record = await prisma.resetToken.findFirst({
where: { hash, expiresAt: { gt: new Date() }, usedAt: null }
});Updating the Password
If valid, hash the new password and save it, then mark the token used so it cannot be replayed.
const pw = await bcrypt.hash(newPassword, 12);
await prisma.user.update({ where: { id: record.userId }, data: { password: pw } });
await prisma.resetToken.update({ where: { id: record.id }, data: { usedAt: new Date() } });Email Verification Flow
Verification works the same way: on signup, email a token. When clicked, set emailVerified on the user and invalidate the token.
await prisma.user.update({
where: { id }, data: { emailVerified: new Date() }
});Preventing Abuse
Protect these endpoints:
- Rate limit reset requests
- Give identical responses for known and unknown emails
- Allow only one active token per user
Best Practices
Build recovery securely:
- Use random, hashed tokens with expiry
- Send via a transactional email provider
- Mark tokens used after one use
- Rate limit and avoid email enumeration
Quick Check
Test your reset-flow knowledge.
Recap
You built account recovery:
- Generate random tokens, store them hashed with expiry
- Email links via a transactional provider
- Verify, then update the password and mark the token used
- Reuse the pattern for email verification and guard against abuse
Users can now safely recover and verify accounts.
Aprende AI Powered SaaS: Stripe + Auth + Billing + Deploy con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 12
- Lecciones
- 48
Preguntas frecuentes
¿La lección «Restablecimiento de contraseñas y verificación de correo electrónico» es gratis?
Sí — el texto completo de «Restablecimiento de contraseñas y verificación de correo electrónico» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy, actualiza a CoddyKit PRO. El curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye 4 lecciones en total.
¿Qué aprenderé en «Restablecimiento de contraseñas y verificación de correo electrónico»?
Cree flujos seguros de recuperación de cuentas y verificación de correo electrónico mediante tokens de un solo uso, caducidad y correo transaccional para que los usuarios recuperen el acceso de forma… Practicas AI Powered SaaS: Stripe + Auth + Billing + Deploy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar AI Powered SaaS: Stripe + Auth + Billing + Deploy?
No se requiere experiencia previa. AI Powered SaaS: Stripe + Auth + Billing + Deploy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Restablecimiento de contraseñas y verificación de correo electrónico»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de AI Powered SaaS: Stripe + Auth + Billing + Deploy?
Sí. Cada lección de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Registro de usuarios y hashing
- Inicio de sesión y generación de JWT
- Rutas protegidas y middleware
- Restablecimiento de contraseñas y verificación de correo electrónico