Code samples · JavaScript
JavaScript code samples
Copy-paste JavaScript 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.
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).
With the official SDK
The official JavaScript and TypeScript SDK does the retries, timeouts and error mapping for you; its sample is on the TypeScript code samples page. 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 below call the API directly.
Validate an address
JavaScript
const API = 'https://api.email-validation.org/v1/validate';
const MAX_WAIT_S = 10; // never wait out a long Retry-After (key_daily_cap lasts until the next UTC day)
async function validate(email, attempts = 3) {
for (let attempt = 1; ; attempt++) {
const res = await fetch(API, {
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 res.json();
const { error } = await res.json();
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);Read the credit balance
JavaScript
const res = await fetch('https://api.email-validation.org/v1/credits', {
headers: { Authorization: `Bearer ${process.env.EV_API_KEY}` },
});
const credits = await res.json();
if (!res.ok) throw new Error(`${credits.error.code}: ${credits.error.message}`);
console.log(`Balance: ${credits.balance}`);Create a bulk job
JavaScript
import { readFile } from 'node:fs/promises';
const csv = await readFile('customers.csv');
const res = await fetch('https://api.email-validation.org/v1/bulk?column=email&has_header=true', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.EV_API_KEY}`,
'Content-Type': 'text/csv',
},
body: csv,
});
const job = await res.json();
if (!res.ok) throw new Error(`${job.error.code}: ${job.error.message}`);
console.log(job.id, job.status);Verify a webhook
JavaScript
// Node.js (Express shown): use express.raw() so the body stays byte-for-byte as sent.
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';
function verifyWebhook(rawBody, headers, secret, toleranceSeconds = 300) {
const id = headers['webhook-id'];
const timestamp = headers['webhook-timestamp'];
const signatures = headers['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 key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const expected = createHmac('sha256', key).update(`${id}.${timestamp}.`).update(rawBody).digest();
for (const entry of signatures.split(' ')) {
const [version, sig] = entry.split(',');
if (version !== 'v1' || !sig) continue;
const given = Buffer.from(sig, 'base64');
if (given.length === expected.length && timingSafeEqual(given, expected)) return JSON.parse(rawBody);
}
throw new Error('No valid signature');
}
const app = express();
app.post('/webhooks/email-validation', express.raw({ type: 'application/json' }), (req, res) => {
let event;
try {
event = verifyWebhook(req.body, req.headers, process.env.EV_WEBHOOK_SECRET);
} catch {
return res.sendStatus(400);
}
// Deduplicate on req.headers['webhook-id'], then handle event.type.
res.sendStatus(204);
});Notes
- Use
POSTwith 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
200answer with the statusunknownis a normal, free result, not an error. - Every endpoint, field and error: the API reference.