Skip to Content
nyx logonyx guide

Serverless

Run an HTTP bot on serverless platforms like Cloudflare Workers, Vercel or AWS Lambda.

Reading time:3 min read

On serverless platforms there's no long-lived process: the platform starts an instance when a request arrives, may reuse it for a while, and stops it whenever it wants. The bot works the same way there, but a few things need to change compared to a regular server.

Creating the bot

Create the bot once per instance and reuse it for every request the instance receives. Put its creation in a function, so your platform's entry and your command deploy script can share it:

src/bot.ts
import {  } from '@nyx-discord/http';

export type  = { : string; : string; : string };

export async function (: , : boolean) {
  const  = .(() => ({
    : .,
    : .,
    : .,
    : ,
    ,
  }));

  // await bot.getCommandManager().addCommands(...);
  await .();
  return ;
}

Deploying commands

Each new instance runs bot.start(), so with deployCommands: true, every cold start would deploy your commands to Discord again, wasting rate limits and slowing down the first request. Create the bot with deployCommands: false on the platform, and deploy commands from your machine (or CI) with a script that reuses the same function:

scripts/deploy-commands.ts
import 'dotenv/config';
import {  } from '../src/bot';

await (. as never, true);
.('Commands deployed.');

Run it again whenever you add or change a command. Commands are matched by name, so the bot doesn't need to know their IDs.

Keeping work alive

The platform may stop the instance once the response is sent, cutting off anything your commands do after their first reply. Pass the platform's waitUntil to the client, see Serverless platforms. Platforms without one, like AWS Lambda, need to wait for the handlers before responding.

Schedules don't run by themselves either, since there's no process to keep their timers. Trigger the work from your platform's scheduled jobs instead, like Workers cron triggers.

Testing without Discord

You can test your endpoint before setting it on the Developer Portal by signing requests yourself. Generate a keypair, use its public key as DISCORD_PUBLIC_KEY, and sign each request like Discord does:

scripts/send.ts
import { , ,  } from 'node:crypto';

// once: generate a keypair, and set `publicKeyHex` as DISCORD_PUBLIC_KEY
const { ,  } = ('ed25519');
const  = .({ : 'der', : 'spki' }).(-32).('hex');

const  = .({ : '1', : '1', : 1, : 't', : 1 });
const  = .(.() / 1000).();
const  = (null, .( + ), ).('hex');

const  = await ('http://localhost:8787/interactions' /* your local URL */, {
  : 'POST',
  : { 'X-Signature-Ed25519': , 'X-Signature-Timestamp':  },
  ,
});
.(., await .()); // 200 {"type":1}

That's a PING. Sending an application command interaction runs your command, though its reply fails with Unknown interaction, since Discord never created it.

Platform examples

Edit on GitHub

Last updated on

On this page