Skip to content

Node.js SDK

Reference
For:
Developers

The HostRepute Node.js SDK, @hostrepute/sdk version 0.1.0, is a TypeScript client for the REST API v1 with ES module and CommonJS builds and no runtime dependencies. It needs Node.js 20.10 or later and uses the platform’s fetch. Version 0.1.0 manages domains and IPs, check profiles, alert channels and delivery hours well, but can’t read check results or metrics yet: read known problems in 0.1.0 before you build on it.

Install (when it's published)
npm install @hostrepute/sdk

new HostreputeClient(options) takes a team API token and optional settings. Create the token in Settings, then API tokens with the abilities your code needs; Authentication and API tokens explains them. The SDK doesn’t read environment variables itself: the examples on this page read the token from HOSTREPUTE_API_TOKEN.

index.ts
import { HostreputeClient } from '@hostrepute/sdk'
const client = new HostreputeClient({
token: process.env.HOSTREPUTE_API_TOKEN ?? '',
timeoutMs: 45_000,
userAgent: 'deploy-checks/1.4',
})
for await (const host of client.hosts.iterate({ perPage: 100 })) {
console.log(host.host, host.blocklistedAt !== null)
}

The constructor throws a TypeError for an empty token, a base URL that isn’t a URL, or an invalid timeout or retry setting.

Option Default What it does
token required The team API token, sent as Authorization: Bearer <token>.
baseUrl https://app.hostrepute.com The API’s address. Give the origin only: the SDK adds /api/v1/… to every path.
timeoutMs 30000 One time limit for the whole call, including retries and the waits between them.
userAgent hostrepute-node/0.1.0 node/<version> The User-Agent header.
retry { maxAttempts: 3, baseDelayMs: 200, maxDelayMs: 5000 } The retry policy. See retries.
fetch globalThis.fetch Your own fetch-compatible function, for proxies or instrumentation.
defaultHeaders {} Extra headers on every request. They are applied last, so they also replace Accept, Authorization or User-Agent if you name them.

Every method also accepts an AbortSignal (signal) to cancel it; a cancelled call rejects with the signal’s AbortError.

The client has one property per API resource. The names follow the API, not the portal:

In HostRepute Property Methods API
Domains and IPs client.hosts list, iterate, get, create, update, delete /api/v1/hosts
Blocklists client.dataSources list, iterate, get /api/v1/data-sources
Check profiles client.monitoringProfiles list, iterate, get, create, update, delete /api/v1/data-source-groups
Alert channels client.alerts list, iterate, get, create, update, delete /api/v1/alerts
Delivery hours client.contactGroups list, iterate, get, create, update, delete /api/v1/alert-groups
Blocklist checks client.blacklist check, status, checkAndWait, waitFor /api/v1/blacklist
Certificate checks client.certificates check, status, checkAndWait, waitFor /api/v1/certificates
Email authentication checks client.deliverability check, status, checkAndWait, waitFor /api/v1/deliverability
Prometheus metrics client.metrics get /api/v1/metrics
  • list({ page, perPage }) returns one page with data, meta, links, currentPage, lastPage, perPage, total and hasNextPage. perPage is 1–100; the API sends 15 when you leave it out. iterate() is an async iterator over every page, 50 items per request unless you set perPage. Read Pagination.
  • get, update and delete take the uuid, except dataSources.get, which takes the blocklist’s numeric id.
  • update sends PUT with the fields you set, and throws a TypeError when you set none.
  • The SDK has no method for sending a test alert. Call POST /api/v1/alerts/{alert}/test directly.

Every domain or IP needs a check profile. The SDK calls it monitoringProfileUuid and sends it as data_source_group_uuid:

Add a domain with the default check profile
const profiles = await client.monitoringProfiles.list()
const profile = profiles.data.find((p) => p.isDefault)
if (!profile) throw new Error('No default check profile')
const host = await client.hosts.create({
name: 'Mail',
host: 'mail.example.com',
monitoringProfileUuid: profile.uuid,
})

Delivery hours are contactGroups in the SDK. schedule is a plain object that the SDK sends unchanged, so give it the shape the API expects:

  • Keys mon, tue, wed, thu, fri, sat and sun, each with enabled, start and end. Times are HH:MM, and an enabled day must end after it starts.
  • A day you leave out gets no alerts. Leave schedule out entirely for delivery hours that are open at any time.
  • update leaves out null and undefined, so it can’t turn existing delivery hours back to any time. Send "schedule": null with the REST API instead.
  • The SDK’s README shows a days and hours shape: the API rejects it with 422.
Weekdays 08:00 to 18:00 in New York
const day = (enabled: boolean) => ({ enabled, start: '08:00', end: '18:00' })
const hours = await client.contactGroups.create({
name: 'Business hours',
timezone: 'America/New_York',
schedule: {
mon: day(true), tue: day(true), wed: day(true), thu: day(true), fri: day(true),
sat: day(false), sun: day(false),
},
})

An alert channel is alerts. settings holds the field the channel type needs (email here; Set up alert channels lists them all), and contactGroupUuids the delivery hours it follows:

An email alert channel that follows the delivery hours
import { AlertFrequency, AlertType } from '@hostrepute/sdk'
const channel = await client.alerts.create({
type: AlertType.Email,
frequency: AlertFrequency.OnceOnListedDelisted,
settings: { email: '[email protected]' },
contactGroupUuids: [hours.uuid],
})

For frequency, use AlertFrequency.OnceOnListedDelisted (Listed and removed in the portal) or AlertFrequency.OncePerCheckWhileListed (Only when listed). The SDK also defines AlertFrequency.Daily, which the API rejects with 422, and AlertFrequency.EveryCheck, a retired value that the API stores as once_on_listed_delisted.

Each check uses 1 credit (credit costs). check() starts a blocklist or certificate check and returns it with status pending; its uuid identifies the check:

Start a blocklist check
const scan = await client.blacklist.check({ host: 'mail.example.com' })
console.log(scan.uuid, scan.status)

certificates.check() also takes protocol, port and sni, and both take callbackUrl to be told when the check ends. A callback’s signature can’t be verified yet, so treat the callback as a notification and read the result from the status endpoint, as Receive webhooks explains. The SDK’s own webhook helpers don’t match what HostRepute sends, so don’t use them.

The SDK also has status(uuid), waitFor(uuid, options) and checkAndWait(input, options). The wait helpers poll status until the check is completed or failed, for up to timeoutMs (60 seconds by default) every pollIntervalMs (2 seconds), and then throw a TimeoutError with the scanUuid. In 0.1.0 they don’t work against the API (see below), so poll GET /api/v1/blacklist/status/{uuid} or GET /api/v1/certificates/status/{uuid} yourself, or use a callback, as Run checks and wait for results shows.

  • Status and wait helpers fail while a check runs. status(), waitFor() and checkAndWait() on blacklist and certificates throw DecodingError: Unknown scan status "processing" as soon as the API reports the check as running.
  • Results are missing. The blocklist and certificate check objects have no result and no counts (such as how many blocklists list the host), so even a completed check doesn’t tell you what it found.
  • Email authentication checks always throw. Every deliverability method throws a DecodingError on the API’s passed, warning, failed or skipped status, after the API has run the check and used the credit.
  • metrics.get() throws a DecodingError, because it reads the Prometheus text as JSON.
  • 402 has no typed error. Read err.body.required_credits and err.body.available_credits on the ApiError.

The SDK retries a failed request up to 3 attempts in total:

  • 429 is retried for every method. A 429 means the API refused the request before running it, so a retried check isn’t charged twice.
  • 5xx and network errors are retried only for GET, HEAD, OPTIONS, PUT and DELETE. A POST that creates something or starts a check isn’t retried, so the SDK never starts a check twice.
  • Waits. When the response has Retry-After (seconds or an HTTP date), the SDK waits that long. Otherwise it waits a random delay between zero and 200 ms × 2attempt − 1, capped at 5 seconds.
  • When the attempts run out, you get the error for the last response, for example a RateLimitError.
Five attempts with longer waits
const client = new HostreputeClient({
token: process.env.HOSTREPUTE_API_TOKEN ?? '',
retry: { maxAttempts: 5, baseDelayMs: 500, maxDelayMs: 10_000 },
})

retry: { maxAttempts: 1 } turns retries off. timeoutMs covers the retries too: when it runs out while the SDK waits to retry, the call rejects with the platform’s DOMException named TimeoutError, not an SDK error. Rate limits lists the limits behind 429.

All SDK errors extend HostreputeError. API errors extend ApiError, with statusCode, message, errors (field names to messages), body (the parsed response) and response.

Status or cause Class Extra fields
401 AuthenticationError
403 AuthorizationError
404 NotFoundError
422 ValidationError errors
429 RateLimitError retryAfterSeconds
5xx ServerError
Any other status, including 402 ApiError
No response NetworkError cause
A wait helper’s timeout TimeoutError scanUuid
A response the SDK can’t read DecodingError cause
Handle the errors a check can return
import { ApiError, RateLimitError, ValidationError } from '@hostrepute/sdk'
try {
await client.blacklist.check({ host: 'mail.example.com' })
} catch (err) {
if (err instanceof ValidationError) {
console.error(err.errors)
} else if (err instanceof RateLimitError) {
console.error(`Rate limited, retry in ${err.retryAfterSeconds} s`)
} else if (err instanceof ApiError && err.statusCode === 402) {
console.error(`Needs ${err.body.required_credits} credits, ${err.body.available_credits} left`)
} else {
throw err
}
}

Errors shows the response body behind each status.