Skip to content

Mail into your templates and queue

The package never renders or sends mail. Each flow that needs one emits a typed AuthMailEvent to your Mailer, and your code turns it into a message in your own templates and language.

Each flow calls send and answers without awaiting the promise it returns, so a delivery that is slow, or never settles, neither delays nor hangs a response. In most flows the call itself is on the response path, though: whatever your send does before it returns its promise counts toward the response time, and a door that mails on one branch only (a lock notice, a password-changed mail) would answer slower on that branch. A send that rendered the template, or opened an SMTP connection, before returning would make the two branches take different times and give the answer back. So Mailer.send must store a job and return; a worker builds the template and sends it. Sign-up hands both of its templates (account-exists for a taken address, verify-email for a new one) over from a background task, after a store call: the answer does not wait for that call, so with a store on the network send runs after the answer, and an end-to-end test that reads the mail right after sign-up must wait for it.

Delivery from the library is at most once. Each mail is handed to send once; a send that throws or rejects does not fail the flow, the error goes to the configured logger as Mailer failed with the event type and user id, and the mail is not retried. Retries are the job of your queue. Make sure your queue is up, and give createAuth a logger.

Enqueueing narrows the window in which a mail can be lost, but does not close it on its own. The library does not await the enqueue, so if the process exits, or a serverless runtime freezes the instance once the response is sent, before the queue write settles, that mail is lost. Every mail, every lock notice and a reset job run without enqueue go through one background runner, configured by the background option of createAuth:

  • On a runtime that freezes after the response (Vercel, Cloudflare Workers and similar), pass its waitUntil. The runner hands it each task’s promise as the task starts; the promise never rejects. On Workers the function belongs to the request (ctx.waitUntil), so build auth per request there, or keep the request’s ctx somewhere your waitUntil can reach it.
  • On a long-lived Node process, call await auth.flush() during graceful shutdown, after the server stops taking requests and before you close the database and Redis connections. It resolves once no task is left that has neither settled nor timed out, tasks started while it waits included, and never rejects. Pass { timeout } to bound the wait: after that long it logs Background flush stopped waiting, with the labels of the tasks still running, and resolves, so a send that never settles cannot hold shutdown forever. With @noctcore/auth-nestjs, AuthModule does this for you on shutdown, bounded to 10 seconds by default.
  • background.timeout (a Duration) stops waiting on a task that is still running after it: the task is logged as Background task timed out: <label> and counted, and flush and waitUntil stop waiting for it. JavaScript cannot cancel a promise, so the send itself keeps running and keeps whatever it holds in memory until it settles. Give your enqueue its own timeout too.
  • background.maxPending bounds memory while a mailer hangs instead of failing: while that many tasks are still running, timed out or not, a new task is not started. It is logged as Background task dropped: <label>, with the user id when there is one, and counted. A dropped mail is not retried, like any other failed send. Each mail is one capped task (mail <type>, such as mail lockout), and a sign-up’s verification mail is one capped task that issues the code and hands the mail over (verification mail). Work that writes an audit row runs outside the cap and is never dropped: the register.created, account.locked and account.locked_permanently rows (tasks labelled audit <type>), the taken-address half of a sign-up (existing address notice: the owner lookup and the register.existing row) and a reset job run without enqueue (password reset job: the lookup, the mail limit and the password.reset_request_ignored row). Only the mail these start is capped. So under maxPending you can lose a mail, and with a dropped verification mail its email.verification_sent row (a dropped mail was not sent), but no other audit row. Uncapped tasks still count for timeout, waitUntil and flush, but take no slots: a hung audit sink, or a user store that hangs during those two lookups, grows memory the way it did before maxPending, so keep the sink’s and the store’s own calls bounded. While the cap is full, the drop log names the mail that was dropped, mail account-exists for a taken address and verification mail for a new one, so the logs of the two sign-up branches differ; the answer to the client does not.

A dropped or failed mail still spends the budget

Section titled “A dropped or failed mail still spends the budget”

The per-account mail limits are spent before the mail is handed to the background runner: password-reset-mail, email-verification-request and email-change-request (3 per '1h' by default) all work this way. A mail that is then dropped under maxPending, or that the mailer fails to send, never reaches the user but still counts against their budget. While the cap is full or the mailer is failing, up to 3 requests an hour can be used up with no mail sent, and the account cannot ask again until the window ends. The client gets the same answer either way, so neither side sees it. Nothing is refunded and nothing is retried.

Watch the signal on your side: the Background task dropped: <label> and Mailer failed log lines (pass a logger), and the dropped outcome of the auth_background_task metric. A steady count means the cap is too low or the mailer is unhealthy, and users are being locked out of reset, verification or email change for the rest of the hour.

Timeouts and drops are counted on your metrics as auth_background_task, with the labels task (such as mail verify-email) and outcome (timed_out or dropped). None of the three is set by default: tasks run detached, with no timeout and no cap. Drops, timeouts and failures are logged through your logger, and the default logger is silent, so pass a logger (and metrics) or you will not see them.

type Sent when Fields beyond to, userId and dedupeKey
verify-email a new account registers, or a signed-in user asks for another code (code mode) or url (link mode), expiresAt
password-reset a reset is requested for a known address, link mode url, expiresAt
password-reset-code the same, code mode code, expiresAt
password-changed a password was changed or reset at
account-exists someone registered with an address that already has an account none
lockout failed sign-ins locked the account until, permanent (only with the opt-in permanent tier: the lock holds until an admin clears it and until is only its stored far-future expiry, so say that instead of printing the date)
email-change-confirm an email change was requested for a free address; sent to the new address code (code mode) or url (link mode), expiresAt
email-change-in-use an email change named an address that already has an account; sent to that address, userId is its account none
email-changed an email change was confirmed; sent to the address it replaced newEmail, at, revertUrl, revertExpiresAt
email-change-reverted a revert link restored the address; every session ended and the password must be reset at
two-factor-enabled the two-factor plugin: a second factor was turned on at
two-factor-disabled the two-factor plugin: the second factor was turned off, by the owner or by an admin’s twoFactor.reset at, reset (true when an admin reset it)
recovery-code-used the two-factor plugin: a recovery code was spent remaining (null when the count could not be read), at
invitation the invitations plugin: an invitation to a scope; no userId, since the address may have no account scope, inviterId, url, expiresAt

account-exists is the other half of the uniform registration answer: the caller sees “check your email” either way, and only the owner of the address learns the account exists. lockout tells the owner someone is guessing their password. email-change-in-use plays the same part for an email change, and email-changed is the owner’s way back when the change was not theirs (Email change).

dedupeKey is a server-minted nonce, unique per event and safe to use as a job id, so a retried enqueue stores one job.

Mails to the address an account already holds carry an optional meta: { ip, userAgent? }, the client IP (after trust-proxy resolution) and the user agent when your framework passed one. They are password-reset, password-reset-code, password-changed, lockout, account-exists, email-changed, email-change-reverted, two-factor-enabled, two-factor-disabled and recovery-code-used. Use it for “asked from this IP” in a reset, lockout or security mail. On account-exists it is the IP of whoever tried to sign up with the holder’s address. A reset mail takes it from the reset job, so it is there when the job runs on your queue, far from the request. verify-email after a sign-up and email-change-confirm never carry it: they go to an address the request named itself and nobody has proven yet. email-change-in-use and invitation never carry it either: they go to someone other than the account the request acted on. A mailer that ignores meta keeps working.

meta is personal data. If your queue stores the event, it stores the IP and user agent too: keep the retention of the mail queue in line with what your privacy policy says about them.

The samples use the two calls every job queue has in some form. Map them onto BullMQ, pg-boss, Graphile Worker, SQS or whatever you run.

src/mail/queue.ts
/**
* The two calls this guide needs from a job queue. BullMQ, pg-boss, Graphile
* Worker and SQS all offer them under some name; adapt the names to yours.
*/
export interface Queue<T> {
/** Adds a job. A second add with the same `jobId` is dropped. */
add(data: T, options: { jobId: string }): Promise<void>;
}
/** A rendered message, ready for whatever sends your mail. */
export interface OutgoingMail {
readonly to: string;
readonly subject: string;
readonly text: string;
}

A switch over event.type with a never check in the default branch: if a release adds an event type, your build fails until it has a template, instead of the mail silently going missing.

src/mail/templates.ts
import type { AuthMailEvent } from '@noctcore/auth';
import type { OutgoingMail } from './queue';
/** One template per event type. The `never` check fails the build when a new type appears. */
export function renderAuthMail(event: AuthMailEvent): OutgoingMail {
switch (event.type) {
case 'verify-email':
return {
to: event.to,
subject: 'Confirm your email address',
text: event.code
? `Your code is ${event.code}. It expires at ${event.expiresAt.toISOString()}.`
: `Confirm your address: ${event.url ?? ''}`,
};
case 'password-reset':
return {
to: event.to,
subject: 'Reset your password',
text: `Choose a new password: ${event.url}\nIf you did not ask for this, ignore this mail.`,
};
case 'password-reset-code':
return {
to: event.to,
subject: 'Your password reset code',
text: `Your code is ${event.code}. If you did not ask for it, ignore this mail.`,
};
case 'password-changed':
return {
to: event.to,
subject: 'Your password was changed',
text: `Your password was changed at ${event.at.toISOString()}. If this was not you, reset it now.`,
};
case 'account-exists':
return {
to: event.to,
subject: 'You already have an account',
text: 'Someone tried to register with this address. Sign in or reset your password instead.',
};
case 'lockout':
return {
to: event.to,
subject: 'Someone is trying to sign in to your account',
text: `After repeated wrong passwords, your account is locked until ${event.until.toISOString()}. A device you signed in from before can still sign in with your password.`,
};
case 'email-change-confirm':
return {
to: event.to,
subject: 'Confirm your new email address',
text: event.code
? `Your code is ${event.code}. It expires at ${event.expiresAt.toISOString()}. If you did not ask to use this address, ignore this mail.`
: `Confirm your new address: ${event.url ?? ''}`,
};
case 'email-change-in-use':
return {
to: event.to,
subject: 'Someone tried to move an account to your address',
text: 'An account asked to change its email to this address, which already has an account. Nothing changed. If this was you, sign in to that account instead.',
};
case 'email-changed':
return {
to: event.to,
subject: 'Your email address was changed',
text: `Your account now uses ${event.newEmail}. If this was not you, undo it before ${event.revertExpiresAt.toISOString()}: ${event.revertUrl}`,
};
case 'email-change-reverted':
return {
to: event.to,
subject: 'Your email address is back',
text: 'The email change was undone and every session was signed out. Reset your password to sign in again.',
};
// The three below come from the two-factor plugin (@noctcore/auth/two-factor).
case 'two-factor-enabled':
return {
to: event.to,
subject: 'Two-factor authentication is on',
text: `Two-factor authentication was turned on at ${event.at.toISOString()}. If this was not you, reset your password and contact support.`,
};
case 'two-factor-disabled':
return {
to: event.to,
subject: 'Two-factor authentication is off',
text: `Two-factor authentication was turned off at ${event.at.toISOString()}. If this was not you, reset your password and contact support.`,
};
case 'recovery-code-used':
return {
to: event.to,
subject: 'A recovery code was used',
text: `A recovery code was used to sign in at ${event.at.toISOString()}. ${event.remaining === null ? '' : `${event.remaining} codes are left. `}If this was not you, reset your password now.`,
};
case 'invitation':
// Never say whether the address has an account: the mail is the same either way.
return {
to: event.to,
subject: 'You are invited',
text: `You were invited to join. Accept before ${event.expiresAt.toISOString()}: ${event.url}`,
};
default: {
const unhandled: never = event;
throw new Error(`No template for ${JSON.stringify(unhandled)}`);
}
}
}

Codes and links are credentials. Keep them out of logs and analytics, and if your queue stores job data in plain text, give its storage the same care as your session store.

src/mail/mailer.ts
import type { AuthMailEvent, Mailer } from '@noctcore/auth';
import type { OutgoingMail, Queue } from './queue';
import { renderAuthMail } from './templates';
/**
* Puts the raw event on the queue and returns; a worker renders and sends it.
* Rendering here would be work done before `send` returns, and a door that
* mails on one branch only would answer slower on that branch.
*/
export function queueMailer(queue: Queue<AuthMailEvent>): Mailer {
return {
async send(event) {
// dedupeKey is unique per event: if this add is retried, the queue keeps one job.
await queue.add(event, { jobId: event.dedupeKey });
},
};
}
/** Your worker's handler for the mail queue: render off the response path, then deliver. */
export function handleMailJob(
event: AuthMailEvent,
deliver: (mail: OutgoingMail) => Promise<void>,
): Promise<void> {
return deliver(renderAuthMail(event));
}

The queue holds the raw AuthMailEvent: send renders nothing. Your worker takes each event off the queue, runs handleMailJob (which renders the template and hands the OutgoingMail to your mail provider), and retries on failure as your queue allows. If your queue stores job data as JSON, the event’s Date fields come back as strings, so revive them before rendering.

A reset request answers the same for every address and does none of the per-account work on the response path. It builds a PasswordResetJob (email, ip, userAgent when the request had one, and a dedupeKey); the lookup, the per-account mail limit and the mail happen when that job runs, in auth.jobs.processPasswordReset(job).

Without passwordReset.enqueue the job runs detached in the same process. That keeps the response time independent of the address but loses the job if the process dies. With enqueue, the job goes on your queue and your worker runs it:

src/mail/config.ts
import type { Auth, AuthConfig, AuthMailEvent, AuthUser, PasswordResetJob } from '@noctcore/auth';
import { queueMailer } from './mailer';
import type { Queue } from './queue';
export interface MailQueues {
readonly mail: Queue<AuthMailEvent>;
readonly passwordResets: Queue<PasswordResetJob>;
}
/** The mail half of the createAuth config: spread it into yours. */
export function mailConfig(
queues: MailQueues,
): Pick<AuthConfig<AuthUser, unknown, []>, 'mailer' | 'passwordReset'> {
return {
mailer: queueMailer(queues.mail),
passwordReset: {
// The request only enqueues; the lookup and the mail run in the worker.
enqueue: (job) => queues.passwordResets.add(job, { jobId: job.dedupeKey }),
},
};
}
/** Your worker's handler for the password reset queue. */
export function handlePasswordResetJob(
auth: Auth<AuthUser, Record<string, never>>,
job: PasswordResetJob,
): Promise<void> {
return auth.jobs.processPasswordReset(job);
}

Spread mailConfig(queues) into your createAuth config, and register handlePasswordResetJob as the handler of the reset queue.

  • The job’s dedupeKey is the same for every request for one address within a minute, so a burst of requests stores one job and sends one mail.
  • processPasswordReset writes password.reset_request_ignored to the audit trail when it sends nothing (unknown address, a hook refused, the per-account limit of 3 mails an hour), so the reason is recorded even though the client was answered long before. When it sends a link or code it writes password.reset_issued with the user and data.kind (link or code), after the token is stored and before the mail is handed over. Both rows carry the request’s IP and user agent from the job.
  • A job queued by an older version has no userAgent; it runs the same, and its mail’s meta holds only the IP.
  • The job carries the address in plain text. Treat the reset queue’s storage like the mail queue’s.