TutorialAuthenticationPasswordReset

How to implement password reset in Node.js and TypeScript

Implement password reset in Node.js and TypeScript step by step: hashed one-time tokens, a constant response, the reset email via an API, session cleanup.

Olivier Bazoud
November 13, 2026
November 15, 2026
11 min read

A user who forgot their password has one way back into your app: the reset email. If it arrives late or not at all, they're locked out and they open a support ticket. If the flow is poorly secured, an attacker can use it to take over accounts.

You will implement password reset in Node.js and TypeScript, end to end, with the reset email sent through the Nuntly email API. For more context on this use case, see the password reset emails page.

Overview of the password reset flow in Node.js

The password reset flow follows four steps:

  1. The user submits their email address to request a reset.
  2. Your server generates a secure token, stores it, and sends a reset email.
  3. The user clicks the link in the email, which sends the token back to your server.
  4. Your server verifies the token and allows the user to set a new password.

Step 1: Accept the reset request

Create an endpoint that accepts an email address and initiates the reset process. The response must be the same whether or not the email exists in your system, in content and in timing.

Account enumeration: probing a login or reset endpoint to learn which email addresses have an account.

The OWASP Forgot Password Cheat Sheet states the rule for the timing half:

Ensure that responses return in a consistent amount of time to prevent an attacker enumerating which accounts exist.

The samples use Hono for routing and Drizzle ORM with three tables: users (id, email, passwordHash), sessions (userId) and passwordResets (id, userId, tokenHash, createdAt, expiresAt and a nullable usedAt). Swap in your own framework and database layer.

TypeScript
import { Hono } from 'hono';
import { and, eq, gt, isNull } from 'drizzle-orm';
const app = new Hono();
app.post('/auth/forgot-password', async (c) => {
const { email } = await c.req.json();
// Always return the same response to prevent email enumeration
const response = {
message: 'If an account with that email exists, a reset link has been sent.',
};
if (typeof email !== 'string') {
return c.json(response, 200);
}
const user = await db.query.users.findFirst({
where: eq(users.email, email),
});
if (!user) {
return c.json(response, 200);
}
// Rate limit, token and email (Steps 2 and 3).
// Not awaited: a slower or failed response would reveal that the account exists.
createResetTokenAndSendEmail(user).catch((err) => {
console.error('Password reset failed', { userId: user.id, err });
});
return c.json(response, 200);
});

Both branches run the same single lookup and return the same message. The rate limit check, the token and the email all run after the response is sent, so an existing account doesn't answer slower than an unknown one. On a runtime that stops once the response is sent (serverless functions), push this job to a queue instead. A failed send is logged with the user ID, never with the address, and the caller still gets the same response.

Step 2: Generate a secure token

The reset token must be cryptographically random and stored as a hash. Node's randomBytes generates cryptographically strong pseudorandom data. Never store the plain token in your database. If your database is compromised, an attacker with plain tokens could reset any user's password.

TypeScript
import { randomBytes, createHash } from 'node:crypto';
interface ResetToken {
plainToken: string;
hashedToken: string;
expiresAt: Date;
}
function generateResetToken(): ResetToken {
// Generate 32 bytes of random data, encoded as hex
const plainToken = randomBytes(32).toString('hex');
// Hash the token before storing it
const hashedToken = createHash('sha256').update(plainToken).digest('hex');
// Token expires in 1 hour
const expiresAt = new Date(Date.now() + 60 * 60 * 1000);
return { plainToken, hashedToken, expiresAt };
}

Step 1 calls this function after it has answered. It applies the per-user rate limit, then stores the hashed token along with the user ID and expiration. A plain check followed by an insert would let parallel requests for one account all pass the check, so the three writes run in one transaction that first locks the user row. The email goes out after the commit:

TypeScript
async function createResetTokenAndSendEmail(user: User) {
const { plainToken, hashedToken, expiresAt } = generateResetToken();
const created = await db.transaction(async (tx) => {
// Lock the user row: concurrent requests for one account run one at a time
await tx.select({ id: users.id }).from(users).where(eq(users.id, user.id)).for('update');
// Rate limit: one reset request per minute per user, skipped silently
const recentRequest = await tx.query.passwordResets.findFirst({
where: and(
eq(passwordResets.userId, user.id),
gt(passwordResets.createdAt, new Date(Date.now() - 60_000)),
),
});
if (recentRequest) {
return false;
}
// Invalidate any existing tokens for this user
await tx
.update(passwordResets)
.set({ usedAt: new Date() })
.where(and(eq(passwordResets.userId, user.id), isNull(passwordResets.usedAt)));
// Store the hashed token
await tx.insert(passwordResets).values({
userId: user.id,
tokenHash: hashedToken,
expiresAt,
});
return true;
});
if (!created) {
return;
}
// Send the email with the plain token
await sendResetEmail(user.email, plainToken);
}

Step 3: Send the password reset email through the API

Use the Nuntly SDK to send the reset email. The email contains a link with the plain token as a URL parameter.

createSafeNuntly() reads your API key from the NUNTLY_API_KEY environment variable. It returns { data, error } instead of throwing, so the error check sits right after the call. The from address must belong to a domain you verified in Nuntly. SDK setup covers the API key and the sending domain, and the free plan needs no credit card.

TypeScript
import { APIError, createSafeNuntly } from '@nuntly/sdk';
const nuntly = createSafeNuntly();
async function sendResetEmail(email: string, token: string) {
const resetUrl = `https://app.example.com/auth/reset-password?token=${token}`;
const { error } = await nuntly.emails.send({
from: 'security@example.com',
to: email,
subject: 'Reset your password',
html: `
<h2>Password reset request</h2>
<p>You requested a password reset for your account.
Click the link below to set a new password:</p>
<p><a href="${resetUrl}">Reset your password</a></p>
<p>This link expires in 1 hour. If you did not request this reset,
you can safely ignore this email.</p>
<p>For security, this link can only be used once.</p>
`,
text: [
'You requested a password reset. Visit this link to set a new password:',
resetUrl,
'This link expires in 1 hour.',
].join('\n\n'),
tags: [{ name: 'type', value: 'password-reset' }],
});
if (error) {
// Log the error type and HTTP status only: the message can quote email addresses
const status = error instanceof APIError ? error.status : undefined;
console.error('Failed to send reset email', { error: error.name, status });
throw new Error('Failed to send reset email');
}
}

On the email itself:

  • Send both HTML and plain text versions, so the link works in clients that don't render HTML.
  • Include a clear expiration notice so users know the link is time-limited.
  • Tell users to ignore the email if they did not request the reset.
  • Tag the email so your webhook handler can tell reset emails apart from other sends. The tag also shows on the email's page in the dashboard.
  • Render the HTML from a React component with React Email instead of an inline template string.

Step 4: Verify the token and reset the password

When the user clicks the link and submits their new password, verify the token against the stored hash.

TypeScript
app.post('/auth/reset-password', async (c) => {
const { token, newPassword } = await c.req.json();
if (typeof token !== 'string' || typeof newPassword !== 'string') {
return c.json({ error: 'Invalid or expired reset token.' }, 400);
}
// Hash the submitted token to compare with the stored hash
const tokenHash = createHash('sha256').update(token).digest('hex');
// Find the matching reset record
const resetRecord = await db.query.passwordResets.findFirst({
where: and(
eq(passwordResets.tokenHash, tokenHash),
isNull(passwordResets.usedAt),
gt(passwordResets.expiresAt, new Date()),
),
});
if (!resetRecord) {
return c.json({ error: 'Invalid or expired reset token.' }, 400);
}
// Validate password strength
if (!isStrongPassword(newPassword)) {
return c.json({ error: 'Password does not meet strength requirements.' }, 400);
}
// Hash the new password
const passwordHash = await hashPassword(newPassword);
const updated = await db.transaction(async (tx) => {
// Claim the token: only one request can switch usedAt from null
const claimed = await tx
.update(passwordResets)
.set({ usedAt: new Date() })
.where(and(eq(passwordResets.id, resetRecord.id), isNull(passwordResets.usedAt)))
.returning({ id: passwordResets.id });
if (claimed.length === 0) {
return false;
}
await tx
.update(users)
.set({ passwordHash })
.where(eq(users.id, resetRecord.userId));
// Log out every existing session (see Session invalidation below)
await tx.delete(sessions).where(eq(sessions.userId, resetRecord.userId));
return true;
});
if (!updated) {
return c.json({ error: 'Invalid or expired reset token.' }, 400);
}
return c.json({ message: 'Password updated successfully.' }, 200);
});

The verification step checks three conditions:

  1. The hashed token matches a stored record.
  2. The token has not been used before.
  3. The token has not expired.

All three must pass for the reset to proceed. The lookup alone does not make the token single-use: two requests sent at the same moment can both find it unused. So the transaction first claims the token with an update that only matches while usedAt is still null. The second request updates no row and gets the same error as an expired token. The password update and the session cleanup run in the same transaction, so a failure leaves none of them half done.

Security considerations

The OWASP Forgot Password Cheat Sheet lists the controls a reset flow needs. Here is where each one sits in the code above:

StepAttack it blocksControl
1Account enumerationSame message and timing for every address
2Inbox floodingOne request per minute per account
2Token guessing or theft32 random bytes, stored as a SHA-256 hash
2 and 4Link replayOne-hour expiry, single use
4Attacker staying logged inSession cleanup after the reset
Reset pageToken leak through RefererReferrer-Policy: no-referrer on the page

Token expiration

OWASP asks for tokens that "expire after an appropriate period" and names no duration. One hour is a reasonable default. A shorter window leaves a forgotten link exposed for less time, but frustrates users who check email infrequently.

One-time use

Claim the token before you change the password, in the same transaction, with an update that only matches an unused token, as Step 4 does. Marking it used after the password update leaves a window where a second request with the same token also succeeds. A used token can never be replayed, even by an attacker who intercepted the link.

Referrer policy

The token travels in the query string of the reset link. If the reset page loads a third-party script or image, or links to another site, the browser can send that full URL in the Referer header. The cheat sheet asks for a Referrer-Policy: no-referrer header (or the matching <meta name="referrer"> tag) on the reset page so the token never leaves your site.

Password validation

Validate the new password server-side. Do not rely only on client-side validation. Check minimum length, and consider using a library like zxcvbn to evaluate password strength.

Session invalidation

OWASP lets you either ask the user or invalidate the sessions automatically. Step 4 does it automatically: the sessions delete inside the transaction logs out an attacker who already had access.

Confirmation email

The cheat sheet also recommends emailing the user once the password has been reset, and never putting the password in that email. The code above does not send this email. A second nuntly.emails.send call after the transaction would.

Logging and monitoring

Log reset requests for auditing, and never log the token value. The passwordResets table already holds one row per request that passes the rate limit, so a burst against one account is visible there too.

Set up webhooks to receive delivery events for your reset emails. Each event carries the email's tags, so the password-reset tag lets your handler pick out reset emails. If a reset email bounces, you know the user will not receive it and can surface that through your support flow. Handle webhook events shows the signature check your endpoint needs.

Next steps

A reset flow is only as safe as its token: random, hashed at rest, short-lived, and used once. The rest of the code keeps the endpoint from saying whether an account exists.

The token and email functions depend only on Node's crypto module and the Nuntly SDK, so they move to another TypeScript backend unchanged. The guides to send email from Next.js, Express, and NestJS show where the client and the send call go in each one.

If you use Better Auth, it creates the token and calls your sendResetPassword callback. Better Auth email verification in Next.js wires that callback to the Nuntly SDK.

If your users sign in with Supabase Auth, Supabase sends the reset email itself. Send Supabase emails through your own provider covers its custom SMTP setting and the Send Email Hook.

Ready to get started?

Ship emails, not infrastructure

Free plan available. No credit card required.

Start for free