Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

Typed Email Boundaries for React Forms

A signup form can look simple, but the email step are where a surprising number of product bugs hide. A user submits an address, the API sends a message, a link opens in another tab, and React has to explain what happens

A signup form can look simple, but the email step are where a surprising number of product bugs hide. A user submits an address, the API sends a message, a link opens in another tab, and React has to explain what happens next. When those responsibilities leak into one component, every small change becomes harder to test.

This article shows a practical boundary for React and TypeScript email flows. The goal is not to build a full inbox mock. It is to give the UI a small, typed contract that can be tested with deterministic fixtures and swapped between a local environment and CI.

Why email needs a boundary in React

Email verification has more states than isLoading and isVerified. A useful flow usually includes:

  • idle: the user has not submitted an address
  • sending: the request is in progress
  • sent: the message was accepted and a resend timer can start
  • verified: the token was accepted
  • expired: the token is no longer useful
  • failed: the user can see an actionable error

If a component talks directly to a vendor SDK, it starts making decisions about network errors, message IDs, expiry, and retry rules. The rendering code then knows too much. It also becomes tempting to assert on vendor-shaped responses in every test.

Put one adapter between the form and the email service. The component should ask for an address and receive a result that is meaningful to the product, not a raw provider payload. That makes the boundary easier to review and the behaviour more predictable.

Model the flow as a small state machine

Start with a discriminated union. It prevents impossible combinations such as verified: true and error: "timeout" appearing together.

type EmailState =
  | { kind: "idle"; value: string }
  | { kind: "sending"; value: string }
  | { kind: "sent"; value: string; expiresAt: number }
  | { kind: "verified"; value: string }
  | { kind: "expired"; value: string }
  | { kind: "failed"; value: string; message: string };

type EmailGateway = {
  requestVerification(email: string): Promise<{ expiresAt: number }>;
  confirmVerification(token: string): Promise<void>;
};

The kind field gives the React view a single decision point:

function VerificationMessage({ state }: { state: EmailState }) {
  switch (state.kind) {
    case "sending":
      return <p>Sending a verification link…</p>;
    case "sent":
      return <p>Check your inbox before {new Date(state.expiresAt).toLocaleTimeString()}.</p>;
    case "verified":
      return <p>Email confirmed.</p>;
    case "expired":
      return <p>The link expired. Request a new one.</p>;
    case "failed":
      return <p role="alert">{state.message}</p>;
    default:
      return null;
  }
}

The UI doesnt need to understand whether the provider returned a 429, a timeout, or a malformed response. The adapter maps those details to failed, while the component stays focused on the user experience.

Keep the adapter typed

The implementation can be small. Validate the input before making a request, normalize provider errors, and return only the fields the product needs.

class VerificationService implements EmailGateway {
  constructor(private readonly request: typeof fetch) {}

  async requestVerification(email: string) {
    const response = await this.request("/api/verification", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ email }),
    });

    if (!response.ok) {
      throw new Error("verification_request_failed");
    }

    const data: unknown = await response.json();
    if (!isExpiryPayload(data)) {
      throw new Error("invalid_verification_response");
    }

    return data;
  }

  async confirmVerification(token: string) {
    const response = await this.request("/api/verification/confirm", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ token }),
    });

    if (!response.ok) throw new Error("verification_confirmation_failed");
  }
}

function isExpiryPayload(value: unknown): value is { expiresAt: number } {
  return typeof value === "object" && value !== null &&
    "expiresAt" in value && typeof value.expiresAt === "number";
}

Do not let the adapter silently retry a request that may send another message. A resend action should be explicit, and the server should own idempotency or rate limiting. For teams changing email addresses, keeping an audit trail of the event is also useful; these auditable email-change events are a good backend companion to the frontend boundary.

Test the boundary, not the inbox vendor

Inject the gateway into the hook or component. In a unit test, the fake gateway can resolve or reject immediately:

const gateway: EmailGateway = {
  requestVerification: vi.fn().mockResolvedValue({
    expiresAt: Date.now() + 10 * 60 * 1000,
  }),
  confirmVerification: vi.fn().mockResolvedValue(undefined),
};

Then test product outcomes:

  1. Submitting a valid address enters sending and then sent.
  2. A rejected request renders an actionable failure.
  3. A second click is disabled while the first request is running.
  4. An expired token offers a clear resend path.
  5. A malformed provider response never reaches the success state.

For end-to-end tests, use a dedicated fixture mailbox or a temporary email address only for non-sensitive test data. Never place real customer information in a shared inbox. The fixture should be created per test run and deleted on cleanup, even when a test fails.

This is also where odd input cases belong. Keep examples such as temp gamil com and tem email in validation tests if they represent real support tickets. They help ensure the UI gives a useful message instead of letting a typo travel to the backend.

A short debugging checklist

When an email test flakes, check the boundary in this order:

  • Did the form submit once, or did a double click create two requests?
  • Did the adapter normalize the provider error into a stable code?
  • Is the expiry timestamp coming from the server rather than the browser clock?
  • Does the test clean up its fixture when an assertion fails?
  • Are logs showing the request ID instead of the full email address?
  • Is the CI enviroment using the same API contract as local development?

If the failure is in redirect handling, review the trust assumptions separately. A few OAuth redirect test ideas can help expose a similar class of boundary bug, where a browser flow succeeds but the app accepts the wrong destination.

Questions teams usually ask

Should the state machine live in a custom hook?

Usually, yes, when more than one screen shares the flow. Keep the gateway outside the hook and pass it in, so tests can use a fake without mocking modules globally. If only one small form uses it, a local reducer is fine.

Should we put the email in every log?

No. Use a request ID, a short hash, or a redacted representation. Email is user data, and a debug statement can easily survive longer than the test enviroment that created it.

What belongs in a fixture factory?

Only stable fields needed by the test: an address, a run ID, a token, and an expiry. Keep vendor-specific setup seperately from the assertions, and make cleanup part of the factory contract.

Ship the boundary in small steps

First define the union and the gateway interface. Next move provider mapping into one adapter. Then replace broad component mocks with a fake gateway and add one failure test for each state transition. Finally, add a run-scoped mailbox for the few end-to-end checks that need a real message.

That sequence keeps the change reviewable. It also means a provider migration, a new resend policy, or a TypeScript refactor does not force the whole React form to be rewritten. The result is a smaller UI contract, clearer failures, and email tests that recieve the same care as the rest of the product.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.