Skip to main content

Node.js SDK

@thumbmarkjs/management is the official Node.js SDK for the Management API. It is written in TypeScript, has no runtime dependencies, and ships ESM and CommonJS builds together with type definitions. This page applies to @thumbmarkjs/management 0.2.x.

Server-side only

The SDK authenticates with a management secret. Run it in Node.js on your server or in CI/CD. Never bundle it into browser code, and never hard-code the secret in your source.

Install and requirements​

npm install @thumbmarkjs/management

The SDK needs Node.js 18 or later, because it uses the built-in fetch.

Authenticate​

Create a client with your management secret. The SDK does not read environment variables by itself, so pass the secret in:

import { createManagementClient } from '@thumbmarkjs/management';

const client = createManagementClient({
apiKey: process.env.THUMBMARK_MANAGEMENT_SECRET,
});

apiKey is required, and it is your management secret, not your public ThumbmarkJS API key. It is sent as Authorization: Bearer <apiKey>. If it is empty or does not start with tmsec_, createManagementClient throws a ConfigurationError immediately, before any network call.

Create the secret in the console and keep it in an environment variable or a secret manager. See Management secrets. The secret needs the allowed-hostnames:manage scope for the operations below.

The client always exposes client.allowedHostnames, client.requests and client.visitors. Calls to requests and visitors only work on accounts with request history enabled, otherwise they throw a RequestHistoryNotEnabledError. See Request history.

Work with allowed hostnames​

The examples are ES modules. Save them as .mjs files, or set "type": "module" in your package.json, so that top-level await works.

quickstart.mjs
import { createManagementClient } from '@thumbmarkjs/management';

const client = createManagementClient({
apiKey: process.env.THUMBMARK_MANAGEMENT_SECRET,
});

// Add a hostname. Adding one that is already on the list is not an error.
const { status } = await client.allowedHostnames.add('app.example.com');
console.log(status === 201 ? 'Added app.example.com' : 'app.example.com was already allowed');

// Read the first page of the list.
const { items, nextCursor } = await client.allowedHostnames.list();
console.log('First page:', items, nextCursor ? '(more pages)' : '(last page)');

// Remove it again.
await client.allowedHostnames.remove('app.example.com');
console.log('Removed app.example.com');

List hostnames​

list({ cursor }) returns { items, nextCursor }. items is an array of hostname strings. nextCursor is absent on the last page. The SDK does not paginate for you, so follow nextCursor until it is gone:

paginate.mjs
import { createManagementClient } from '@thumbmarkjs/management';

const client = createManagementClient({
apiKey: process.env.THUMBMARK_MANAGEMENT_SECRET,
});

// Collect every allowed hostname by following nextCursor until it is absent.
const hostnames = [];
let cursor;
do {
const page = await client.allowedHostnames.list({ cursor });
hostnames.push(...page.items);
cursor = page.nextCursor;
} while (cursor);

console.log(`${hostnames.length} allowed hostnames:`, hostnames);

Add a hostname​

add(hostname) resolves to { status }. The status is 201 if the hostname was added and 204 if it was already on the list, so calling it twice is safe. An invalid hostname, or one that would exceed the account's hostname limit, throws a ValidationError. See Hostname rules.

Remove a hostname​

remove(hostname) resolves to { status: 204 }. If the hostname is not on the list, it throws a NotFoundError. Pass { idempotent: true } to treat a missing hostname as success, in which case it also resolves to { status: 204 }:

await client.allowedHostnames.remove('old.example.com', { idempotent: true });

Recipe: allow a preview environment from CI​

This script adds a hostname when a preview environment is created and removes it when the environment is torn down. Both actions are safe to run twice.

preview-env.mjs
import { createManagementClient } from '@thumbmarkjs/management';

const client = createManagementClient({
apiKey: process.env.THUMBMARK_MANAGEMENT_SECRET,
});

// The action is "add" when a preview environment is created and "remove" when it is torn down.
const [action, hostname] = process.argv.slice(2);

if (action === 'add') {
await client.allowedHostnames.add(hostname);
} else if (action === 'remove') {
// idempotent: true so that tearing down twice (or a never-added host) does not fail the job
await client.allowedHostnames.remove(hostname, { idempotent: true });
} else {
throw new Error('Usage: node preview-env.mjs <add|remove> <hostname>');
}
console.log(`${action} ${hostname}: done`);

Store the management secret in your CI system's secret store and expose it to this step as THUMBMARK_MANAGEMENT_SECRET.

Configuration​

createManagementClient accepts these options:

OptionTypeDefaultDescription
apiKeystringrequiredYour management secret (tmsec_live_...).
baseUrlstringhttps://admin-api.thumbmarkjs.comAPI base URL. You normally do not need to set this.
fetchtypeof fetchglobal fetchA fetch-compatible function, for example for tests or a proxy.
timeoutMsnumber10000Timeout for each attempt, in milliseconds.
retry{ maxRetries: number }{ maxRetries: 2 }How often a failed attempt is retried. 0 turns retries off.
config.mjs
import { createManagementClient } from '@thumbmarkjs/management';

const client = createManagementClient({
apiKey: process.env.THUMBMARK_MANAGEMENT_SECRET,
timeoutMs: 5_000, // per attempt; default 10_000
retry: { maxRetries: 3 }, // default 2; 0 turns retries off
});

const { items } = await client.allowedHostnames.list();
console.log('OK with custom timeout and retries:', items.length, 'hostnames on the first page');

Retries and timeouts​

Every attempt is aborted after timeoutMs (client.visitors.delete() uses at least 25 seconds per attempt, see Request history) and fails with a TimeoutError. With the default maxRetries of 2, the SDK makes up to 3 attempts in total.

The SDK retries when:

  • the request fails before a response arrives (a NetworkError),
  • an attempt times out (a TimeoutError),
  • the API answers with a 5xx status.

Retries wait with exponential backoff and jitter, starting at about 200 ms and capped at 2 seconds. The SDK retries only network errors, timeouts and 5xx responses. A retry never applies a change twice, but if the first attempt succeeded and its response was lost, add() can report 204 instead of 201, and remove() can throw a NotFoundError unless you pass { idempotent: true }.

Responses with 4xx statuses, including 429 Too Many Requests, are never retried, and the SDK does not read a Retry-After header for them. Handle those errors in your own code.

Errors​

Every error class is exported from the package. Errors that come from an HTTP response extend ManagementApiError and carry:

  • status: the HTTP status code,
  • code: the error code from the response body, or HTTP_<status> (for example HTTP_403) if the body has none,
  • body: the parsed response body, if there was one.
ClassWhen it is thrown
ManagementApiErrorBase class of all HTTP errors. Thrown as-is for statuses that have no more specific class, for example 409.
ValidationError400: the request was invalid, for example an invalid hostname or cursor.
AuthenticationError401 or 403: the secret is missing, invalid, revoked, or lacks the required scope. These cases look the same.
AuthorizationErrorExported but reserved. The SDK does not throw it today, so do not rely on it.
NotFoundError404: for example, removing a hostname that is not on the list.
ServerError5xx, after the retries are used up.
RequestHistoryNotEnabledError403 with code REQUEST_HISTORY_NOT_ENABLED: the secret is fine, but request history is not enabled for the account. See Request history.
VisitorDeletionIncompleteErrorvisitors.delete() could not confirm that the erasure finished. See Request history.
NetworkErrorThe request failed before any response, for example because of a DNS failure. The original error is in cause. It is not a ManagementApiError.
TimeoutErrorAn attempt exceeded timeoutMs. It has a timeoutMs property and is not a ManagementApiError.
ConfigurationErrorThe client options are invalid, for example a missing or malformed apiKey. It is not a ManagementApiError.

Check the specific classes before ManagementApiError, because they are all subclasses of it:

errors.mjs
import {
createManagementClient,
AuthenticationError,
ManagementApiError,
NetworkError,
NotFoundError,
TimeoutError,
ValidationError,
} from '@thumbmarkjs/management';

const client = createManagementClient({
apiKey: process.env.THUMBMARK_MANAGEMENT_SECRET,
});

async function addHostname(hostname) {
try {
await client.allowedHostnames.add(hostname);
console.log(`${hostname}: added`);
} catch (err) {
if (err instanceof ValidationError) {
// 400: the hostname is invalid, or the account is at its hostname limit.
console.error(`${hostname}: rejected (${err.message})`);
} else if (err instanceof AuthenticationError) {
// 401/403: missing, invalid or revoked secret, or the secret lacks the scope.
console.error('Check the management secret and its permissions');
} else if (err instanceof TimeoutError || err instanceof NetworkError) {
// The SDK already retried. Try again later.
console.error(`${hostname}: could not reach the API`);
} else if (err instanceof ManagementApiError) {
// Any other HTTP status, for example 409 (err.code is "HTTP_409" without a body code).
console.error(`${hostname}: HTTP ${err.status} (${err.code})`);
} else {
throw err;
}
}
}

async function removeHostname(hostname) {
try {
await client.allowedHostnames.remove(hostname);
} catch (err) {
if (err instanceof NotFoundError) {
console.log(`${hostname}: was not on the list`);
} else {
throw err;
}
}
}

await addHostname('good.example.com');
await removeHostname('missing.example.com');
// remove() with idempotent: true treats "already gone" as success.
const { status } = await client.allowedHostnames.remove('missing.example.com', { idempotent: true });
console.log('idempotent remove status:', status);

CommonJS and TypeScript​

The package also works with require. CommonJS has no top-level await, so wrap the calls in an async function:

commonjs.cjs
const { createManagementClient } = require('@thumbmarkjs/management');

async function main() {
const client = createManagementClient({
apiKey: process.env.THUMBMARK_MANAGEMENT_SECRET,
});
const { items } = await client.allowedHostnames.list();
console.log('CommonJS OK:', items);
}

main().catch((err) => {
console.error(err);
process.exit(1);
});

The types are bundled. process.env values have the type string | undefined, so check the secret before you pass it in:

typed.mts
import {
createManagementClient,
type ListResult,
type WriteResult,
} from '@thumbmarkjs/management';

const apiKey = process.env.THUMBMARK_MANAGEMENT_SECRET;
if (!apiKey) {
throw new Error('Set THUMBMARK_MANAGEMENT_SECRET');
}

const client = createManagementClient({ apiKey });

async function listAll(): Promise<string[]> {
const all: string[] = [];
let cursor: string | undefined;
do {
const page: ListResult = await client.allowedHostnames.list({ cursor });
all.push(...page.items);
cursor = page.nextCursor;
} while (cursor);
return all;
}

const result: WriteResult = await client.allowedHostnames.add('typed.example.com');
console.log('typed add status:', result.status, '| total:', (await listAll()).length);

Next steps​