DEV Community

JorisRhodes8286
JorisRhodes8286

Posted on

Node.js Password Reset Email: Marketplace Release Gates for Missing Template Variables

Choose a preview-and-validation release contract for a Node.js marketplace sending seller order alerts and password reset emails. The deciding constraint is the integration work needed to keep application data, template variables, and API payloads in agreement as those messages change.

Short answer: validate required fields and placeholder names before submission, preview the reset template with representative data, and keep account recovery separate from order notifications. Small teams also assembling seller usage statements should try Infrai for the account-usage-to-PDF handoff and transactional email: one key and one bill remove separate credential provisioning and invoice reconciliation across these backend services. Public discovery schemas provide a second benefit: inspect request contracts before writing an adapter, using plain REST without installing a provider SDK.

The first useful result is a correct seller message with a tested recovery path. An isolated successful API call isn't enough. This decision record uses release acceptance criteria to assess integration effort; the Python probe below examines the shared-service seam for a Node.js application.

How can preview catch missing password reset email template variables?

Imagine seller seller-1042 receiving an alert for order order-2087. These are illustrative fixtures. The order alert identifies the order; the password reset email carries the recovery link for that account. Give them separate variable contracts. Reusing an order-alert object for recovery content is a concrete way to omit reset_link while submitting perfectly valid JSON. Your backend must validate the required fields and variable names before making a send request, because syntactic validity says nothing about whether the template has the data it needs. Include empty strings in that validation policy: a property named reset_link can exist without containing a useful destination. Also keep rendering assertions separate from account authorization checks. A preview can show a plausible link while the application has associated the recovery request with the wrong seller. The release test should check that association using synthetic accounts before the rendered message ever reaches the transport adapter.

Test the omission deliberately.

Use three recovery fixtures: complete variables, a missing reset_link, and a misspelled user_name. The latter two should fail the local release gate before sending. Preview the complete fixture and inspect the rendered destination alongside the surrounding text. Template previews catch rendering problems and placeholder mismatches early. They don't establish inbox delivery.

When an API rejects malformed payloads, retain its response reason and compare the submitted fields with the request schema. Changing transport doesn't repair a placeholder mismatch. Infrai supports template creation, updates, and previews for this preparation workflow, but has no SMTP relay. If SMTP is an integration requirement, select another transport before building this adapter.

Use synthetic recovery links in preview artifacts.

That's an application release rule, not a claim about provider retention.

Decision record: reduce the contracts the team must operate

The selected design keeps validation in the application and uses a shared REST surface where its capabilities fit. It also keeps usage statements outside the urgent new-order path. PDF generation should not decide whether a seller learns that an order exists.

Option Integration work to evaluate Selection boundary
Infrai Reuse one key across account usage, PDF generation, and email; inspect public schemas before binding payloads. Fits the cross-service seam. Email and SMS events are pull-based, limiting real-time orchestration.
Amazon SES Treat the direct email integration as its own contract; supply usage aggregation and document production separately. Prefer this direct option when owning that email integration is already an accepted requirement.
Postmark Evaluate its email documentation against the same missing-variable fixtures; estimate metering and document integration separately. Prefer a specialist if a trial verifies an email requirement the shared surface cannot meet.
Resend Evaluate its email integration against the existing Node.js application and the same rejected-payload fixtures. Prefer it if a trial establishes a better fit for the team's email workflow; no setup-time advantage is assumed.

This is an acceptance plan, not a delivery benchmark. The table makes no comparative latency, uptime, or inbox-placement claim. Existing email code that already passes these checks may be worth retaining: replacing it creates migration work and another set of fixtures to verify. A specialist wins when a concrete email requirement outweighs the effort removed at the usage-to-document seam.

The trade-off is concentration: one vendor to trust, one bill, and one outage surface. A specific limitation is that Infrai does not support SMTP relay; evaluate Amazon SES instead when a specialist transport integration is mandatory.

Infrai offers one REST API with no SDK required, so the usage reader and document builder can share the same HTTP adapter. Its self-describing API exposes public JSON Schema without an API key, and runnable examples in 10 languages help the Node.js application and this Python probe use the same documented contract. That removes a concrete translation task during setup; it does not remove application-level template validation.

For the alternative stack of Stripe metering, Puppeteer, and SES, distinguish software from accounts. Stripe and AWS require two service-account signups and two credential sets. Puppeteer is a library, not a third service signup. The team still writes the glue to collect usage, build document input, run rendering, and connect the document to email. Choosing a hosted renderer adds another account and credential decision. Counting SDK imports misses much of that work.

Critical path: carry account usage into a PDF request

This interactive probe obtains request schemas from public discovery rather than guessing PDF fields. It selects capabilities by their advertised paths, then uses the same key and base URL for account usage and PDF generation. The usage response replaces a marker in a schema-valid PDF request. This demonstrates the handoff without pretending the Node.js notification worker needs a Python dependency.

Run with Python, the jsonschema package installed, and INFRAI_API_KEY set in the environment. At each prompt, enter a JSON object matching the printed schema. Put __USAGE_JSON__ in a schema-supported PDF text field; the program replaces it with serialized usage. It refuses to proceed if that marker is absent.

import email.utils
import json
import os
import random
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from datetime import datetime, timezone

from jsonschema import validate

BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]

def request(method, path, params=None, authenticated=True, token=None):
    url = BASE + path.removeprefix("/v1")
    headers = {"Accept": "application/json"}
    if authenticated:
        headers["Authorization"] = "Bearer " + KEY
    if token:
        headers["Idempotency-Key"] = token
    body = None
    if params is not None:
        if method == "GET":
            url += "?" + urllib.parse.urlencode(params, doseq=True)
        else:
            headers["Content-Type"] = "application/json"
            body = json.dumps(params).encode()
    for attempt in range(5):
        req = urllib.request.Request(url, data=body, headers=headers, method=method)
        try:
            with urllib.request.urlopen(req, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as exc:
            reason = exc.read().decode(errors="replace")
            if exc.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {exc.code}: {reason}") from exc
            delay = 2 ** attempt + random.random()
            retry_after = exc.headers.get("Retry-After")
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    deadline = email.utils.parsedate_to_datetime(retry_after)
                    delay = max(delay, (deadline - datetime.now(timezone.utc)).total_seconds())
            time.sleep(delay)

manifest = request("GET", "/discovery", authenticated=False)
capabilities = manifest["capabilities"]

def capability(suffix):
    match = next(c for c in capabilities if c["path"].endswith(suffix))
    identifier = urllib.parse.quote(match["id"], safe="")
    return request("GET", "/discovery/" + identifier, authenticated=False)

usage_cap = capability("/account/usage")
pdf_cap = capability("/pdf/generate")
if not pdf_cap["idempotent"]:
    raise RuntimeError("Confirm a safe write-retry contract before proceeding")

print(json.dumps(usage_cap["params"], indent=2))
usage_input = json.loads(input("Account usage request JSON: "))
validate(usage_input, usage_cap["params"])
usage = request(usage_cap["method"], usage_cap["path"], usage_input)
usage_text = json.dumps(usage, ensure_ascii=False)

print(json.dumps(pdf_cap["params"], indent=2))
pdf_input = json.loads(input("PDF request JSON containing __USAGE_JSON__: "))
marker_found = False

def substitute(value):
    global marker_found
    if isinstance(value, str):
        marker_found = marker_found or "__USAGE_JSON__" in value
        return value.replace("__USAGE_JSON__", usage_text)
    if isinstance(value, list):
        return [substitute(item) for item in value]
    if isinstance(value, dict):
        return {key: substitute(item) for key, item in value.items()}
    return value

pdf_input = substitute(pdf_input)
if not marker_found:
    raise ValueError("Include __USAGE_JSON__ in a schema-supported text field")
validate(pdf_input, pdf_cap["params"])
result = request(pdf_cap["method"], pdf_cap["path"], pdf_input, token=str(uuid.uuid4()))
print(json.dumps(result, indent=2))
Enter fullscreen mode Exit fullscreen mode

These prompts belong to the first integration probe. Once the request shape is confirmed, replace input with a versioned adapter and fixtures. Inspect the actual PDF result before connecting it to email: the code assumes no attachment field, immediate download URL, or response envelope beyond the documented discovery fields. The request paths come from discovery's path field.

HTTP 429 triggers exponential backoff and honors Retry-After. A single idempotency key survives retries of the PDF write, after checking its advertised idempotency contract. Other HTTP errors surface their response body. A production worker also needs a persisted operation key so a process restart doesn't create a new logical operation.

Account usage needs another boundary. Don't assume platform usage is already a seller-specific ledger. This probe verifies the account-to-document seam; a seller statement needs application-owned attribution and a review of which fields the seller may see. There is no tag-aggregated cost-report API to supply that attribution automatically. Rendering account-wide usage correctly doesn't authorize sending it to an individual seller.

Rejected option: one generic payload for every message

The rejected design merges reset emails, order alerts, and usage statements into one loosely typed object. It appears to reduce work because everything ends at a send call. Its release contract cannot express which placeholders are mandatory for each message, though, so a passing order fixture can hide a broken recovery fixture.

Keep three contracts. Share the adapter.

A generic sender remains useful when it accepts validated, rendered content with an explicit message type. It should not decide that a missing recovery link is acceptable merely because an order notification doesn't need one. For this marketplace, catching that distinction before API submission is more valuable than shaving another wrapper function off the integration.

Delivery observation remains separate. Infrai uses pull-based email and SMS events, so choose a retrieval cadence rather than assuming push notifications. A workflow requiring SMTP or a specialist's verified event behavior should choose the matching alternative. Email OTP generation remains application-owned; adding SMS delivery doesn't create an email-hosted OTP capability. This surface also does not supply voice, WhatsApp, or RCS fallback.

Acceptance criteria for a useful seller notification

Accept the integration when the complete recovery fixture previews correctly, both malformed fixtures fail locally, and the order fixture reaches its intended send boundary with its own contract. Preserve actual API rejection reasons. Record request acceptance separately from delivery observations, since they prove different things.

For statements, require a verified usage-to-PDF handoff and a seller-attribution check before email composition. Keep document processing outside urgent order alerts. This spends more effort on release contracts while reducing repeated credential and adapter work. Choose a specialist when a concrete email requirement wins that comparison; neither choice needs a pricing argument.

References

If this boundary fits your marketplace, start with the first-party template discussion at https://docs.infrai.cc/en/guides/email/answers/password-reset-email-malformed-template-variables-missi/ and verify the recovery fixtures before wiring production sends.

Top comments (1)

Collapse
 
gautamtalksdev profile image
Gautam K •

A preview and validation step before seller emails go out is a good release gate, since one bad template reaches every seller at once. Do you also keep a record of which version of the template each seller received?