# Email Validation API Code Samples in TypeScript

URL: https://email-validation.org/docs/code-samples/typescript/
Updated: 2026-11-29

> Documentation index: https://email-validation.org/llms.txt

Copy-paste TypeScript examples that validate one address, send the API key in the `Authorization` header, retry
`429` and `503` answers after `Retry-After` when the wait is at most 10 seconds (never `key_daily_cap`, which lasts
until the next UTC day), and report other errors with their code and request id. Each uses the free test address
`accepted@sandbox.email-validation.org`; replace it with a real address when you are ready. The same samples in other
languages: [all code samples](https://email-validation.org/docs/code-samples/).

Set your key first: `export EV_API_KEY="ev_live_…"`.

The samples call `https://api.email-validation.org`. For EU data residency, replace it with `https://api-eu.email-validation.org`, or pass the SDK's EU base URL constant;
there `/v1/validate` takes `POST` only ([EU data residency](https://email-validation.org/docs/eu-data-residency/)).

## With the official SDK

The [official JavaScript and TypeScript SDK](https://email-validation.org/docs/sdks/javascript/) does the retries, timeouts and error mapping
for you: one call validates an address and every failure arrives as a typed error. There are official SDKs for JavaScript/TypeScript, Python, Go, PHP, Ruby, C#, Rust and Swift; those for Java, Kotlin, Dart, Elixir, C and Perl are built and tested and coming soon to their package registries. The plain
HTTP samples further down call the API directly.

**TypeScript**

```ts
import { EmailValidation, EmailValidationError, InsufficientCreditsError } from '@email-validation/sdk';

const ev = new EmailValidation({ apiKey: process.env.EV_API_KEY! });

try {
  const result = await ev.validate('accepted@sandbox.email-validation.org');
  console.log(result.status, result.reason, result.action); // valid accepted send
} catch (err) {
  if (err instanceof InsufficientCreditsError) console.error('buy credits; nothing was charged');
  else if (err instanceof EmailValidationError) console.error(err.code, err.requestId);
  else throw err;
}
```

## Validate an address

**TypeScript**

```ts
type Status = 'valid' | 'invalid' | 'catch_all' | 'unknown' | 'disposable';
type Action = 'send' | 'send_with_caution' | 'remove' | 'retry_later';

interface ValidationResult {
  email: string;
  status: Status;
  reason: string;
  action: Action;
  did_you_mean: string | null;
  credits_used: 0 | 1;
  request_id: string;
}

interface ApiError {
  error: { code: string; message: string; request_id: string };
}

const MAX_WAIT_S = 10; // never wait out a long Retry-After (key_daily_cap lasts until the next UTC day)

export async function validate(email: string, attempts = 3): Promise<ValidationResult> {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch('https://api.email-validation.org/v1/validate', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.EV_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email }),
      signal: AbortSignal.timeout(20_000),
    });
    if (res.ok) return (await res.json()) as ValidationResult;
    const { error } = (await res.json()) as ApiError;
    const wait = Number(res.headers.get('Retry-After')) || 1;
    const retryable =
      (res.status === 429 || res.status === 503) && error.code !== 'key_daily_cap' && wait <= MAX_WAIT_S;
    if (retryable && attempt < attempts) {
      await new Promise((resolve) => setTimeout(resolve, wait * 1000));
      continue;
    }
    throw new Error(`${error.code}: ${error.message} (${error.request_id})`);
  }
}

const result = await validate('accepted@sandbox.email-validation.org');
console.log(result.status, result.reason, result.action, result.credits_used);
```

## Verify a webhook

**TypeScript**

```ts
// Web Crypto: Cloudflare Workers, Deno, Bun, Node.js 22+.
export async function verifyWebhook(
  rawBody: string,
  headers: Headers,
  secret: string,
  toleranceSeconds = 300,
): Promise<unknown> {
  const id = headers.get('webhook-id');
  const timestamp = headers.get('webhook-timestamp');
  const signatures = headers.get('webhook-signature');
  if (!id || !timestamp || !signatures) throw new Error('Missing webhook headers');
  const ts = Number(timestamp);
  if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > toleranceSeconds) {
    throw new Error('Timestamp outside tolerance');
  }
  const toBytes = (b64: string) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
  const key = await crypto.subtle.importKey(
    'raw',
    toBytes(secret.replace(/^whsec_/, '')),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify'],
  );
  const data = new TextEncoder().encode(`${id}.${timestamp}.${rawBody}`);
  for (const entry of signatures.split(' ')) {
    const [version, sig] = entry.split(',');
    if (version !== 'v1' || !sig) continue;
    let given: Uint8Array;
    try {
      given = toBytes(sig);
    } catch {
      continue;
    }
    // crypto.subtle.verify compares in constant time.
    if (await crypto.subtle.verify('HMAC', key, given, data)) return JSON.parse(rawBody);
  }
  throw new Error('No valid signature');
}

// In a Worker: const event = await verifyWebhook(await request.text(), request.headers, env.EV_WEBHOOK_SECRET);
```

## Other calls

- Read the credit balance: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#credits)).
- Create a bulk job: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#bulk)).

## Notes

- Use `POST` with a JSON body; it keeps addresses out of URLs and logs.
- Set the HTTP timeout to about 20 seconds: a check may take up to 15 seconds (10 by default).
- A `200` answer with the status `unknown` is a normal, free result, not an error.
- Every endpoint, field and error: the [API reference](https://email-validation.org/docs/api-reference/).
