Email verification is often implemented as two endpoints and a token table. The difficult part starts when the client has to decide what to do after a request fails. Is the code expired, was the message delayed, can the user safely request another message, or did the server reject the address for a security reason?
If every failure becomes HTTP 400 with "verification failed", the frontend guesses. That creates duplicate emails, unsafe retries, and support tickets that are hard to reproduce. A clear error contract turns an authentication workflow into something that clients can operate reliably.
This article describes a small REST API design for verification requests. It focuses on the boundary between API behavior, database state, and the UI that consumes it. The same boundary matters when a fake email generator is used in CI: test inboxes are fast sometimes, but they still expose retry and ordering bugs.
Why verification APIs need an error contract
An email flow has several independent outcomes:
- The request is valid and a message was queued.
- The account already has a pending verification request.
- The token is unknown, expired, or already consumed.
- The mail provider is temporarily unavailable.
- The caller is not allowed to learn whether an address exists.
These outcomes do not all map to the same client action. A token that is expired should lead to a resend option. A provider outage should lead to a delayed retry. An invalid token should not be retried in a tight loop. Treating them as one error is convenient for the first endpoint, but it makes the whole system less reliable.
I start by documenting the action that is safe for each error. The HTTP status, stable application code, and retry hint then become an API contract rather than incidental implementation detail.
For the security side of the flow, it is worth pairing this design with a threat model for OAuth email verification. Verification is proof of control of an inbox, not proof that every other identity claim is true.
Separate client action from server failure
The client needs to know two things: what happened and what it may do next. Those are related, but they are not the same field.
For example, an expired token is a permanent failure for the current token, while a resend request can be valid immediately. A provider timeout is a temporary failure, but resending immediately may create multiple messages. A retryable boolean alone cannot express these differences very well.
A useful response shape is small and explicit:
{
"error": {
"code": "VERIFICATION_TOKEN_EXPIRED",
"message": "This verification link has expired.",
"action": "request_new_link",
"retry_after_seconds": 0,
"request_id": "req_01JX..."
}
}
code is for program logic, while message is safe display text. action tells the UI what control to show. retry_after_seconds is useful for throttling, and request_id gives operators a way to connect a user report to logs. The message can change without forcing every client to ship a new version.
Do not put database exception strings into this payload. They are noisy, may reveal implementation details, and are not stable enough for consumers.
Design a stable error envelope
Here is a practical mapping for the two main endpoints:
| Situation | Status | Code | Safe client action |
|---|---|---|---|
| Malformed address | 422 | INVALID_EMAIL |
Fix input |
| Accepted request | 202 | — | Show pending state |
| Rate limit reached | 429 | RESEND_COOLDOWN |
Wait for the hint |
| Expired token | 410 | VERIFICATION_TOKEN_EXPIRED |
Request a new link |
| Used token | 409 | VERIFICATION_ALREADY_USED |
Refresh account state |
| Temporary mail failure | 503 | DELIVERY_UNAVAILABLE |
Retry with backoff |
The exact statuses can vary, but the meanings should not. In particular, avoid returning a different body for an existing and a non-existing account during a public sign-up flow. That difference can become an account enumeration signal.
The resend endpoint should also accept an idempotency key. If a browser retries after a timeout, the server can return the original request result instead of queueing another message. A key scoped to the user and operation is safer than one global key shared across all requests.
When changing an email address, require proof in the right order and keep the old address usable until the new one is confirmed. The article on proof before changing an email address covers why this boundary deserves its own threat analysis.
Make resend and token consumption idempotent
There are two different idempotency problems:
- A resend request must not create unlimited delivery jobs when the caller repeats a request.
- A verification token must not apply its account mutation twice.
For resends, store an operation key, its result, and an expiry time. The request transaction should check that record before adding a new outbox row. For token consumption, use a single conditional update:
UPDATE verification_tokens
SET consumed_at = now()
WHERE token_hash = $1
AND consumed_at IS NULL
AND expires_at > now()
RETURNING user_id;
If no row returns, the handler should distinguish only as much as the public contract allows. Internally, logs can record whether the token was missing, expired, or already consumed. Externally, the response can remain a stable VERIFICATION_TOKEN_INVALID when revealing the difference would be unhelpful.
The database constraint is important. Checking a token and updating it in two separate operations leaves a race where two requests both pass the check. A transaction with a conditional update keeps the rule near the data it protects.
Map errors in a Node.js handler
Keep domain errors separate from transport formatting. This makes unit tests target behavior instead of Express or a particular logger.
type VerificationErrorCode =
| "INVALID_EMAIL"
| "RESEND_COOLDOWN"
| "VERIFICATION_TOKEN_EXPIRED"
| "DELIVERY_UNAVAILABLE";
type VerificationError = Error & {
code: VerificationErrorCode;
action: "fix_input" | "wait" | "request_new_link" | "retry_later";
retryAfterSeconds?: number;
};
function toHttpError(error: VerificationError) {
const statusByCode: Record<VerificationErrorCode, number> = {
INVALID_EMAIL: 422,
RESEND_COOLDOWN: 429,
VERIFICATION_TOKEN_EXPIRED: 410,
DELIVERY_UNAVAILABLE: 503,
};
return {
status: statusByCode[error.code],
body: {
error: {
code: error.code,
message: error.message,
action: error.action,
retry_after_seconds: error.retryAfterSeconds ?? 0,
},
},
};
}
The handler can attach a request ID and emit the structured log after formatting. Avoid logging raw tokens or complete email addresses. A typo like tempail in a test fixture should not accidentally become a production identifier, so fixture names and input validation should be seperated clearly.
Operational checks for production
Before shipping, verify the contract under failure instead of only checking the happy path:
- Repeat the same resend request with the same idempotency key.
- Send two token-consumption requests concurrently.
- Make the mail provider return a timeout and confirm
503plus backoff guidance. - Confirm rate limits use a stable key and do not leak account existence.
- Record queue age, delivery failures, and token-consumption conflicts.
- Ensure expired rows are cleaned without deleting evidence needed for debugging.
The retry budget should be owned by the caller and the server together. Unlimited client retries is not resilience; it is traffic that eventually make the outage larger. A short, documented backoff is more safer than a spinner that retries forever.
Q&A
Should every error include a retry hint?
No. A malformed address and a consumed token need a corrective action, not a timed retry. Include a retry hint when waiting is actually valid, and use an action value for other cases.
Is HTTP 202 required when the email is queued?
No, but it communicates that processing is asynchronous. Whatever status you choose, keep the response shape and delivery semantics stable so clients does not need to infer queue behavior from a message string.
Should test inboxes be treated as real authentication factors?
Only inside a controlled test boundary. A fake email generator can help exercise delivery workflows, but production authorization should not trust a test fixture or a mail message without validating its token, audience, expiry, and request context.
An error contract is a small investment with a wide payoff. It gives frontend clients a safe next step, gives backend code a place to express state, and gives operators useful evidence when delivery is slow. Start with stable codes and idempotent mutations, then extend the contract only when a new client action genuinely needs it.
Top comments (0)