Libraries
Node.js SDK
In short
Install @rocketverifier/sdk, create a client with your API key and call rv.verify(email). The SDK covers every public endpoint, converts yes and no flags to booleans, retries rate limits with a stable Idempotency-Key and ships full TypeScript types.
On this page
- Install the SDK
- Create a client
- Verify an email
- Result fields
- Yes and no flags are booleans
- Verify a list in bulk
- Create a job
- Wait for a job
- Track progress
- Read results
- Download results
- Get, list and cancel jobs
- Upload a file
- Preview and confirm an upload
- Check a domain
- Read credits and account
- Manage monitors
- Manage webhook endpoints
- Verify webhook signatures
- Act for a user with OAuth
- How token refresh works
- Handle errors
- Retries and timeouts
- TypeScript types
- Next steps
- Frequently asked questions
@rocketverifier/sdk is the official Node.js and TypeScript library for the RocketVerifier API. It wraps every endpoint you need in production: real-time verification, bulk jobs from a list or a file, progress and downloads, webhooks, monitors, credits and RocketVerifier Connect OAuth.
- Package
- @rocketverifier/sdk
- Version
- 2.2.1
- Runtime
- Node.js 18+
- Dependencies
- None
Install the SDK#
Install from npm. The package has no runtime dependencies and uses the built-in fetch, FormData and node:crypto.
npm install @rocketverifier/sdkBoth ES module and CommonJS builds are included, with type definitions for each.
import RocketVerifier from "@rocketverifier/sdk";
// or: const { RocketVerifier } = require("@rocketverifier/sdk");Create a client#
Pass your API key as the first argument, or pass one options object. Read the key from ROCKETVERIFIER_API_KEY so it never lands in source control.
import RocketVerifier from "@rocketverifier/sdk";
const rv = new RocketVerifier(process.env.ROCKETVERIFIER_API_KEY);
// With options
const rv2 = new RocketVerifier(process.env.ROCKETVERIFIER_API_KEY, {
timeout: 15000,
maxRetries: 5,
});
// One options object
const rv3 = new RocketVerifier({ apiKey: process.env.ROCKETVERIFIER_API_KEY, baseUrl: "https://api.rocketverifier.com" });The constructor throws an AuthenticationError when neither an API key nor an access token is given. Live keys start with rv_live_; sandbox keys start with rv_test_ and accept only sandbox addresses.
Options
- apiKeystring
Your API key. Pass this or
accessToken. See authentication. - accessTokenstring
An OAuth access token (
rv_at_...) from RocketVerifier Connect. Calls run on the connected user's account and credits. - refreshTokenstring
An OAuth refresh token (
rv_rt_...). Withoauth, the client refreshes the access token automatically on a 401invalid_token. - oauthOAuth | OAuthClientOptions
The OAuth client used for automatic refresh.
- onTokenRefresh(tokens) => void | Promise<void>
Called with the new token set after an automatic refresh. Persist the new refresh token here.
- baseUrlstringdefault https://api.rocketverifier.com
API base URL.
- timeoutnumberdefault 30000
Request timeout in milliseconds, covering the full response body. A value of
0falls back to the default. - maxRetriesnumberdefault 3
Retries after the first attempt, on 429 responses and network errors. Set
0to turn retries off. - headersRecord<string, string>
Extra headers sent with every request. They are applied last, so they can override the defaults.
Verify an email#
rv.verify(email, idempotencyKey?) checks one address with POST /v1/verify and resolves to a typed VerificationResult. Branch on status and read subStatus for the reason.
const result = await rv.verify("deliverable@sandbox.rocketverifier.com");
switch (result.status) {
case "deliverable":
break; // send
case "risky":
console.log("Review:", result.subStatus, result.catchAllVerdict);
break;
case "undeliverable":
console.log("Remove. Suggestion:", result.didYouMean);
break;
case "unknown":
break; // free: check again later
}The SDK rejects input without an @ before sending a request (ValidationError). Pass your own idempotencyKey when you retry a call yourself; otherwise a random key is generated per call. The reading results guide explains every status and sub_status.
Result fields#
The SDK maps the snake_case API response to camelCase fields.
| SDK field | API field | Type |
|---|---|---|
email | email | string |
status | status | "deliverable" | "undeliverable" | "risky" | "unknown" |
subStatus | sub_status | SubStatus, "none" when not specific |
score | score | number, 0 to 100 |
reason | reason | string |
catchAllVerdict | catch_all_verdict | "send_safe" | "send_with_caution" | "avoid" | null |
didYouMean | did_you_mean | string | null |
verifiedAt | verified_at | ISO 8601 string | null |
provider | provider | string | null |
domain.name | domain.name | string |
domain.acceptAll | domain.acceptAll | boolean | null |
domain.disposable | domain.disposable | boolean |
domain.free | domain.free | boolean |
domain.acceptAllConfidence | domain.acceptAllConfidence | number | null |
domain.acceptAllVerdict | domain.acceptAllVerdict | string | null |
account.role | account.role | boolean |
account.disabled | account.disabled | boolean | null |
account.fullMailbox | account.fullMailbox | boolean | null |
dns.type, dns.record | dns.type, dns.record | string, string | null |
authenticationScore | authentication_score | number |
deliverabilityTier | deliverability_tier | string |
toxic, abuse | toxic, abuse | "yes" | "no" | "unknown" |
spamTrap | spam_trap | boolean |
activity | activity | { verificationCount, activityScore, stabilityScore } | null |
evidence | evidence | Record<string, unknown> | null |
Yes and no flags are booleans#
The API sends flags as the strings "yes", "no" and "unknown". The SDK converts them so you can test them directly.
domain.disposable,domain.free,account.roleandspamTrapbecometruefor"yes"andfalseotherwise.domain.acceptAll,account.disabledandaccount.fullMailboxbecometrue,falseornullwhen the server reports"unknown".toxicandabusekeep the original string.
if (result.domain.disposable || result.account?.role) {
// flag the signup
}Verify a list in bulk#
rv.batch runs bulk jobs of up to 100,000 unique addresses. Create a job, wait for it with a progress callback, then read or download the results. The batch API reference covers the endpoints.
const job = await rv.batch.create({
name: "October signups",
emails: ["deliverable@sandbox.rocketverifier.com", "undeliverable@sandbox.rocketverifier.com"],
});
const done = await rv.batch.wait(job.id, {
pollInterval: 3000,
onProgress: (j) => console.log(`${j.processedEmails}/${j.totalEmails} (${j.progressPercent}%)`),
});
const rows = await rv.batch.download(done.id, { parse: true, filter: "send_safe" });Create a job#
batch.create({ emails, name?, idempotencyKey? }) resolves to { id, jobId, totalEmails, estimatedTimeSeconds, creditsToUse, creditsRemaining }. The API counts unique addresses, so the SDK throws a ValidationError only when the de-duplicated list is larger than 100,000 (MAX_BULK_EMAILS). To get a callback when the job finishes, register a webhook for job.completed.
Wait for a job#
batch.wait(jobId, options?) polls the job until it is completed, failed or cancelled, and resolves to the final BatchJob. It also returns when a previewed upload reaches awaiting_confirmation.
| Option | Default | What it does |
|---|---|---|
pollInterval | 5000 | Milliseconds between status checks. |
timeout | 300000 | Maximum wait in milliseconds. Past it, the call throws a RocketVerifierError with code timeout. |
onProgress | none | Called with every BatchJob snapshot. |
Track progress#
batch.progress(jobId) reads the cheap progress endpoint and resolves to a JobProgress: status, total, processed, remaining, percent, counts (valid, invalid, risky, catchAll, disposable, unknown), countsByStatus (deliverable, undeliverable, risky, unknown), ratePerMinute, etaSeconds and timestamps. Use it for dashboards and progress bars.
Read results#
Results come back one page at a time, or through an async iterator that fetches pages as you go.
const page = await rv.batch.results(jobId, { page: 1, limit: 500, classification: "valid" });
console.log(page.total, page.hasMore);
for await (const r of rv.batch.iterateResults(jobId)) {
console.log(r.email, r.classification, r.subStatus, r.confidenceScore);
}
const all = await rv.batch.allResults(jobId);| Method | Returns | Notes |
|---|---|---|
results(jobId, { page, limit, classification }) | JobResultsPage | limit defaults to 100, up to 1000. |
iterateResults(jobId, { limit, classification, startPage }) | AsyncGenerator<JobResult> | Pages of 1000 by default. |
allResults(jobId, { limit, classification }) | JobResult[] | Every row in one array. |
Each JobResult has email, classification, isValid, isDisposable, isCatchAll, confidenceScore, subStatus and verifiedAt.
Download results#
batch.download(jobId, options?) fetches the full results file of a completed job. The return type follows the options you pass.
const csv = await rv.batch.download(jobId); // CSV text
const rows = await rv.batch.download(jobId, { parse: true }); // typed rows
const json = await rv.batch.download(jobId, { format: "json" }); // { job_id, results }
const safe = await rv.batch.download(jobId, { filter: "send_safe", parse: true });
const joined = await rv.batch.download(jobId, { includeOriginal: true });filterkeeps onlydeliverable,undeliverable,risky,unknownorsend_saferows.send_safeis deliverable plus high-scoring catch-all addresses.includeOriginaljoins upload jobs with your file's own columns, followed byrv_status,rv_sub_status,rv_scoreand the otherrv_columns.- With
parse: true,is_valid,is_disposable,is_catch_allandis_role_basedbecome booleans andconfidence_scorebecomes a number. The exportedparseDownloadCsv(text)does the same for CSV you already have.
Get, list and cancel jobs#
| Method | Returns |
|---|---|
batch.get(jobId) | BatchJob with counts, progressPercent and timestamps. |
batch.list(limit = 10, page = 1) | BatchJob[], newest first. |
batch.listPage({ page, limit, status }) | { jobs, total, page, limit, hasMore }. limit defaults to 20, up to 100. |
batch.delete(jobId), batch.cancel(jobId) | { success, jobId, refundedCredits, message }. Unprocessed addresses are refunded. |
Upload a file#
batch.upload(options) creates a job from a CSV, TSV, TXT or XLSX file of up to 50 MB, or from a public HTTPS URL. Pass exactly one of file or sourceUrl. See bulk upload for limits and column detection.
import fs from "node:fs";
const upload = await rv.batch.upload({
file: fs.createReadStream("contacts.csv"),
filename: "contacts.csv",
emailColumn: "Work Email",
preview: true,
});
console.log(upload.jobId, upload.status); // "ingesting"| Option | Type | What it does |
|---|---|---|
file | Buffer, Uint8Array, ArrayBuffer, Blob, File or a stream | The file content. Streams are read into memory before sending. |
filename | string | Name with extension. Required unless file is a File with a name. |
contentType | string | MIME type. Defaults from the extension. |
sourceUrl | string | A public HTTPS URL the API fetches instead. |
name | string | Job name. |
emailColumn | string | number | Header name or 0-based index of the email column. |
columnMapping | Record<string, string | number> | For example { email: "Work Email" }. Overrides emailColumn. |
preview | boolean | Stop in awaiting_confirmation with a free list health preview. |
callbackUrl | string | HTTPS URL that receives a signed POST when the job finishes. |
idempotencyKey | string | Makes your own retries safe. |
The result is { id, jobId, status, preview, statusUrl, progressUrl, callbackSecret? }. callbackSecret is returned once, only when you set callbackUrl.
Preview and confirm an upload#
With preview: true, the job waits in awaiting_confirmation with a free estimate of the list's health. Read it with batch.preview, then charge and start the job with batch.confirm.
let res = await rv.batch.preview(upload.jobId);
while (res.pending) {
await new Promise((r) => setTimeout(r, 2000));
res = await rv.batch.preview(upload.jobId);
}
console.log(res.preview.estimatedBounceRate, res.preview.creditsNeeded);
const confirmed = await rv.batch.confirm(upload.jobId);
console.log(confirmed.creditsCharged, confirmed.creditsRemaining);batch.preview(jobId, { refresh })resolves to{ jobId, status, preview, pending }.pendingistruewhile the file is ingesting or the preview is being computed. Preview keys are camelCase, for exampleestimatedBounceRate,creditsNeeded,freeChecksandsmtpSample.batch.confirm(jobId, idempotencyKey?)resolves to{ jobId, status, creditsCharged, creditsRemaining }. A job is never charged twice, so it is safe to retry.
Check a domain#
rv.domain.check(domain) combines the MX lookup and disposable check tools into one call and resolves to { domain, mxRecords, provider, disposable, hasValidMx }.
const info = await rv.domain.check("northwind.io");
console.log(info.hasValidMx, info.mxRecords[0]?.host);Read credits and account#
rv.getCredits() resolves to { credits, usedToday, usedThisMonth }. rv.getMe() returns the account behind the credential with GET /v1/me: email, name, accountType, organization, credits, authType, scopes and app (the OAuth app, or null for API keys).
const { credits } = await rv.getCredits();
const me = await rv.getMe();
console.log(`Connected as ${me.email}, ${credits} credits`);Manage monitors#
rv.monitors schedules list health re-verification (list_health) and SPF, DKIM and DMARC checks (domain_auth). Monitors need the monitors:read and monitors:write scopes. See the monitors API.
const monitor = await rv.monitors.create({
name: "Newsletter list",
type: "list_health",
emails: ["maya@northwind.io", "deliverable@sandbox.rocketverifier.com"],
frequency: "weekly",
alertThreshold: 5,
});
const runs = await rv.monitors.runs(monitor.id, 1, 20);| Method | What it does |
|---|---|
create({ name, type, frequency, domain, emails, alertThreshold, idempotencyKey }) | frequency defaults to weekly, alertThreshold to 5. domain_auth needs domain; list_health needs emails (up to 5,000). |
list(), get(id) | Return Monitor objects. |
update(id, { name, frequency, isActive, alertThreshold, domain, emails }) | Changes only the fields you pass. |
delete(id) | Removes the monitor. |
runs(id, page = 1, limit = 20) | { runs, total, page, limit, hasMore }, most recent first. |
runNow(id, idempotencyKey?) | Runs it immediately. list_health runs cost 1 credit per address. |
Manage webhook endpoints#
rv.webhooks registers HTTPS endpoints that receive signed events such as job.completed. It needs the webhooks:manage scope. The webhooks API lists every event and payload.
const hook = await rv.webhooks.create({
url: "https://northwind.io/hooks/rocketverifier",
events: ["job.completed", "job.failed", "credits.low"],
});
// Store hook.secret now: it is shown only once.| Method | Returns |
|---|---|
listEvents() | { name, description }[] for every event you can subscribe to. |
list(), get(id) | Webhook with isActive, successCount, failureCount and delivery timestamps. |
create({ url, name, events, idempotencyKey }) | Webhook plus secret, signatureHeader and verificationInstructions. Events default to job.completed and job.failed. |
update(id, { name, url, events, isActive }) | The updated Webhook. |
delete(id) | { success, message }. |
test(id) | { success, message, statusCode, responseTimeMs } after a test delivery. |
logs(id, { page, limit, status }) | Delivery attempts, newest first. limit defaults to 50, up to 100. |
rotateSecret(id) | { success, message, secret } with the new secret. |
Verify webhook signatures#
Every delivery carries X-RocketVerifier-Signature: t=<unix>,v1=<hex>, an HMAC-SHA256 of the timestamp and the raw body. constructWebhookEvent checks the signature and the timestamp, then returns the typed event.
import express from "express";
import { constructWebhookEvent, WebhookSignatureError } from "@rocketverifier/sdk";
const app = express();
app.post("/hooks/rocketverifier", express.raw({ type: "application/json" }), (req, res) => {
let event;
try {
event = constructWebhookEvent(
req.body, // raw Buffer, not parsed JSON
req.headers["x-rocketverifier-signature"],
process.env.ROCKETVERIFIER_WEBHOOK_SECRET
);
} catch (err) {
if (err instanceof WebhookSignatureError) return res.status(400).send(err.reason);
throw err;
}
if (event.event === "job.completed") {
console.log("Job done:", event.data.job_id, event.data.valid_count);
}
res.sendStatus(200);
});verifyWebhookSignature(rawBody, header, secret, { toleranceSec, now })returnstrueorfalse.constructWebhookEvent(rawBody, header, secret, options)returns the parsed event and throws aWebhookSignatureErrorwhosereasonismissing_secret,invalid_body,missing_header,malformed_header,timestamp_out_of_tolerance,signature_mismatchorinvalid_json.toleranceSecdefaults to 300 seconds. During a secret rotation the header carries more than onev1value, and any match passes.- Event payloads keep the API's snake_case keys.
WEBHOOK_SIGNATURE_HEADERandWEBHOOK_EVENT_ID_HEADERexport the header names.
Act for a user with OAuth#
The OAuth class runs the RocketVerifier Connect authorization code flow with PKCE, so your app can verify on another user's account and credits. The OAuth guide covers app registration; the OAuth quickstart walks through a full app.
import RocketVerifier, { OAuth } from "@rocketverifier/sdk";
const oauth = new OAuth({
clientId: process.env.RV_CLIENT_ID,
clientSecret: process.env.RV_CLIENT_SECRET,
redirectUri: "https://northwind.io/rocketverifier/callback",
});
// 1. Send the user to the consent screen
const { url, state, codeVerifier } = oauth.getAuthorizeUrl({ scopes: ["verify:bulk", "account:read"] });
// store state and codeVerifier in the session, then redirect to url
// 2. On the callback, after checking state
const tokens = await oauth.exchangeCode({ code: req.query.code, codeVerifier });
// 3. Call the API for that user, with automatic refresh
const userRv = new RocketVerifier({
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
oauth,
onTokenRefresh: async (t) => saveTokens(userId, t),
});| Member | What it does |
|---|---|
new OAuth({ clientId, clientSecret, redirectUri, issuer, tokenEndpointAuthMethod }) | Omit clientSecret for public clients. issuer defaults to https://app.rocketverifier.com; tokenEndpointAuthMethod to client_secret_basic. |
getAuthorizeUrl({ scopes, redirectUri, state, codeVerifier, resource, prompt }) | Returns { url, state, codeVerifier }. state and the PKCE verifier are generated when omitted. |
exchangeCode({ code, codeVerifier, redirectUri }) | Returns an OAuthTokenSet. Codes are single use and expire after 60 seconds. |
refresh(refreshToken) | Returns a new token set. The refresh token rotates on every use. |
revoke(token, tokenTypeHint?) | Revokes a token. Revoking a refresh token ends the connection. |
introspect(token) | Returns { active, scope, clientId, tokenType, exp, ... }. |
An OAuthTokenSet holds accessToken, refreshToken, tokenType, expiresIn (seconds), expiresAt (Unix milliseconds) and scopes.
How token refresh works#
When the API answers 401 invalid_token and the client has both refreshToken and oauth, it refreshes once, retries the call and passes the new tokens to onTokenRefresh. Concurrent calls share a single refresh, because refresh tokens are single use. Without refresh configured, the call throws an InvalidTokenError. If the refresh token itself is rejected, oauth.refresh throws an OAuthError with error === "invalid_grant": send the user through Connect again.
Use rv.setTokens({ accessToken, refreshToken }) to swap in tokens you refreshed elsewhere. OAUTH_SCOPES, generatePkcePair() and pkceChallenge() are exported for custom flows.
Handle errors#
Every error extends RocketVerifierError, which carries message, code, statusCode and details. Catch the subclasses you act on and fall back to the base class.
| Class | Thrown when | code |
|---|---|---|
AuthenticationError | 401, or no credential passed to the constructor. | unauthorized |
InvalidTokenError | 401 invalid_token for an OAuth token that cannot be refreshed. Extends AuthenticationError. | invalid_token |
InsufficientCreditsError | 402. | insufficient_credits |
RateLimitError | 429 after all retries. retryAfter holds the seconds to wait. | rate_limit_exceeded |
ValidationError | 400, or input the SDK rejects before sending. | validation_error |
WebhookSignatureError | constructWebhookEvent cannot trust a delivery. reason says why. | webhook_signature_invalid |
OAuthError | The token, revoke or introspect endpoint returns an error. error holds the OAuth code. | the OAuth error |
RocketVerifierError | Every other status, including 403, 404 and 422, plus timeouts and network failures. | the API's error.code, timeout or network_error |
A zero balance is refused with a 403 before any check runs, so test err.code === "insufficient_credits" to catch both the 402 and the 403 case.
import { RocketVerifierError, RateLimitError } from "@rocketverifier/sdk";
try {
await rv.verify("maya@northwind.io");
} catch (err) {
if (err instanceof RateLimitError) {
console.log(`Slow down for ${err.retryAfter}s`);
} else if (err instanceof RocketVerifierError && err.code === "insufficient_credits") {
console.log("Top up credits");
} else {
throw err;
}
}The errors reference lists every API error code.
Retries and timeouts#
The client retries only what is safe and useful to retry, and never charges twice for a retried call.
- Rate limits (429): retried up to
maxRetriestimes. Each retry waits for theRetry-Afterseconds, or 60 seconds when the header is missing. See rate limits. - Network errors: retried up to
maxRetriestimes, waiting 1, 2 and 3 seconds. - Timeouts: not retried. The call throws a
RocketVerifierErrorwith codetimeoutand status 408 oncetimeoutmilliseconds pass. - Other errors: 4xx and 5xx responses are thrown straight away.
- Idempotency: every POST, PUT and PATCH sends an
Idempotency-Key, generated per call and reused on every retry of that call.
Set maxRetries: 0 to handle every retry yourself.
TypeScript types#
The package is written in TypeScript and exports a type for every request and response. subStatus is typed as SubStatus with a string fallback, so every value the API returns compiles.
import RocketVerifier, {
type VerificationResult,
type VerificationStatus,
type SubStatus,
type BatchJob,
type JobProgress,
type WebhookEvent,
MAX_BULK_EMAILS,
SDK_VERSION,
} from "@rocketverifier/sdk";
function canSend(r: VerificationResult): boolean {
return r.status === "deliverable" || r.catchAllVerdict === "send_safe";
}Other exports include CatchAllVerdict, BatchJobStatus, JobResult, BatchDownloadRow, BulkPreview, Monitor, Webhook, WebhookEventType, OAuthTokenSet, OAuthScope, AccountProfile, CreditBalance, MAX_UPLOAD_BYTES, UPLOAD_EXTENSIONS, USER_AGENT, parseCsv and parseDownloadCsv.
Next steps#
Frequently asked questions
Does the Node.js SDK work with CommonJS and ES modules?
Yes. The package ships both builds. Use import RocketVerifier from "@rocketverifier/sdk" or const { RocketVerifier } = require("@rocketverifier/sdk").
Which errors does the SDK retry?
Rate limits (429) and network errors, up to maxRetries times (3 by default). A 429 waits for the Retry-After seconds. Timeouts and 5xx responses are thrown straight away.
Can a retry charge me twice?
No. Every POST and PATCH carries an Idempotency-Key that the SDK reuses across its own retries, so the API returns the original result instead of charging again.
Why is result.domain.disposable a boolean when the API returns a string?
The SDK converts the API's "yes", "no" and "unknown" strings for you. Flags that can be unknown, such as domain.acceptAll, become true, false or null.
Updated 11 November 2026Suggest an edit