Forgot-password endpoint
The request endpoint finds the user, creates a token, builds the reset URL, and sends the transactional email. This is the center of the recovery workflow because it coordinates storage, encryption, and outbound delivery.
Request reset token
import db from '@/utils/db';
import User from '@/models/User';
import Env from '@/config/env';
import Cryptr from 'cryptr';
import cryptoRandomString from 'crypto-random-string';
import { sendEmail } from '@/config/mail';
import { render } from '@react-email/render';
import ForgotPasswordEmail from '@/app/emails/ForgotPasswordEmail';
export async function POST(req: Request) {
const payload = await req.json();
await db.connect();
const user = await User.findOne({ email: payload.email });
if (!user) {
await db.disconnect();
return Response.json({ message: 'Nonexistent user!' }, { status: 422 });
}
const randomStr = cryptoRandomString({
length: 64,
type: 'alphanumeric',
});
user.password_reset_token = randomStr;
await user.save();
await db.disconnect();
const crypt = new Cryptr(Env.SECRET_KEY);
const encryptedEmail = crypt.encrypt(user.email);
const url =
Env.APP_URL +
'/reset-password/' +
encryptedEmail +
'?signature=' +
randomStr +
'&mail=' +
encryptedEmail;
const html = render(
ForgotPasswordEmail({
params: {
name: user.name,
email: user.email,
url,
},
})
);
await sendEmail(payload.email, 'Reset Password', html);
return Response.json({
message: 'Email successfully sent. Please check your email.',
});
}