Official SDK
JavaScript & TypeScript SDK
The official JavaScript and TypeScript SDK has no dependencies: it uses only the standard fetch, AbortSignal and Web Crypto APIs and ships its own TypeScript types. It is tested on Node.js 24 and needs Node.js 24 or later.
- npm package
@email-validation/sdk- Registry
- npm
- State
- Published Version 1.1.0
npm install @email-validation/sdkPublished on npm: @email-validation/sdk, version 1.1.0.
Install
In a terminal (on Windows: PowerShell), make a project folder. The examples on this page are ES modules, so the folder's package.json says "type": "module":
mkdir ev-quickstart
cd ev-quickstart
npm init -y
npm pkg set type=moduleThen add the SDK:
npm install @email-validation/sdkIf PowerShell answers that running scripts is disabled, type npm.cmd instead of npm, or use Command Prompt.
Set your API key
Create a key under API keys (quickstart step 1). The code below reads it from the EV_API_KEY environment variable. In the same terminal, run the line for your system, paste the key and press Enter (the key does not show):
macOS / Linux
# Paste the key, then press Enter.
read -rs EV_API_KEY && export EV_API_KEYPowerShell
# Windows PowerShell 5.1 and PowerShell 7. This window only. Paste the key, then press Enter:
$env:EV_API_KEY = [Net.NetworkCredential]::new('', (Read-Host -AsSecureString)).PasswordOptional: to keep the key for windows you open later, run setx EV_API_KEY $env:EV_API_KEY once after the line above. It saves the key in your Windows user environment. To remove it again, run [Environment]::SetEnvironmentVariable('EV_API_KEY', $null, 'User') and open a new window.
In Command Prompt (cmd.exe), run set /p EV_API_KEY= instead and paste the key: Command Prompt shows it as you paste, so run cls afterwards to clear the screen. The key stays set until you close that window.
Validate an address
Save this as index.ts in the folder:
import { EmailValidation } from '@email-validation/sdk';
const ev = new EmailValidation({ apiKey: process.env.EV_API_KEY! });
const result = await ev.validate('accepted@sandbox.email-validation.org');
console.log(result.status, result.reason, result.action); // valid accepted sendThen run it in the same terminal:
node index.tsNode.js 24 runs a TypeScript file as it is, with no build step. The examples on this page are TypeScript. In plain JavaScript, leave out the ! after process.env.EV_API_KEY and the type annotations; everything else is the same: save it as index.js and run node index.js. The examples are ES modules (import and top-level await): run them from a .mjs file, or set "type": "module" in package.json, as the install step does.
Keep the API key on your server: never put it in browser code or in an app you ship to other people. On a public web page, use only a browser key, for example with the form guard.
Options: ipAddress, timeout (seconds the check may take, 5–15), fresh and signal (an AbortSignal). fresh: true checks the address again even when it was checked in the last 12 months (see repeat checks). The result type lists every field with its type; status, reason and action are string unions, so a switch over them is checked by the compiler.
EU data residency
To check addresses and store their results in the EU, point the client at the EU endpoint, https://api-eu.email-validation.org:
import { EmailValidation } from '@email-validation/sdk';
const ev = new EmailValidation({ apiKey: process.env.EV_API_KEY!, baseUrl: 'https://api-eu.email-validation.org' });Write the URL itself, as above: that works with every release. The SDK also exports it as EU_BASE_URL from 1.0.2 on; importing that from 1.0.0 gives undefined in CommonJS or a bundle, and a client without baseUrl calls https://api.email-validation.org. Everything else stays the same; on the EU endpoint a check is always sent as a POST. See EU data residency.
Handle errors
import {
EmailValidationError,
InsufficientCreditsError,
RateLimitError,
} from '@email-validation/sdk';
const address = 'accepted@sandbox.email-validation.org';
try {
await ev.validate(address);
} catch (err) {
if (err instanceof InsufficientCreditsError) {
// buy credits; nothing was charged
} else if (err instanceof RateLimitError) {
console.log(`retry in ${err.retryAfterS}s`);
} else if (err instanceof EmailValidationError) {
console.error(err.code, err.status, err.requestId);
} else {
throw err;
}
}Every error from a call to the API extends EmailValidationError with status (0 when no answer arrived), code, requestId and retryAfterS. Subclasses: InvalidRequestError, AuthenticationError, InsufficientCreditsError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, ServiceUnavailableError, ServerError and ConnectionError. An argument of the wrong shape, such as a bad results filter, throws a TypeError before anything is sent, and a malformed job id is an InvalidRequestError with status 0, also unsent. The API checks values, such as an empty address or a validation timeout outside 5–15 seconds, and answers 400 invalid_request, which costs nothing. verifyWebhook throws its own WebhookVerificationError (verify webhooks).
Retries and timeouts
const ev = new EmailValidation({
apiKey: process.env.EV_API_KEY!,
timeoutMs: 30_000, // per attempt
maxRetries: 2, // after 429 / 503 answers
maxRetryWaitMs: 10_000, // longer Retry-After values are returned to you instead of waited out
});429 and 503 answers are retried with backoff, honoring Retry-After. A daily key cap is never retried. After a network failure or a timeout only reads are sent again: on Node.js and in Workers, a validation (or a bulk upload, start or cancel) is never sent again, by any version of the SDK or by fetch, because it may already have been charged. In a browser, fetch itself may send a POST or DELETE once more on a new connection when the one it reused breaks, and no SDK version can stop it, so a check or a whole bulk list could be charged twice: send the calls that spend credits (validate, bulk.create, bulk.start) from your server.
timeoutMs bounds each attempt of a JSON call as a whole. From version 1.1.0, transfers use it as an idle timeout instead, so large files are never cut off. A bulk.create file upload may take timeoutMs plus the time to send the file at 128 KiB/s until the answer starts (it is sent in 64 KiB pieces, so Node's own 300 s limits never cut it while it moves). A bulk.results body may wait timeoutMs for each next piece, with no limit while it keeps arriving. 1.1.0 also adds requestTimeoutMs to every call, which replaces timeoutMs for that one call (and for each poll of bulk.wait):
const credits = await ev.credits({ requestTimeoutMs: 5_000 });Pass signal (an AbortSignal) to stop a call, a retry wait or a poll wait at once: it fails with ConnectionError and the code aborted, and is never retried.
A bulk.create that ends in a timeout or connection_error, or is aborted through its signal (aborted), may still have created the job: the service can receive the whole list after the SDK stopped waiting, and unless you passed start: false that job may have started and charged its eligible checks. The API has no job list and no idempotency key, so before you upload the list again, look for the job under Bulk lists in the dashboard (jobs created through the API are listed there too, as "Untitled list" with their upload time). A webhook cannot tell you whether the job was created: a job created through the API sends bulk.completed / bulk.failed only to the endpoint you passed as webhookEndpointId, and only when the job ends.
Credits, usage and status
const credits = await ev.credits(); // { balance, debt, pending, lots }
// the last 90 days by default; pass from / to as YYYY-MM-DD for another range
const usage = await ev.usage({ groupBy: 'day' });
const status = await ev.status();Bulk jobs
Bulk calls need a key with the Bulk lists permission (the bulk scope). New keys get only validate and account:read, so turn it on for the key in the dashboard first; without it, every bulk call fails with 403 forbidden (scopes).
Each block below creates exactly one job and follows that job's id: copy one of them, not both (every create is a new job, and a job that starts uses credits for its eligible checks). From a list (JSON, up to 100,000 addresses):
let job = await ev.bulk.create({ emails: ['accepted@sandbox.email-validation.org', 'catch_all@sandbox.email-validation.org'] });
job = await ev.bulk.wait(job.id, { onProgress: (j) => console.log(j.status, j.processed) });
if (job.status === 'completed') {
const res = await ev.bulk.results(job.id, { filter: ['valid', 'catch_all'] });
console.log(await res.text()); // or stream res.body for large files
} else if (job.status === 'ready') {
// it could not start: job.error_code is e.g. 'insufficient_credits' (buy credits, then ev.bulk.start(job.id))
}Or from a CSV file (up to 100 MB), then fetch the results as above:
import { readFile } from 'node:fs/promises';
let job = await ev.bulk.create({ file: await readFile('customers.csv') }, { column: 'email', hasHeader: true });
job = await ev.bulk.wait(job.id);
console.log(job.status);wait() returns when the job is completed, failed, cancelled or expired, or when it is still ready with an error_code: it could not start, for example insufficient_credits, and will not continue on its own. Pass timeoutMs to give up earlier.
Also: ev.bulk.get(id), ev.bulk.start(id) for jobs created with start: false (once the job is ready, not while it is still analyzing; then wait()), and ev.bulk.cancel(id).
To save the results to a file on Node.js and resume after a failure, download into a partial file of that job and ask for the rest with a range (the SDK has no file-system helper, because it also runs in browsers and Workers). This writes <path>.<job id>.all-original-escaped.part (filter 'all', columns 'original', formulas escaped) and moves it onto path when it is complete: a file already at path is replaced only then, and left as it was if the call fails.
import {
chmodSync,
createWriteStream,
existsSync,
lstatSync,
realpathSync,
renameSync,
rmSync,
statSync,
} from 'node:fs';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import type { ReadableStream as NodeReadableStream } from 'node:stream/web';
import { EmailValidationError, InvalidRequestError } from '@email-validation/sdk';
async function download(jobId: string, path: string): Promise<number> {
// a symbolic link is followed (its target is replaced); a directory or other non-file is refused
const target = lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink() ? realpathSync(path) : path;
if (statSync(target, { throwIfNoEntry: false })?.isFile() === false) throw new Error(`Not a file: ${target}`);
const part = `${target}.${jobId}.all-original-escaped.part`; // this job's partial file, never `target` itself
let size = existsSync(part) ? statSync(part).size : 0;
let res: Response | undefined;
try {
res = await ev.bulk.results(jobId, size > 0 ? { range: `bytes=${size}-` } : {});
} catch (err) {
if (!(err instanceof InvalidRequestError) || size === 0) throw err;
if (err.status === 200) {
// the API cannot send this file in parts: download it whole, from byte 0
size = 0;
res = await ev.bulk.results(jobId);
} else if (err.status === 416) {
// nothing after `size` bytes: the part is complete only if the results file is exactly that long
const first = await ev.bulk.results(jobId, { range: 'bytes=0-0' });
await first.body?.cancel();
if (first.headers.get('content-range') !== `bytes 0-0/${size}`) {
rmSync(part); // longer than the results file, so not a part of it
throw err;
}
} else throw err;
}
if (res) {
const mismatch = () =>
new EmailValidationError('The partial download does not match the result file.', {
status: res.status,
code: 'unexpected_response',
});
const m = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(res.headers.get('content-range') ?? '');
const [start, last, total] = [Number(m?.[1]), Number(m?.[2]), Number(m?.[3])]; // NaN when absent
if (size > 0 && !(start === size && last >= start && total > last)) {
await res.body?.cancel();
throw mismatch(); // the part is left as it was
}
const body = Readable.fromWeb(res.body as NodeReadableStream<Uint8Array>);
await pipeline(body, createWriteStream(part, { flags: size > 0 ? 'a' : 'w' }));
if (size > 0 && statSync(part).size !== total) throw mismatch();
}
const mode = statSync(target, { throwIfNoEntry: false })?.mode;
if (mode !== undefined) chmodSync(part, mode & 0o7777); // the file keeps its permissions
renameSync(part, target); // replaces the file only now, in one step
return statSync(target).size;
}Called again after a failure, it continues only that job's own partial file and checks that the answer starts where that file ends; it never reads or appends to the file at path, so the same path can be reused for every job. Run one download per destination at a time. A symbolic link at path is followed (its target is replaced) and the file keeps its permissions; a directory or other non-file at path throws before any request. If a resume throws EmailValidationError (unexpected_response), delete the part file to start over. Leftover *.part files of other jobs or options beside the destination can be deleted.
Verify webhooks
import { verifyWebhook, WebhookVerificationError } from '@email-validation/sdk';
// In any fetch-style handler (a Request in, a Response out):
export default {
async fetch(request: Request, env: { EV_WEBHOOK_SECRET: string }) {
try {
const event = await verifyWebhook(await request.text(), request.headers, env.EV_WEBHOOK_SECRET);
if (event.type === 'bulk.completed') console.log('job done', event.data.job_id);
return new Response(null, { status: 204 });
} catch (err) {
if (err instanceof WebhookVerificationError) return new Response('invalid signature', { status: 400 });
throw err;
}
},
};verifyWebhook accepts the raw body as a string or bytes, and headers as a Headers object or a plain object such as Node's req.headers. event.type can also be webhook.test, sent when you press Send test in the dashboard: answer it with a 2xx like any other event. await signWebhook(id, timestamp, body, secret) (timestamp in Unix seconds) returns a valid webhook-signature value for local tests.
Constants
STATUSES, REASONS, REASONS_BY_STATUS, ACTIONS, ERROR_CODES, WEBHOOK_EVENTS and sandboxAddress(reason) mirror the API's vocabulary. See the statuses and reasons and test addresses pages.
Bring your own HTTP client
Pass fetch: with any function that has the signature of fetch, for example one that goes through a proxy, logs requests or answers from a fake in your tests:
import { EmailValidation } from '@email-validation/sdk';
const ev = new EmailValidation({
apiKey: process.env.EV_API_KEY!,
fetch: (input, init) => {
console.log(init?.method, String(input)); // never log init.headers: they hold the key
return fetch(input, init);
},
});It must pass the init it gets through unchanged, above all redirect: 'manual': redirects are never followed, and an answer that followed one is refused. It must never send a request again by itself (no retry wrapper or retrying proxy agent): the SDK retries reads itself, and a validation, bulk upload, start or cancel sent twice may be charged or applied twice. The SDK keeps its own timeouts and cancellation around your function.
The names and logos of other companies and projects belong to their owners; showing them here does not mean they endorse or partner with us.