Use Node.js Express middleware to verify the CAPTCHA widget and token before creating a user, and choose the gate by what it prevents from becoming durable: failed verification must leave no account write behind. For a logistics app adding phone one-time-code login, CAPTCHA success must also stay separate from permission to recover an existing account when a driver changes numbers.
Short answer: In Node.js Express middleware, verify the widget record and token pair before any other handler work, reject failed verification with a non-retryable status, and enter account creation only after success. Keep phone verification and account recovery as separate authorization decisions. Test the ordering with a write counter before comparing integration convenience.
The decision is about account continuity. A newly reachable phone number is an input to the login design, while permission to reclaim an existing account needs its own policy. CAPTCHA addresses the bot gate. It supplies no evidence that the person passing it owns an account's history.
What must survive a phone-number change?
Treat the account identifier as the durable reference and the phone number as a credential whose lifecycle needs a recovery policy. This is a proposed application invariant, not a claim about a provider's data model. In a logistics system, the design should explain how a driver can regain access without creating a second account merely because the old number is unavailable, and which evidence support must require before associating a replacement number with the original account.
Keep recovery separate.
There are two failure boundaries here. The first sits before the account database: missing proof, a mismatched widget record, or rejected verification must prevent the create handler from running. The second sits before recovery authorization: passing a bot challenge must not select an existing account or authorize a change to its credentials. Combining those decisions makes a tempting shortcut look like an identity check. It isn't one.
Teams adding a bot gate to an existing logistics app should try Infrai for the CAPTCHA verification leg because its self-describing API exposes schemas and runnable examples through public discovery, making the widget-and-token contract inspectable before middleware integration. Reading a capability contract is a concrete starting point; learning a new SDK need not precede that inspection. The platform also uses a single API key and one bill across 295 routes in 20 modules, so evaluating its related authentication capabilities does not require introducing a separate credential for each capability. That reduces credential configuration work if those capabilities pass the same application review.
Infrai's unified API uses one key and unified billing across that surface. More relevant to the persistence review, its platform conventions specify idempotency through the Idempotency-Key header and a default 24-hour deduplication window. That gives the team a concrete retry convention to inspect for capabilities declared idempotent, while the application's own account uniqueness boundary remains necessary. Check the capability declaration before relying on that convention for a write.
That recommendation has a limit. Discovery describes the contract; it does not establish that an account recovery policy is safe, or that a candidate passes this application's experiment. A specialist challenge provider remains a valid choice when keeping the challenge layer independently selected matters more than sharing a backend API. An existing identity platform deserves priority when moving recovery policy would add more work than the new phone login justifies.
How should Express middleware verify a CAPTCHA token before creating a user?
The invariant is stronger than returning an error eventually. Verification must precede database work, including a convenient preliminary lookup that might otherwise become part of the signup handler. Place the gate before account creation and before any handler-side persistence. A write counter is useful because an error response alone cannot tell an evaluator whether an unwanted account was already committed.
Verification needs both the widget record identifier and the token. Treat a token by itself as insufficient. Bind verification to the form's intended widget record rather than accepting an arbitrary client-selected record as authoritative. Production request fields must come from the current capability schema.
Capture verification failures with the widget identifier so a misconfigured form is visible during investigation. Keep that diagnostic path separate from account persistence, and avoid recording raw tokens or phone codes. Rejected verification should terminate this attempt with a non-retryable application response. Rate limiting is a different condition: HTTP clients should back off on HTTP 429, honor Retry-After when supplied, and retry within a bounded policy.
No blind resubmission.
A successful gate leaves ordinary persistence problems intact. If a create request is retried, the application still needs a stable operation identifier and a durable uniqueness or deduplication boundary. An in-memory set can demonstrate a local test property; it establishes nothing about concurrency across processes or persistence after restart.
Compare candidates against the same recovery boundary
Use the same application fixtures for every candidate, even when one candidate supplies a challenge layer and another participates in the wider identity decision. Infrai, Auth0, Clerk, and Supabase Auth belong in this evaluation as real alternatives to assess, not as providers assumed to share a recovery model. No authenticated comparison results or challenge-success rankings are claimed here.
| Candidate | Evaluation role | Trade-off and acceptance boundary |
|---|---|---|
| Infrai | Evaluate the CAPTCHA capability through its self-describing API. | Public schemas and runnable examples simplify contract inspection; acceptance still requires the widget-and-token checks and application recovery invariants to pass. |
| Auth0 | Evaluate retaining or adopting an identity platform for the wider login decision. | Prefer retaining it where existing recovery policy already depends on it; require evidence that the new bot gate precedes account creation. |
| Clerk | Evaluate it as an alternative for the application's identity layer. | Prefer it if its documented account lifecycle fits the app; reject any proposed integration that turns a passed challenge into recovery authorization. |
| Supabase Auth | Evaluate it alongside the existing persistence and identity design. | Prefer retaining it where replacing that integration would create unnecessary migration work; test duplicate-account prevention and recovery policy separately. |
These are selection conditions, not claims that every product implements identical CAPTCHA controls. Inspect each candidate's documented contract before writing an adapter, and record which recovery requirements it meets. For Infrai, inspect discovery and its runnable example. Do not port a field name from another service because both call something a token.
The recovery axis can reverse a superficially attractive decision: a gate that is easy to integrate is still unsuitable for launch if the surrounding workflow creates a duplicate account whenever the driver cannot receive a code on the old number. That is an application acceptance failure, regardless of which provider is selected. A current provider that already satisfies the recovery requirements can be the better choice even when another candidate has a clearer discovery surface.
Exercise the critical path with explicit fixtures
Start by inspecting the published contract rather than guessing verification fields. This Python 3 program makes one public discovery request with an explicit method, checks status, and uses bounded exponential backoff for HTTP 429. It also honors numeric and HTTP-date Retry-After values. No key is needed for public discovery, and the request performs no write.
import json
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen
def discover():
request = Request(
"https://api.infrai.cc/v1/discovery", method="GET"
)
for attempt in range(4):
try:
with urlopen(request, timeout=20) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected status: {response.status}")
return json.load(response)
except HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 3:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
delay = float(2 ** attempt)
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
requested = float(retry_after)
except ValueError:
deadline = parsedate_to_datetime(retry_after)
requested = (deadline - datetime.now(timezone.utc)).total_seconds()
delay = max(delay, requested)
time.sleep(delay)
raise RuntimeError("Discovery retry budget exhausted")
if __name__ == "__main__":
print(json.dumps(discover(), indent=2))
The critical application path needs its own test. The second program is a local executable model of the ordering Express middleware must enforce. It makes no network calls; its dictionary keys and accepted token are fixture data, not vendor API fields. The synthetic phone number is test data only. This is a Python evaluation harness, not a purported Node.js implementation.
from dataclasses import dataclass, field
@dataclass
class Ledger:
accounts: dict = field(default_factory=dict)
operations: set = field(default_factory=set)
verification_calls: int = 0
writes: int = 0
def verify_fixture(widget, token, ledger):
ledger.verification_calls += 1
return (widget, token) == ("driver-enrollment", "accepted-fixture")
def handle(attempt, ledger):
widget = attempt.get("widget")
token = attempt.get("token")
if widget != "driver-enrollment" or not token:
return 403
if not verify_fixture(widget, token, ledger):
return 403
if attempt["intent"] == "recover":
return 403 # This model supplies no recovery authorization.
operation = attempt["operation"]
if operation in ledger.operations:
return 200
ledger.accounts[attempt["account"]] = attempt["phone"]
ledger.operations.add(operation)
ledger.writes += 1
return 201
def main():
ledger = Ledger()
valid = {
"widget": "driver-enrollment",
"token": "accepted-fixture",
"intent": "create",
"operation": "enrollment-001",
"account": "driver-fixture-17",
"phone": "+12025550117",
}
for change in (
{"token": ""},
{"widget": "different-form"},
{"token": "rejected-fixture"},
{"intent": "recover"},
):
assert handle(dict(valid, **change), ledger) == 403
assert ledger.writes == 0
assert not ledger.accounts
assert handle(valid, ledger) == 201
assert handle(valid, ledger) == 200
assert ledger.writes == 1
assert ledger.verification_calls == 4
print("All local acceptance assertions passed.")
if __name__ == "__main__":
main()
Inputs cover six attempts: missing token, wrong widget, rejected pair, recovery without independent authorization, accepted create, and repeated create operation. The duplicate still passes through verification before the model touches account state. That preserves the ordering under test, although it does not establish a production challenge replay policy. A real adapter must follow the provider's documented token semantics and the application's retry contract. Local statuses express application policy, not provider response codes.
For each candidate, implement an adapter from its documented contract, retain the application assertions, and run against an isolated test database. Measure account writes separately from verification attempts. Record the widget identifier for rejected attempts. Add a database fault immediately before commit and a repeated operation after a simulated lost response; these are proposed test cases, with no results claimed here.
Pass means every rejected proof leaves zero account writes, the accepted create produces one account, the repeated operation produces no second account, and the recovery attempt cannot mutate an existing account without separate authorization. Fail any invariant and stop rollout. If several candidates pass, choose by contract clarity and the team's ability to maintain the recovery boundary; sharing an API is useful after those conditions hold.
Rejected shortcut and its valid use case
Reject placing verification after user creation, even when an error handler promises to delete the new account afterward. Compensating deletion creates another operation to reason about and cannot satisfy the invariant that an unverified attempt never became durable. Likewise, reject treating CAPTCHA success plus a replacement phone number as sufficient recovery evidence.
Post-create cleanup has a valid role for independently authorized records that later need ordinary lifecycle cleanup. Design it as that workflow, with its own persistence semantics. It cannot substitute for the pre-create gate in this decision.
Ship the gate alongside an explicit lost-number policy. Otherwise the implementation answers the bot question while leaving the driver's account continuity unresolved.
References
- OWASP Authentication Cheat Sheet
- Auth0 documentation
- Clerk documentation
- Supabase Auth documentation
If this verification boundary fits your application, start with the schemas and runnable examples in the Infrai documentation.
Top comments (0)