Menu JavaScript / TypeScript

SDKs

JavaScript and TypeScript SDK

The official client of the fake-email.pro API for Node.js and TypeScript, built on the standard fetch. It covers every endpoint with typed models, turns errors into exceptions you can catch by type, retries rate limits on its own, and waits for the email of an end-to-end test – handing back its one-time code or confirmation link. Open source under the MIT license.

Node 18+, no dependencies, ESM and CommonJS, types included

Terminal
npm install fake-email-pro

fake-email-pro on npmSource on GitHub

API key

Create a key as in Quickstart and put it in the FAKE_EMAIL_API_KEY environment variable – a CI secret on a build agent. The client reads it from there, or takes it as apiKey. The API is server-to-server, without CORS: run the client in Node, in the test runner or in a Cypress task, never in the page under test.

Quickstart

JavaScript
import { FakeEmail } from 'fake-email-pro'

const client = new FakeEmail() // reads FAKE_EMAIL_API_KEY

const mailbox = await client.mailboxes.create()
console.log('Sign up with', mailbox.address)

try {
  // Long-polls the mailbox for up to 60 s and returns the one-time code
  const code = await client.waitForCode(mailbox.address, { subject: 'verification' })
  console.log(code)
} finally {
  await client.mailboxes.delete(mailbox.address)
}

Playwright

A fixture gives each test its own mailbox, and waitForCode waits across as many long polls as the timeout allows.

TypeScript
import { test as base, expect } from '@playwright/test'
import { FakeEmail, type Mailbox } from 'fake-email-pro'

const fakeEmail = new FakeEmail()

// A fresh mailbox for every test, deleted when the test ends
const test = base.extend<{ mailbox: Mailbox }>({
  mailbox: async ({}, use) => {
    const mailbox = await fakeEmail.mailboxes.create()
    await use(mailbox)
    await fakeEmail.mailboxes.delete(mailbox.address)
  },
})

test('sign-up is confirmed with the emailed code', async ({ page, mailbox }) => {
  test.setTimeout(90_000) // longer than the wait below
  await page.goto('/sign-up')
  await page.getByLabel('Email').fill(mailbox.address)
  await page.getByRole('button', { name: 'Sign up' }).click()

  const code = await fakeEmail.waitForCode(mailbox.address, { timeoutMs: 60_000 })
  await page.getByLabel('Code').fill(code)
  await expect(page.getByText('Email confirmed')).toBeVisible()
})

Cypress

Cypress runs the test in the browser, so the client goes into tasks in cypress.config.ts, which run in Node. The task timeout is longer than the wait.

// cypress.config.ts – tasks run in Node, so the key never reaches the browser
import { defineConfig } from 'cypress'
import { FakeEmail } from 'fake-email-pro'

const fakeEmail = new FakeEmail()

export default defineConfig({
  e2e: {
    setupNodeEvents(on) {
      on('task', {
        createMailbox: () => fakeEmail.mailboxes.create(),
        waitForLink: (address: string) => fakeEmail.waitForLink(address, { timeoutMs: 60_000 }),
        deleteMailbox: (address: string) => fakeEmail.mailboxes.delete(address).then(() => null),
      })
    },
  },
})

Waiting for an email

  • waitForMessage(address, options) – the first message that matches from, subject and an optional match function. It repeats the 60-second long poll until timeoutMs (60 s by default), then throws WaitTimeoutError; an AbortSignal in signal cancels it.
  • waitForCode and waitForLink – the same, returning the code or the confirmation link the API read out of the email; a message without one is skipped.
  • For the next email in the same mailbox, pass after with the id of the one you have. More on the flow in Email testing.
JavaScript
const first = await client.waitForMessage(address, { subject: 'Welcome' })

// Strictly after the first one: nothing that arrived in between is lost
const second = await client.waitForMessage(address, {
  after: first.id,
  match: message => message.attachmentsCount > 0,
})

Methods and models

Every endpoint method also takes { signal, timeoutMs, maxRetries } as its last argument, for that one call. The wait helpers take WaitForMessageOptions instead: signal, and timeoutMs for the whole wait; they run their retries themselves, so there is no maxRetries. listAll is an async iterator over every page.

The client has a method for each endpoint of the API; their parameters and responses are in Endpoints.

Errors and retries

Every error of the API is thrown as an APIError with the HTTP status, the error code, the message and the rate-limit headers; its subclass names the case: BadRequestError 400, AuthenticationError 401, QuotaExhaustedError 402, PermissionDeniedError 403, NotFoundError 404, ConflictError 409, RateLimitError 429, InternalServerError 5xx. What each status and code means is in Errors. A request that got no response throws APIConnectionError, and one whose HTTP attempt outlasted its timeout APITimeoutError, a subclass of it.

Retries (twice by default) wait the Retry-After of the response, or a short backoff without one. A 429 and a 503 are retried on every method, since the server refused them before doing anything – except a 503 that asks to come back in more than 5 s, which is thrown at once. A network error, a timed-out attempt, a 502, a 504 and Cloudflare's 520–524 are retried on GET and DELETE only, so a mailbox is never created twice; a retried DELETE that gets 404 counts as done, since the attempt before it went through. A wait helper waits out 429, 502–504, 520–524 and connection errors until its own deadline, and then throws WaitTimeoutError.

Configuration

JavaScript
const client = new FakeEmail({
  apiKey: 'fep_...', // default: process.env.FAKE_EMAIL_API_KEY
  baseUrl: 'https://api.fake-email.pro', // default
  timeoutMs: 30_000, // per HTTP attempt; a wait request always gets its server timeout + 10 s
  maxRetries: 2,
  fetch: customFetch, // default: the global fetch
  userAgent: 'my-e2e-suite/1.0', // appended to fake-email-pro-js/<version>
})

Types for every object are exported – Mailbox, SimpleMessage, DetailedMessage, Limits and the rest – generated from the OpenAPI document.

Other languages

C# / .NET, Go, Java, PHP, Python – or every SDK and the OpenAPI document for any other language.

Something missing, confusing or wrong on this page? Tell us