HTTP bots
Bots that receive interactions over HTTP (an Interactions Endpoint URL) instead of the gateway use
@shardlens/http. It runs on Cloudflare Workers, Deno, Bun and Node (for example with @discordjs/core), using
Web-standard APIs only.
pnpm add @shardlens/httpnpm install @shardlens/httpyarn add @shardlens/httpbun add @shardlens/httpdeno add npm:@shardlens/httpYou need a running collector and its ingest key (slk_ingest_…). The code on
this page takes its types from discord-api-types; install it too if you don’t have it.
Wrap your handler
Section titled “Wrap your handler”wrapInteractionHandler takes the function that answers an interaction and returns one you call the same way. Your
answer goes back to Discord unchanged; a handler that throws still throws.
This is a whole bot in one module. It verifies Discord’s signature, answers, and records every interaction:
import { createShardlensHttp, type WaitUntilContext } from '@shardlens/http';import type { APIInteraction, APIInteractionResponse } from 'discord-api-types/v10';
/** Worker bindings (vars and secrets), or `process.env` and `Deno.env.toObject()` on other runtimes. */export interface Env { /** Developer Portal → General Information → Public Key. */ DISCORD_PUBLIC_KEY?: string | undefined; /** Your collector, for example `https://stats.example.com`. */ SHARDLENS_URL?: string | undefined; /** `slk_ingest_…`. Keep it in a secret. */ SHARDLENS_INGEST_KEY?: string | undefined;}
const hex = (s: string) => Uint8Array.from(s.match(/../g) ?? [], (b) => Number.parseInt(b, 16));
/** Discord signs every request with Ed25519, and checks that the endpoint refuses a bad signature with 401. */async function verified(request: Request, body: string, publicKey: string): Promise<boolean> { const signature = request.headers.get('x-signature-ed25519'); const timestamp = request.headers.get('x-signature-timestamp'); if (!signature || !timestamp) return false; try { const key = await crypto.subtle.importKey('raw', hex(publicKey), { name: 'Ed25519' }, false, ['verify']); return await crypto.subtle.verify('Ed25519', key, hex(signature), new TextEncoder().encode(timestamp + body)); } catch { return false; }}
// Shardlens finds `ctx` among the arguments, and sends this interaction's events through `ctx.waitUntil`.async function answer(interaction: APIInteraction, _ctx?: WaitUntilContext): Promise<APIInteractionResponse> { if (interaction.type === 1) return { type: 1 }; // PING: answered, not recorded if (interaction.type === 2 && interaction.data.name === 'ping') { return { type: 4, data: { content: 'Pong!', flags: 64 } }; } return { type: 4, data: { content: 'Unknown command', flags: 64 } };}
/** The bot, for any runtime: Workers below, Deno, Bun and Node through their own servers. */export function createBot(env: Env) { // Nothing runs until the first interaction: no timers, no network. const lens = createShardlensHttp({ endpoint: env.SHARDLENS_URL, apiKey: env.SHARDLENS_INGEST_KEY }); const handle = lens.wrapInteractionHandler(answer); return { lens, async fetch(request: Request, ctx?: WaitUntilContext): Promise<Response> { if (request.method !== 'POST') return new Response('Not found', { status: 404 }); const body = await request.text(); if (!(await verified(request, body, env.DISCORD_PUBLIC_KEY ?? ''))) { return new Response('Bad request signature', { status: 401 }); } return Response.json(await handle(JSON.parse(body) as APIInteraction, ctx)); }, };}
// Cloudflare Workers: secrets arrive with the first request, so the bot is created then.let bot: ReturnType<typeof createBot> | undefined;export default { fetch(request: Request, env: Env, ctx: WaitUntilContext): Promise<Response> { bot ??= createBot(env); return bot.fetch(request, ctx); },};The same module runs on every runtime. Only the last few lines, which start the server, differ:
The default export above is the Worker. Keep the URL in wrangler.toml and the two keys in secrets:
name = "my-bot"main = "worker.ts"compatibility_date = "2026-10-01"
[vars]SHARDLENS_URL = "https://stats.example.com"npx wrangler secret put DISCORD_PUBLIC_KEYnpx wrangler secret put SHARDLENS_INGEST_KEYnpx wrangler deployFor npx wrangler dev, put the same two names in a .dev.vars file, which Git should ignore.
Pass ctx to the wrapped handler, as the module does. Shardlens sends each interaction’s events through
ctx.waitUntil, after your response has gone back to Discord.
import { createBot } from './worker.ts';
const bot = createBot(Deno.env.toObject());const server = Deno.serve({ port: 8787 }, (request) => bot.fetch(request));
// Send what is queued before the process stops.Deno.addSignalListener('SIGTERM', async () => { await server.shutdown(); await bot.lens.shutdown(); Deno.exit(0);});deno run --allow-net --allow-env main.tsimport { createBot } from './worker.ts';
const bot = createBot(process.env);const server = Bun.serve({ port: 8787, fetch: (request) => bot.fetch(request) });
// Send what is queued before the process stops.process.on('SIGTERM', async () => { await server.stop(); await bot.lens.shutdown(); process.exit(0);});bun main.tsNode has no built-in server for Request and Response, so this one turns each request into a Request.
@discordjs/core sends what comes after the first answer: follow-ups and edits.
import { createServer } from 'node:http';import { API } from '@discordjs/core/http-only';import { REST } from '@discordjs/rest';import { createBot } from './worker.ts';
const bot = createBot(process.env);// Follow-ups and edits after a deferred reply: api.interactions.followUp(applicationId, token, { content })export const api = new API(new REST().setToken(process.env.DISCORD_TOKEN ?? ''));
const server = createServer(async (req, res) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk); const request = new Request(`http://localhost${req.url}`, { method: req.method ?? 'GET', headers: req.headers as Record<string, string>, body: req.method === 'POST' ? Buffer.concat(chunks) : null, }); const response = await bot.fetch(request); res.writeHead(response.status, Object.fromEntries(response.headers)); res.end(Buffer.from(await response.arrayBuffer()));});server.listen(8787);
// Send what is queued before the process stops.process.on('SIGTERM', async () => { server.close(); await bot.lens.shutdown(); process.exit(0);});Node 22.18 and later run main.ts as it is (node main.ts); on older versions, compile it first or use tsx.
On Deno, Bun and Node, set DISCORD_PUBLIC_KEY, SHARDLENS_URL and SHARDLENS_INGEST_KEY in the environment.
Then put the bot’s public URL in Interactions Endpoint URL in the Developer Portal. Discord checks it with a PING
and with a badly signed request, which must get a 401: the module answers both.
What it records
Section titled “What it records”For every interaction except PING, exactly the same fields as the discord.js adapter:
command, subcommand, options used, context, channel type, install type, locale, member tier, premium, the response type, and how long
your answer took against Discord’s 3-second deadline. The user ID is hashed before anything is sent. The interaction
token and what users type never leave your bot; nor do option values, unless you list the option in
captureOptionValues.
- Buttons, selects and modals are recorded by their custom ID, with numbers and IDs replaced by
*. Buttons and selects are attributed to the command that created their message, and a command that opens a modal is linked to the modal’s submissions. - Errors thrown by your handler are recorded by class (never the message) and re-thrown unchanged.
- Slow answers: a response returned more than 3 seconds after the interaction was created is recorded as a timeout, because Discord will already have shown “The application did not respond”.
- Deferred replies: the time recorded is the time to your first answer, the deferral. Follow-ups and edits you send through Discord’s REST API afterwards are not recorded.
Responseobjects: a handler may return aResponseinstead of the body. Shardlens reads the callback type from a copy of a JSON body; yourResponseis returned as it is.- Custom events:
lens.track(name, props, { userId, guildId }, ctx)works as in the discord.js adapter. Passctxon Workers, or the event waits for the next interaction. For typed events, register them withdeclare module '@shardlens/http'.
When events are sent
Section titled “When events are sent”- With
waitUntil(Cloudflare Workers, and anything else whose handler gets an object with awaitUntilmethod): if any argument you pass to the wrapped handler haswaitUntil, Shardlens hashes and sends that request’s events through it, after your response. Nothing is left for a timer, because a Worker’s timers stop with the request that set them. If the collector could not be reached, the next interaction asks it for its settings again. - Without
waitUntil(a long-running Node, Bun or Deno server): events are batched and sent in the background every 5 seconds, as in the discord.js adapter. Callawait lens.shutdown()when the process stops. - Serverless without
waitUntil: if your platform can stop the process as soon as the response is sent and gives you nothing likewaitUntil,await lens.flush()before you return. That adds the collector’s round trip to your answer, so preferwaitUntilwhere there is one.
Creating the Shardlens instance is free: nothing runs (no timers, no network) until the first interaction that is recorded, so it is safe on runtimes that forbid I/O at startup. A PING, such as Discord checking your endpoint URL, starts nothing.
Options
Section titled “Options”createShardlensHttp takes the options of the discord.js adapter that make sense without a gateway: endpoint,
apiKey, mode, auditIncludeProfile, captureOptionValues, normaliseCustomId, environment, release,
optedOut, sampleRate, exporters, dryRun, logger and fetch, described in
Configuration. One is its own: instance, a label for this deployment in SDK health
(the Worker’s name, for example). Opt-outs and erasure work the same way: lens.optOut(userId),
lens.optIn(userId) and await lens.forgetUser(userId).
A complete Worker is in
examples/cloudflare-worker.