Cloudflare Workers
Run an HTTP bot on Cloudflare Workers.
This page assumes you've read Serverless, and have a createBot() function like the one there.
Creating the project
npm create cloudflare@latest my-bot -- --type hello-world --lang tsnpm i @nyx-discord/http @discordjs/coreThe bot doesn't need the nodejs_compat compatibility flag.
Writing the worker
Workers only give you your secrets through env once a request arrives, and don't allow network calls before that, so
create the bot on the first request and keep the promise for the next ones. Pass the worker's ctx to the handler, so the
worker stays alive until your handlers finish:
import { } from '@nyx-discord/http';
type = {
: <typeof >;
: <typeof >;
};
let : <> | null = null;
function (: ) {
??= (, false).(() => {
const = .();
return {
: (),
: (.()),
};
});
return ;
}
export default {
async (: , : , : ) {
const { , } = await ();
const { } = new (.);
const = === '/webhook-events' ? : ;
return (, );
},
};Running locally
Put your secrets in .dev.vars:
APP_ID=...
DISCORD_PUBLIC_KEY=...
TOKEN=...npx wrangler devThis runs the worker in workerd, the same runtime as production. Test it without Discord,
or expose it with a tunnel (like cloudflared tunnel --url http://localhost:8787) and set the tunnel's URL as your app's
Interactions Endpoint URL.
Deploying
Put your secrets in a file kept out of git (it can be the same as .dev.vars), and pass it on the first deploy:
npx wrangler deploy --secrets-file .dev.varsLater deploys keep the secrets, so npx wrangler deploy is enough. Remember to deploy your commands too.
If it's your account's first worker, the deploy also creates your workers.dev subdomain, whose certificate can take a few
minutes. Until then, requests to it fail with a TLS handshake error.
Setting the endpoint
On the Developer Portal, set your app's Interactions Endpoint URL to https://<worker>.<subdomain>.workers.dev/interactions,
and its Webhook Events URL (if you use them) to .../webhook-events.
Last updated on
