Node.js SDK
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
Section titled “Install”npm install @hostrepute/sdkCreate a client
Section titled “Create a client”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.
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.
Resources
Section titled “Resources”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 withdata,meta,links,currentPage,lastPage,perPage,totalandhasNextPage.perPageis 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 setperPage. Read Pagination.get,updateanddeletetake theuuid, exceptdataSources.get, which takes the blocklist’s numericid.updatesendsPUTwith the fields you set, and throws aTypeErrorwhen you set none.- The SDK has no method for sending a test alert. Call
POST /api/v1/alerts/{alert}/testdirectly.
Add a domain or IP
Section titled “Add a domain or IP”Every domain or IP needs a check profile. The SDK calls it
monitoringProfileUuid and sends it as data_source_group_uuid:
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,})Set delivery hours and an alert channel
Section titled “Set delivery hours and an alert channel”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,satandsun, each withenabled,startandend. Times areHH:MM, and an enabled day must end after it starts. - A day you leave out gets no alerts. Leave
scheduleout entirely for delivery hours that are open at any time. updateleaves outnullandundefined, so it can’t turn existing delivery hours back to any time. Send"schedule": nullwith the REST API instead.- The SDK’s README shows a
daysandhoursshape: the API rejects it with422.
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:
import { AlertFrequency, AlertType } from '@hostrepute/sdk'
const channel = await client.alerts.create({ type: AlertType.Email, frequency: AlertFrequency.OnceOnListedDelisted, 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.
Run checks
Section titled “Run checks”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:
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.
Known problems in 0.1.0
Section titled “Known problems in 0.1.0”- Status and wait helpers fail while a check runs.
status(),waitFor()andcheckAndWait()onblacklistandcertificatesthrowDecodingError: 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
resultand no counts (such as how many blocklists list the host), so even acompletedcheck doesn’t tell you what it found. - Email authentication checks always throw. Every
deliverabilitymethod throws aDecodingErroron the API’spassed,warning,failedorskippedstatus, after the API has run the check and used the credit. metrics.get()throws aDecodingError, because it reads the Prometheus text as JSON.402has no typed error. Readerr.body.required_creditsanderr.body.available_creditson theApiError.
Retries
Section titled “Retries”The SDK retries a failed request up to 3 attempts in total:
429is retried for every method. A429means the API refused the request before running it, so a retried check isn’t charged twice.5xxand network errors are retried only forGET,HEAD,OPTIONS,PUTandDELETE. APOSTthat 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.
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.
Errors
Section titled “Errors”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 |
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.
Related
Section titled “Related”- Official SDKs compares the five SDKs.
- Make your first API call uses the REST API without an SDK.
- Run checks and wait for results explains polling, callbacks and credits.
- API token abilities lists what each ability allows.
- The API reference documents every operation.

