Skip to content
RocketVerifierDOCS

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

@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.

Terminal
npm install @rocketverifier/sdk

Both ES module and CommonJS builds are included, with type definitions for each.

Node.js
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.

Node.js
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_...). With oauth, the client refreshes the access token automatically on a 401 invalid_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 0 falls back to the default.

  • maxRetriesnumberdefault 3

    Retries after the first attempt, on 429 responses and network errors. Set 0 to 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.

Node.js
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 fieldAPI fieldType
emailemailstring
statusstatus"deliverable" | "undeliverable" | "risky" | "unknown"
subStatussub_statusSubStatus, "none" when not specific
scorescorenumber, 0 to 100
reasonreasonstring
catchAllVerdictcatch_all_verdict"send_safe" | "send_with_caution" | "avoid" | null
didYouMeandid_you_meanstring | null
verifiedAtverified_atISO 8601 string | null
providerproviderstring | null
domain.namedomain.namestring
domain.acceptAlldomain.acceptAllboolean | null
domain.disposabledomain.disposableboolean
domain.freedomain.freeboolean
domain.acceptAllConfidencedomain.acceptAllConfidencenumber | null
domain.acceptAllVerdictdomain.acceptAllVerdictstring | null
account.roleaccount.roleboolean
account.disabledaccount.disabledboolean | null
account.fullMailboxaccount.fullMailboxboolean | null
dns.type, dns.recorddns.type, dns.recordstring, string | null
authenticationScoreauthentication_scorenumber
deliverabilityTierdeliverability_tierstring
toxic, abusetoxic, abuse"yes" | "no" | "unknown"
spamTrapspam_trapboolean
activityactivity{ verificationCount, activityScore, stabilityScore } | null
evidenceevidenceRecord<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.role and spamTrap become true for "yes" and false otherwise.
  • domain.acceptAll, account.disabled and account.fullMailbox become true, false or null when the server reports "unknown".
  • toxic and abuse keep the original string.
Node.js
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.

Node.js
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.

OptionDefaultWhat it does
pollInterval5000Milliseconds between status checks.
timeout300000Maximum wait in milliseconds. Past it, the call throws a RocketVerifierError with code timeout.
onProgressnoneCalled 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.

Node.js
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);
MethodReturnsNotes
results(jobId, { page, limit, classification })JobResultsPagelimit 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.

Node.js
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 });
  • filter keeps only deliverable, undeliverable, risky, unknown or send_safe rows. send_safe is deliverable plus high-scoring catch-all addresses.
  • includeOriginal joins upload jobs with your file's own columns, followed by rv_status, rv_sub_status, rv_score and the other rv_ columns.
  • With parse: true, is_valid, is_disposable, is_catch_all and is_role_based become booleans and confidence_score becomes a number. The exported parseDownloadCsv(text) does the same for CSV you already have.

Get, list and cancel jobs#

MethodReturns
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.

Node.js
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"
OptionTypeWhat it does
fileBuffer, Uint8Array, ArrayBuffer, Blob, File or a streamThe file content. Streams are read into memory before sending.
filenamestringName with extension. Required unless file is a File with a name.
contentTypestringMIME type. Defaults from the extension.
sourceUrlstringA public HTTPS URL the API fetches instead.
namestringJob name.
emailColumnstring | numberHeader name or 0-based index of the email column.
columnMappingRecord<string, string | number>For example { email: "Work Email" }. Overrides emailColumn.
previewbooleanStop in awaiting_confirmation with a free list health preview.
callbackUrlstringHTTPS URL that receives a signed POST when the job finishes.
idempotencyKeystringMakes 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.

Node.js
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 }. pending is true while the file is ingesting or the preview is being computed. Preview keys are camelCase, for example estimatedBounceRate, creditsNeeded, freeChecks and smtpSample.
  • 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 }.

Node.js
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).

Node.js
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.

Node.js
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);
MethodWhat 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.

Node.js
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.
MethodReturns
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.

Node.js
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 }) returns true or false.
  • constructWebhookEvent(rawBody, header, secret, options) returns the parsed event and throws a WebhookSignatureError whose reason is missing_secret, invalid_body, missing_header, malformed_header, timestamp_out_of_tolerance, signature_mismatch or invalid_json.
  • toleranceSec defaults to 300 seconds. During a secret rotation the header carries more than one v1 value, and any match passes.
  • Event payloads keep the API's snake_case keys. WEBHOOK_SIGNATURE_HEADER and WEBHOOK_EVENT_ID_HEADER export 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.

Node.js
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),
});
MemberWhat 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.

ClassThrown whencode
AuthenticationError401, or no credential passed to the constructor.unauthorized
InvalidTokenError401 invalid_token for an OAuth token that cannot be refreshed. Extends AuthenticationError.invalid_token
InsufficientCreditsError402.insufficient_credits
RateLimitError429 after all retries. retryAfter holds the seconds to wait.rate_limit_exceeded
ValidationError400, or input the SDK rejects before sending.validation_error
WebhookSignatureErrorconstructWebhookEvent cannot trust a delivery. reason says why.webhook_signature_invalid
OAuthErrorThe token, revoke or introspect endpoint returns an error. error holds the OAuth code.the OAuth error
RocketVerifierErrorEvery 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.

Node.js
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 maxRetries times. Each retry waits for the Retry-After seconds, or 60 seconds when the header is missing. See rate limits.
  • Network errors: retried up to maxRetries times, waiting 1, 2 and 3 seconds.
  • Timeouts: not retried. The call throws a RocketVerifierError with code timeout and status 408 once timeout milliseconds 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.

TypeScript
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