Testing Better Auth and NextAuth OTPs in Playwright in Under 150ms (No IMAP Polling)
Testing email based authentication in end to end Playwright suites is notoriously brittle. Whether your application runs Better Auth, NextAuth, or Supabase Auth, verifying that a user receives an OTP code or magic link
Testing email based authentication in end to end Playwright suites is notoriously brittle.
Whether your application runs Better Auth, NextAuth, or Supabase Auth, verifying that a user receives an OTP code or magic link usually forces developers into one of two anti patterns:
- Polling a shared staging IMAP mailbox every two seconds, waiting 15 to 30 seconds for delivery while risking network timeouts.
- Mocking out email delivery entirely, which tests your mock rather than the actual token generation, URL encoding, and HTML template layout.
In this recipe, we will build a deterministic, reactive test inbox flow in Playwright that intercepts inbound emails via webhook in under 150ms.
The Problem With IMAP Polling Loops
A typical end to end authentication test looks something like this:
// Anti pattern: Flaky IMAP polling
await page.getByRole('button', { name: 'Send Code' }).click();
let otpCode: string | null = null;
for (let i = 0; i < 15; i++) {
otpCode = await checkImapInboxForOtp(testUserEmail);
if (otpCode) break;
await page.waitForTimeout(2000);
}
expect(otpCode).not.toBeNull();
This pattern suffers from severe failure modes:
- High Latency: Adding 10 to 20 seconds per test run slows down continuous integration pipelines.
- Shared State Collisions: Multiple parallel test workers reading from the same staging mailbox cause race conditions.
- IMAP Throttling: Gmail, Outlook, and corporate relays throttle aggressive IMAP connection churn.
The Reactive Webhook Architecture
Instead of polling an external mail server, we use ephemeral inboxes paired with instant HTTP callbacks.
Here is the operational sequence:
- Before navigating to the signup form, your test requests an ephemeral address from a test inbox service.
- The test fills in the form and clicks submit.
- Your application dispatches the transactional auth email through its delivery relay.
- The delivery relay delivers the payload to the test inbox webhook within 150ms.
- The test grabs the OTP code directly from the parsed payload and submits it to the input field.
Runnable Playwright Code Recipe
Here is a complete, production ready Playwright test using this reactive pattern:
import { test, expect } from '@playwright/test';
test.describe('Authentication Flows', () => {
test('should verify 2FA OTP in under 150ms without polling', async ({ page, request }) => {
// 1. Provision an isolated ephemeral test address
const inboxResponse = await request.post('https://api.sadasend.com/v1/test-inboxes', {
headers: { Authorization: `Bearer ${process.env.SADASEND_API_KEY}` }
});
const { email: testEmail, inboxId } = await inboxResponse.json();
// 2. Navigate to login and submit email
await page.goto('/auth/login');
await page.getByLabel('Email Address').fill(testEmail);
await page.getByRole('button', { name: 'Send Verification Code' }).click();
// 3. Await the webhook payload directly (reactive, sub 150ms)
const messageResponse = await request.get(`https://api.sadasend.com/v1/test-inboxes/${inboxId}/messages/latest`, {
headers: { Authorization: `Bearer ${process.env.SADASEND_API_KEY}` }
});
const message = await messageResponse.json();
// 4. Extract OTP from parsed JSON payload via regex
const otpMatch = message.textBody.match(/\b\d{6}\b/);
expect(otpMatch).toBeTruthy();
const otpCode = otpMatch![0];
// 5. Fill OTP into browser input and verify login
await page.getByLabel('Enter 6-digit Code').fill(otpCode);
await page.getByRole('button', { name: 'Verify' }).click();
// 6. Confirm successful authentication redirect
await expect(page).toHaveURL('/dashboard');
await expect(page.getByText('Welcome back')).toBeVisible();
});
});
Key Advantages of Reactive Test Inboxes
- Sub 150ms Execution: Your test receives the verification token before the browser even completes DOM hydration.
- Deterministic CI: Zero timeout flakiness in GitHub Actions or GitLab CI.
- No Domain Burn: Test inboxes isolate automated traffic from production sender reputation.
💡 Developer Infrastructure Note: For production transactional email delivery with built in bounce defense and reactive test inboxes, check out SadaSend.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.