Skip to content

REST

@lunibee/rest is Lunibee’s HTTP client for the Discord REST API. It has no runtime dependencies and handles:

  • per-bucket and global rate limits, shared across processes and bots through Redis with atomic reservations if you want (see Distributed REST);
  • safe retries and a bounded server-controlled backoff;
  • per-request timeouts and AbortSignal cancellation;
  • token-safe errors, hooks and logs;
  • multipart file uploads;
  • typed route builders (Routes) and a standalone WebhookClient.

A Client creates its own REST (client.rest), configured with ClientOptions.rest. You only build one yourself for scripts, workers without a Gateway, or tests.

import { REST, Routes, RESTError } from "lunibee";
// or the package on its own:
import { REST, Routes, RESTError } from "@lunibee/rest";

The examples below are TypeScript; the JavaScript is the same without the type arguments.

import { REST, Routes, type UserData, type APIMessage } from "lunibee";
const rest = new REST({ token: process.env.DISCORD_TOKEN! });
const me = await rest.get<UserData>(Routes.user());
const message = await rest.post<APIMessage>(Routes.channelMessages("123456789012345678"), {
content: `Hello from ${me.username} 🐝`,
});
new REST(options?: RESTOptions)
Option Type Default Description
token string — Bot token. Can be set later with setToken(). Requests without a token are sent without Authorization.
baseURL string https://discord.com/api/v10 Base URL, including the API version. See Base URL rules.
allowInsecureBaseURL boolean false Accept a cleartext http:// baseURL that is not on this machine, such as an internal REST proxy on a network you trust.
timeout number 15000 Timeout for each HTTP attempt, in ms (minimum 1).
retries number 2 Most retries for the default retry policy.
retryPolicy RetryPolicy createRetryPolicy(retries) Replaces the retry policy. See Retries.
maxBackoff number 600000 The longest a rate-limit header may make this client wait, in ms. See Bounded backoff.
concurrentBuckets boolean true Lets requests on a bucket whose limit is known run in parallel, up to its remaining allowance. Needs a store with reserve() (both built-in stores qualify when Redis has eval). Set false for strict one-at-a-time ordering per bucket.
store RateLimitStore MemoryRateLimitStore Where rate-limit state lives. RedisRateLimitStore shares it between processes.
hooks RESTHooks {} Lifecycle callbacks. See Hooks.
transport HttpTransport an HttpTransport from baseURL, allowInsecureBaseURL and timeout Replaces the HTTP stage, for example with a fake fetch in tests. When given, baseURL, allowInsecureBaseURL and timeout are ignored.
telemetry RESTTelemetry — Receives telemetry events. RESTMetrics is a ready-made aggregator.
maxQueued number unlimited Most requests waiting for a bucket slot, over all buckets. One more fails at once with a RESTError of kind "overloaded".
maxQueuedPerBucket number unlimited The same limit for the requests waiting on one bucket.
globalLimit number | false 50 Requests per second this bot may send across all buckets, enforced before Discord answers with a global 429 and shared through the store by every process. Set the limit Discord granted a large bot, or false to rely on 429s alone. Interaction callbacks do not count.
maxQueueWait number unlimited Longest, in ms, a request may wait before it is sent: queued behind its bucket, for a rate limit, or between retries. Past it the request fails with kind "overloaded". A request can set its own maxQueueWait in its options.
stopOnInvalidToken boolean true After a 401 on a bot route, refuse later requests with that token (kind "authentication", not sent) until setToken(). Repeated 401s count towards Discord’s invalid-request ban.

There is no apiVersion option: the version is part of baseURL.

const rest = new REST({
token: process.env.DISCORD_TOKEN!,
timeout: 10_000,
retries: 3,
maxBackoff: 60_000,
});
Member Description
setToken(token) Sets the token for later requests. Throws a TypeError for an empty token.
setHooks(hooks) Replaces every hook. setHooks({}) removes them. Returns this.
store The RateLimitStore in use (read-only).
diagnostics() { mode, queued, inFlight, buckets, closed, invalidRequests, tokenRejected }: how limits are enforced right now ("local", "distributed", "observational", "degraded-local" or "unavailable"), requests waiting for a slot, requests started and not settled, bucket keys holding a slot, whether close() was called, the 401/403/429 responses of the last ten minutes (shared-scope 429s excepted; Discord bans an IP for a while past 10,000), and whether the token was rejected.
close() Stops the client. New requests and requests still queued or waiting for a limit fail with kind "aborted"; attempts already sent finish. Resolves when nothing is in flight.

Every request method returns a promise of the decoded response: JSON as an object, other content as text, and undefined for 204 No Content. Pass the expected type as the type argument, for example rest.get<APIGuild>(…).

Paths are relative to baseURL, start with /, and are usually built with Routes.

const guild = await rest.get<APIGuild>(Routes.guild(guildId), {
query: { with_counts: true },
});

The body comes second and is always sent as the body; options (reason, query, headers, files, …) go third:

await rest.post(
Routes.channelMessages(channelId),
{ content: "Hello!" },
{ reason: "Greeting" },
);

With no body, pass undefined: rest.put(path, undefined, { reason: "x" }).

await rest.patch(Routes.channel(channelId), { name: "new-name" }, { reason: "Rename" });
await rest.put(Routes.guildBan(guildId, userId), { delete_message_seconds: 86_400 });
await rest.delete(Routes.message(channelId, messageId), { reason: "Spam" });

postWithFiles<T>(path, body, files, options?) and patchWithFiles<T>(…)

Section titled “postWithFiles<T>(path, body, files, options?) and patchWithFiles<T>(…)”

Send a multipart/form-data request: the body goes in the payload_json field and the files in files[0], files[1] and so on.

await rest.postWithFiles(
Routes.channelMessages(channelId),
{ content: "Here is your report", attachments: [{ id: 0, description: "CSV export" }] },
[{ name: "report.csv", data: csvBytes, contentType: "text/csv" }],
);

RESTFileAttachment:

Field Type Description
name string File name. CR, LF, " and \ are replaced with _, so a name cannot add headers to its part.
data Blob | Uint8Array | ArrayBuffer, or a promise of one Contents. A promise is awaited just before the request is sent.
contentType string MIME type. Default application/octet-stream.

Passing files in the options of any method does the same: rest.post(path, body, { files }).

Every helper above calls request(method, path, body?, options?):

await rest.request(
"POST",
Routes.channelMessages(channelId),
{ content: "hi" },
{ reason: "Test", query: new URLSearchParams({ wait: "true" }) },
);

RESTRequestOptions (and RequestData, which adds files, plus the body that get() and delete() take there):

Option Type Description
signal AbortSignal Cancels the request, including any wait for a rate limit. See Cancellation.
query URLSearchParams | Record<string, string | number | boolean | null | undefined> | string Query string. null and undefined values are skipped; a string may start with ? or not.
headers Record<string, string> Extra headers. The library’s own Authorization, User-Agent, X-Audit-Log-Reason and Content-Type win, however you spell the name.
reason string Audit-log reason, sent percent-encoded as X-Audit-Log-Reason.
auth boolean false sends the request without Authorization (for example to a webhook or interaction route). Default true.
body unknown RequestData only, for get() and delete(): the body. The other methods take theirs positionally.
files RESTFileAttachment[] RequestData only: switches the request to multipart.
Header When
Authorization: Bot <token> A token is set and auth is not false.
User-Agent: DiscordBot (https://github.com/Ekretos/lunibee, <version>) Always.
Content-Type: application/json JSON bodies. Multipart bodies let fetch set the boundary.
X-Audit-Log-Reason reason is set.

Before anything is sent, a path is refused with a TypeError if it:

  • does not start with /;
  • contains a control character (tab, CR, LF and the rest of U+0000–U+001F, U+007F), a space or #, which a URL parser would strip or treat as the end of the path;
  • has a . or .. segment, including percent-encoded forms such as %2e%2e and segments like %2f..%2f that decode to one;
  • contains a backslash;
  • has malformed percent-encoding.

Routes also checks every id it is given, so a value like ../../channels/1 can never change which endpoint receives your token. Redirects are refused too (fetch runs with redirect: "error").

Routes builds API paths. Every id is checked to be a snowflake (decimal, up to 20 digits) and a TypeError is thrown otherwise; invite codes and emoji are percent-encoded.

Routes.user() // "/users/@me"
Routes.userById(userId) // "/users/{user}"
Routes.channelMessages(channelId) // "/channels/{channel}/messages"
Routes.message(channelId, messageId) // "/channels/{channel}/messages/{message}"
Routes.guildMember(guildId, userId) // "/guilds/{guild}/members/{user}"
Routes.interactionCallback(id, token) // "/interactions/{id}/{token}/callback"
Area Builders
Users user(), userById(userId), userGuilds(), currentUserGuild(guildId)
Guilds guild, guildPreview, guildChannels, guildActiveThreads, guildAuditLog, guildPrune, guildVanity, guildWelcomeScreen, guildOnboarding, guildIntegration(guildId, integrationId), guildVoiceState(guildId, userId)
Members guildMembers, guildMembersSearch, guildMember(guildId, userId), guildMemberMe, guildMemberRole(guildId, userId, roleId)
Roles guildRoles, guildRole(guildId, roleId)
Bans guildBans, guildBan(guildId, userId), guildBulkBan
Channels channel, channelPermission(channelId, overwriteId), channelTyping, channelInvites, channelWebhooks
Messages channelMessages, message, crosspostMessage, channelBulkDelete, channelMessagesPins, channelMessagesPin
Reactions messageReactions(channelId, messageId, emoji), messageReactionMe, messageReactionUser, messageReactionsAll
Threads channelThreads, messageThread, threadMembers, threadMember(threadId, userId), channelPublicArchivedThreads, channelPrivateArchivedThreads, channelJoinedPrivateArchivedThreads
Polls pollExpire(channelId, messageId), pollAnswerVoters(channelId, messageId, answerId)
Emojis and stickers guildEmoji(guildId, emojiId?), applicationEmoji(applicationId, emojiId?), guildSticker(guildId, stickerId?), sticker(stickerId), stickerPacks(packId?)
Soundboard sendSoundboardSound(channelId), soundboardDefaultSounds(), guildSoundboardSound(guildId, soundId?)
Commands applicationCommands, applicationCommand, guildApplicationCommands(appId, guildId), guildApplicationCommand(appId, guildId, commandId)
Interactions interactionCallback(id, token), interactionOriginalResponse(applicationId, token)
Webhooks webhook(webhookId, token?), webhookMessage(webhookId, token, messageId), guildWebhooks
Invites invite(code), guildInvites
Scheduled events guildScheduledEvents, guildScheduledEvent, guildScheduledEventUsers
Auto-moderation guildAutoModerationRules, guildAutoModerationRule
Stage instances stageInstances(), stageInstanceByChannel(channelId)
Monetisation applicationSkus, applicationEntitlement(appId, entitlementId?), consumeEntitlement, skuSubscription(skuId, subscriptionId?)
Gateway and voice gateway(), gatewayBot(), voiceRegions()

For a route without a builder, write the path yourself; the path safety checks still apply. bun scripts/api-coverage.ts in the repository prints every Discord route and what covers it.

Discord limits requests per bucket. A bucket is identified by the hash Discord returns in X-RateLimit-Bucket, scoped by the route’s major parameter (channel, guild, or webhook id and token). Two channels on the same endpoint get separate limits, and two routes Discord maps to one hash share one.

Limits belong to a bot: bucket keys and the global limit are scoped by a fingerprint of the token (a truncated SHA-256, never the token), so bots sharing one store never share a counter. Interaction callbacks (/interactions/:id/:token/…) and token webhooks (/webhooks/:id/:token…) are limited per webhook, whoever sends them, so their buckets are shared by every bot; interaction callbacks count against no global limit. Requests without a token are scoped as "anon".

For each request the client:

  1. builds a route key: the method plus the path with ids replaced by :id, a reaction’s emoji by :emoji and the query removed, plus the major parameter;
  2. looks up the bucket hash learned for that route, falling back to the route key until Discord sends one;
  3. queues behind earlier requests on that bucket;
  4. reserves one unit of the bucket’s allowance, in the same atomic step that checks the global limit, and waits while either is spent. On a bucket nobody knows yet, one request (the probe) goes first and the others wait for its response; after a window resets, the next one opens at the known limit, so a fleet waking together cannot send more than the limit at once;
  5. with concurrentBuckets, frees the bucket’s slot as soon as the reservation is granted on a bucket whose limit is known, so the next request can go;
  6. merges X-RateLimit-Limit, -Remaining, -Reset-After, -Reset and -Bucket from the response. Within a window remaining only goes down, and a response from an older window (an earlier X-RateLimit-Reset) is ignored, so a late response cannot hand back allowance already reserved.

Headers are parsed one by one: a missing, empty, negative or non-numeric value is ignored, never read as 0.

A 429 records its wait (retry_after from the body, else Retry-After, else X-RateLimit-Reset-After, else one second) in the store, on the bucket, or on the bot’s global limit when the body says global: true, X-RateLimit-Global is true or X-RateLimit-Scope is global. The retry then waits for that state like any other request, so every request on the bucket, in every process, honours it. The onRateLimit hook fires for every 429 response; a wait the client imposes on itself from earlier headers (an exhausted bucket, an active global limit) does not fire it.

The server decides how long the client waits, so a misbehaving proxy, or anyone who can answer in Discord’s place, could send Retry-After: 99999999 and stall the bot. maxBackoff (default ten minutes) caps every server-controlled wait:

  • A Retry-After longer than maxBackoff fails the request immediately with a RESTError (status 429) instead of sleeping.
  • Bucket resets and global resets are stored no further than maxBackoff ahead.
  • A request that keeps losing the race for its bucket to other processes gives up after waiting twice maxBackoff, with a RESTError of kind "rateLimited", rather than wait forever.

By default each process keeps its own limits in a MemoryRateLimitStore. Bots that send from several processes (clusters, workers, a dashboard) should share them with Redis. With Bun’s built-in client:

import { REST, RedisRateLimitStore, fromBunRedis } from "@lunibee/rest";
const store = new RedisRateLimitStore({
client: fromBunRedis(new Bun.RedisClient(process.env.REDIS_URL!)),
prefix: "mybot:rest:", // default "lunibee:rest:"
failurePolicy: "degraded-local", // or "fail-closed"
});
await store.verify(); // fails fast if EVAL is disabled
const rest = new REST({ token: process.env.DISCORD_TOKEN!, store });

ioredis and node-redis clients are passed as they are (client: new Redis(url)).

RedisRateLimitStoreOptions Default Description
client — Any client with get, mget, set and del (ioredis and node-redis both fit; fromBunRedis() adapts Bun.RedisClient). With eval, every reservation, response merge and global extension is one atomic Lua script that reads Redis’s own clock (TIME). Without it the store is observational: workers can race on the last unit.
prefix "lunibee:rest:" Key prefix. Keys are versioned under it (…v1:bucket:…, …v1:global:…, …v1:route:…) and every key has a TTL. On Redis Cluster put a hash tag in it ("{mybot}:rest:").
failurePolicy "degraded-local" While Redis is unreachable: "degraded-local" limits from this process’s last known state; "fail-closed" fails each request with kind "coordination" without sending it. Either way the change is logged once, emitted as a mode event and shown by mode / diagnostics(), and the store returns to Redis when it answers.
commandTimeout 2000 Longest one Redis command may take, in ms, before it counts as failed.
requireAtomic false Throw at construction when the client has no eval.
telemetry — Receives store (per-command latency and outcome) and mode events.
onError — Called with (operation, error) for every failed command.
Member Description
mode "distributed", "observational", "degraded-local" or "unavailable".
diagnostics() { mode, failurePolicy, atomic, failures, lastFailureAt, lastError }, with tokens removed from lastError.
verify() Runs a script once; throws a TypeError without eval, or a RESTError of kind "coordination" when Redis refuses scripts.
isHealthy(), lastError Whether the last command succeeded, and the latest error.
supportsReservation Whether the client has eval.

The memory store keeps at most 10,000 bucket entries, 10,000 route-to-bucket mappings and 10,000 global scopes, dropping the oldest first, and prunes buckets a minute after their reset (the limit is remembered that long, so the next window opens at it).

Failure modes, guarantees and scaling are on Distributed REST.

To write your own store, implement RateLimitStore. Only the first six methods are required; each optional one adds a guarantee:

interface RateLimitStore {
getBucketHash(route: string): Promise<string | undefined> | string | undefined;
setBucketHash(route: string, hash: string): Promise<void> | void;
getBucket(key: string): Promise<BucketState | undefined> | BucketState | undefined;
updateBucket(key: string, state: BucketState): Promise<void> | void;
getGlobalReset(scope?: string): Promise<number> | number;
setGlobalReset(resetAt: number, scope?: string): Promise<void> | void;
// Atomic reservation (enables concurrentBuckets). Must grant one probe on an unknown bucket.
reserve?(key: string, options?: ReserveOptions): Promise<Reservation> | Reservation;
readonly reservesGlobal?: boolean; // reserve() also checks options.global
// Atomic response merge; without it the limiter reads, merges and writes.
reconcile?(key: string, update: BucketUpdate): Promise<void> | void;
// Atomic "at least this long" global limit; without it a concurrent writer can shorten it.
extendGlobalReset?(scope: string, waitMs: number): Promise<void> | void;
// Clears a probe placeholder, or refunds a unit whose request never left.
release?(key: string, grant: { resetAt?: number }, refund: boolean): Promise<void> | void;
prune?(maxAge?: number): Promise<void> | void;
}

reserveState() and reconcileState() in packages/rest/src/store.ts are the decisions the built-in stores make; a custom store can call them on its own state.

The default policy is createRetryPolicy(retries), with retries defaulting to 2. It retries:

Failure Retried for Delay
429 every method the server’s retry_after / Retry-After (bounded by maxBackoff)
5xx GET, HEAD, PUT, DELETE min(10 s, 500 ms × 2^attempt) plus up to 250 ms of jitter
network failure (DNS, reset, TLS) GET, HEAD, PUT, DELETE same as 5xx

POST and PATCH are never replayed after a 5xx or a network failure: Discord may already have acted on them, and a second message or a second ban is worse than an error. A timeout is never retried, and neither is a 401, 403 or any other 4xx but 429.

For a 429 the wait is the limiter’s (see Rate limits): the retry sleeps only what getDelay() asks beyond the server’s delay, then waits for the bucket or global limit with every other request. The onRetry hook fires before each retry of an error response (429, 5xx); a retry after a network failure does not fire it.

A custom policy:

import { REST, type RetryPolicy } from "@lunibee/rest";
const patient: RetryPolicy = {
maxRetries: 5,
shouldRetry: (method, status) => status === 429 || (status >= 500 && method === "GET"),
getDelay: (attempt, retryAfter) => (retryAfter ?? 2 ** attempt) * 1000,
};
const rest = new REST({ token, retryPolicy: patient });

status is 0 for a network failure. retryAfter is in seconds.

Every HTTP attempt has its own timeout (default 15 s). When it fires the attempt is aborted and the request fails with a RESTError of kind "timeout". Waiting for a rate limit does not count toward the timeout.

An AbortSignal cancels a request wherever it is: queued behind its bucket, waiting for a rate limit, between retries, or in flight. The promise rejects with a RESTError of kind "aborted" (status 0), whose cause is the signal’s reason.

import { RESTError } from "lunibee";
const controller = new AbortController();
setTimeout(() => controller.abort(), 5_000);
try {
await rest.get(Routes.guild(guildId), { signal: controller.signal });
} catch (error) {
if (error instanceof RESTError && error.kind === "aborted") {
console.warn("Request was cancelled.");
} else {
throw error;
}
}

AbortSignal.timeout(ms) works too. One signal can be reused for many requests: the client removes its listener from the signal on every path.

abortError(path, reason) builds the same RESTError (kind "aborted"), for custom transports or stores that need to report a cancellation the same way.

Requests wait in memory for their bucket. To bound that, set maxQueued (all buckets) or maxQueuedPerBucket; a request beyond either fails at once with kind "overloaded" (retryable), so a flood sheds load instead of growing the heap. A request on an idle bucket never counts as waiting.

close() is the graceful shutdown: it refuses new requests and fails those still queued or waiting for a limit (kind "aborted"), lets attempts already on the wire finish, and resolves when nothing is in flight.

process.on("SIGTERM", async () => {
await rest.close();
process.exit(0);
});

Pass telemetry: { emit(event) { … } } to receive events. They never contain a token, a token fingerprint or a body, and routes are normalised (GET:/channels/:id/messages/:id/reactions/:emoji), so labels stay bounded. A sink that throws is ignored.

Event type Fields
request method, route, status, attempts, durationMs, ok — once per request, end to end.
response method, route, status, durationMs — once per HTTP attempt.
rateLimited route, scope (user, global, shared, unknown), retryAfterMs.
wait reason (bucket, global, probe), durationMs.
reservation granted, known, latencyMs.
retry route, reason (rateLimited, server, network), attempt.
cancelled stage (queued, waiting, transport, retry).
overloaded, networkError (timedOut) A refused or failed attempt.
tokenRejected Discord answered 401 on a bot route; later requests with the token are refused.
bucket change (discovered, remapped), route.
queue queued, inFlight.
store, mode From RedisRateLimitStore’s own telemetry: per-command latency and outcome, and mode changes.

RESTMetrics turns them into counters, gauges and latency histograms, capping distinct route labels (500 by default, then other):

import { REST, RedisRateLimitStore, RESTMetrics } from "@lunibee/rest";
const metrics = new RESTMetrics();
const rest = new REST({
token: process.env.DISCORD_TOKEN!,
telemetry: metrics,
store: new RedisRateLimitStore({ client: redisClient, telemetry: metrics }),
});
Bun.serve({ port: 9100, fetch: () => new Response(metrics.toPrometheus()) });
metrics.snapshot(); // { counters, gauges, histograms }

Every failure rejects with a RESTError: a Discord error response, a network failure, a timeout, a cancellation, or an exhausted retry.

import { RESTError, RESTErrorCode } from "lunibee";
try {
await rest.delete(Routes.message(channelId, messageId));
} catch (error) {
if (!(error instanceof RESTError)) throw error;
if (error.code === RESTErrorCode.UnknownMessage) return; // already gone
console.error(`${error.method} ${error.path} → ${error.status} (${error.kind})`);
if (error.hint) console.error(error.hint);
if (error.retryable) queueForLater();
}
Property Type Description
kind RESTErrorKind The failure category; see the table below.
status number HTTP status, or 0 for a network failure, timeout or cancellation.
code number | undefined Discord’s JSON error code. Compare it with RESTErrorCode.
message string Discord’s message, or a description of the failure.
errors unknown Discord’s raw error payload, including the field-by-field validation errors of a 400.
method string | undefined Request method.
path string | undefined Request path, with webhook and interaction tokens replaced by :token.
hint string | undefined What to check, for codes 50001 (Missing Access) and 50013 (Missing Permissions); undefined for any other code.
retryable boolean Whether the same request could succeed later: true for rateLimited, server, network, timeout, coordination and overloaded.
cause unknown For network failures, a copy of the underlying error with tokens removed.
kind When
aborted The signal fired.
timeout An attempt exceeded timeout.
network No response: DNS, connection reset, TLS, a refused redirect.
rateLimited 429 after retries, or a Retry-After beyond maxBackoff.
authentication 401: the token is wrong or revoked.
permission 403.
notFound 404.
validation 400 or 422: Discord refused the body.
server 5xx.
client Any other 4xx.
coordination The rate-limit store failed (failurePolicy: "fail-closed", a script error, an invalid reply, or refusals with no wait). The request was not sent.
overloaded maxQueued or maxQueuedPerBucket was reached (the request was not sent), or the request waited past maxQueueWait.

Names for the Discord error codes bots handle most, such as UnknownMessage (10008), UnknownMember (10007), UnknownInteraction (10062), MissingAccess (50001), MissingPermissions (50013) and MaxPins (30003). Any other code is still available as a number on error.code.

Tokens never appear in anything the client produces:

  • error.path, error messages and every hook context replace webhook and interaction tokens with :token.
  • A network error’s cause is a sanitised copy, because runtimes put the request URL (with its token) in their error messages. That includes errors thrown by a custom transport.
  • Configuration errors never repeat the credentials in a bad baseURL.

redactPath(path) applies the same rule to your own logs:

import { redactPath } from "@lunibee/rest";
redactPath("/webhooks/1/abcdef/messages/2"); // "/webhooks/1/:token/messages/2"

Hooks let you observe traffic for metrics or logging. Each one runs on a microtask, apart from the request, and anything it throws is ignored, so a broken hook can never fail a request. Paths in hook contexts are already redacted. Keep hooks fast: work done in one still takes event-loop time from requests in flight.

const rest = new REST({
token,
hooks: {
onRequest: ({ method, path, attempt }) => metrics.inc("rest.request"),
onResponse: ({ method, path, status, durationMs }) => metrics.observe("rest.latency", durationMs),
onRateLimit: ({ path, retryAfterMs, global, bucket }) => log.warn("rate limited", { path, retryAfterMs, global }),
onRetry: ({ path, attempt, status, delayMs }) => log.info("retry", { path, attempt, status }),
},
});
Hook Context
onRequest { method, path, attempt }, before every HTTP attempt.
onResponse { method, path, status, durationMs }, after every response.
onRateLimit { method, path, retryAfterMs, global, bucket? }, for every 429 response.
onRetry { method, path, attempt, status, delayMs }, before retrying an error response.

rest.setHooks(hooks) replaces all hooks at runtime.

The bot token is sent to baseURL, so the URL is checked when the client is built and a TypeError is thrown if:

  • it is not an absolute https: or http: URL;
  • it contains credentials (user:pass@), a query, or a fragment (a bare ? or # included);
  • it is http: on a host other than this machine (localhost, 127.0.0.1, [::1]) and allowInsecureBaseURL is not set.

The URL is normalised, and a trailing / is removed.

new REST({ token, baseURL: "https://discord-proxy.internal/api/v10" }); // ok
new REST({ token, baseURL: "http://localhost:8080/api/v10" }); // ok: this machine
new REST({ token, baseURL: "http://rest-proxy:8080/api/v10", allowInsecureBaseURL: true }); // opt-in

Sends to a webhook without a bot token. It accepts a webhook URL or an id and token.

import { WebhookClient, CreateEmbed } from "lunibee";
const hook = new WebhookClient({ url: process.env.WEBHOOK_URL! });
// or: new WebhookClient({ id: "123…", token: "abc…" })
const sent = await hook.send({
content: "Deployed ✅",
username: "CI",
avatar_url: "https://example.com/ci.png",
allowed_mentions: { parse: [] },
embeds: [new CreateEmbed().setTitle("v0.3.1")],
});
await hook.editMessage(sent.id, { content: "Deployed ✅ (verified)" });
await hook.fetchMessage(sent.id);
await hook.deleteMessage(sent.id);

The URL must be Discord’s own webhook URL (discord.com, discordapp.com, ptb. or canary.); anything else throws.

Method Description
send(options) Sends a message and returns it (?wait=true). Takes a string or WebhookMessageOptions.
editMessage(messageId, options) Edits a message the webhook sent. Same options as send, files included.
fetchMessage(messageId, { threadId? }) Fetches a message the webhook sent.
deleteMessage(messageId, { threadId? }) Deletes a message the webhook sent.

WebhookMessageOptions: content, username, avatar_url, tts, embeds (objects or builders), components (objects or builders), files, flags, allowed_mentions, thread_id.

The second constructor argument takes { timeout?, retries? } for the webhook’s own REST.

A request passes through stages that are each exported, so you can test or reuse them:

request → createRouteKey → RequestScheduler → RateLimiter → HttpTransport → ResponseDecoder
Export Responsibility
createRouteKey(method, path) Returns { method, path, route, major }: the normalised route (GET:/channels/:id/messages) and its major parameter.
normalizeRoutePath(path), majorParameter(path), scopeBucket(hash, major), serializeQuery(query) The pieces createRouteKey and request use.
RequestScheduler Runs one request per bucket key at a time and frees the slot on every exit path, including an abort while queued. Options: maxQueued, maxQueuedPerBucket; queued counts waiting requests.
RateLimiter Reserves bucket and global allowance (acquire() returns a Grant), merges response headers (applyResponse()), records 429s, gives back a probe or an unsent request’s unit (releaseGrant()), caps waits to maxBackoff (DEFAULT_MAX_BACKOFF_MS).
parseRateLimitHeaders(headers), headerNumber(headers, name) Defensive header parsing: absent or invalid values are undefined, never 0.
requestIdentity(path, fingerprint), tokenFingerprint(token) Whose limits a request counts against (see Rate limits).
HttpTransport One HTTP attempt with timeout, cancellation and redirect: "error". Options: baseURL, allowInsecureBaseURL, timeout, fetch.
TransportError What HttpTransport throws for a failed attempt (timedOut tells a timeout apart). REST turns it into a RESTError.
ResponseDecoder Reads JSON, text or nothing (204), and Discord’s error fields and Retry-After.
MemoryRateLimitStore, RedisRateLimitStore, fromBunRedis(client) The built-in stores, and the Bun.RedisClient adapter.
RESTMetrics An in-memory telemetry aggregator; see Telemetry.
createRetryPolicy(maxRetries) The default retry policy.

Give REST a transport with a fake fetch:

import { REST, HttpTransport } from "@lunibee/rest";
const calls: string[] = [];
const rest = new REST({
token: "test-token",
transport: new HttpTransport({
fetch: async (url, init) => {
calls.push(`${init.method} ${url}`);
return new Response(JSON.stringify({ id: "1" }), {
status: 200,
headers: { "content-type": "application/json" },
});
},
}),
});

@lunibee/testing also has MockREST, which records each call and answers from a path-to-response map.