BotNetwork

Discord interactions over HTTP: endpoint URL and Ed25519 checks

A Discord bot that only uses slash commands, buttons and modals does not need a WebSocket connection open all day. Point Discord at an HTTPS endpoint, verify every request with your application's public key, and your bot becomes an ordinary web handler.

Published 8 min read

Two ways to receive interactions

When someone uses one of your app's commands, clicks a button or submits a modal, Discord creates an interaction. According to Discord's documentation, your app can receive interactions in two mutually exclusive ways:

  • Gateway: an INTERACTION_CREATE event over the WebSocket connection that libraries such as discord.js keep open. This is the default.
  • HTTP: a POST request to an Interactions Endpoint URL that you set in the Developer Portal. Discord calls this "outgoing webhooks", and it does not require a connected client.

Once you set an endpoint URL, interactions stop arriving over the Gateway and go to that URL instead. You cannot split them between the two.

When HTTP interactions make sense

HTTP fits bots whose features are all commands and components: lookups, forms, moderation tools, utilities, dashboards that answer /status. Because each interaction is a separate request, the handler can run on any web stack, scale like a normal API and sit behind the same reverse proxy as the rest of your services. It also removes the reconnect and heartbeat logic that a Gateway bot must handle, which is one of the ideas in keeping a bot online for free.

It does not fit everything. The HTTP endpoint only receives interactions. If your bot must react to ordinary messages, member joins, reactions or presence, you still need a Gateway connection with the right intents (see Discord gateway intents explained), and then it is usually simpler to receive interactions there too.

What your endpoint must do before Discord accepts it

The Interactions overview lists two requirements. If either fails, the Developer Portal will not save your URL:

  1. Acknowledge PING. When you save the URL, Discord sends a POST with a payload of type: 1. You must answer 200 with a JSON body {"type": 1} (a PONG) and a valid Content-Type header.
  2. Validate the security headers. Every request carries X-Signature-Ed25519 (a hex signature) and X-Signature-Timestamp. You verify the signature over the timestamp followed by the raw request body, using your application's public key from the General Information page. If verification fails, answer 401.

Discord also states that it performs routine automated checks on your endpoint, including purposely sending invalid signatures. If your endpoint accepts one of those, Discord removes the URL and alerts you by email and system DM. In practice this means a handler that "temporarily" skips verification will eventually be switched off.

Verifying the signature correctly

The signed message is the timestamp string concatenated with the request body exactly as it arrived. Three details matter:

  • Use the raw body. If your framework parses JSON first and you serialize it again, whitespace and key order can change and the signature will not match. Read the bytes, verify, and only then parse.
  • Decode from hex. The signature and the public key are both hex strings. A malformed hex value should end in 401, not in an unhandled exception that returns 500.
  • The public key is not a secret, the bot token is. The public key only verifies. The bot token, which you use later to call the API, belongs in a secret store as described in securing bot tokens.

Discord's documentation does not define a maximum age for X-Signature-Timestamp. Some developers also reject timestamps far from the current time as extra protection against replays; if you do this, allow for clock drift and keep your server time synchronized.

Python implementation (Flask and PyNaCl)

This is a complete endpoint. It was tested before publishing against requests signed with a locally generated Ed25519 key, including invalid and malformed signatures:

import os
from flask import Flask, request, jsonify, abort
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError

app = Flask(__name__)
verify_key = VerifyKey(bytes.fromhex(os.environ["DISCORD_PUBLIC_KEY"]))

def verify(req) -> bool:
    signature = req.headers.get("X-Signature-Ed25519", "")
    timestamp = req.headers.get("X-Signature-Timestamp", "")
    body = req.get_data()  # raw bytes, before any JSON parsing
    try:
        verify_key.verify(timestamp.encode() + body, bytes.fromhex(signature))
        return True
    except (BadSignatureError, ValueError):
        return False

@app.post("/interactions")
def interactions():
    if not verify(request):
        abort(401, "invalid request signature")
    interaction = request.get_json()
    if interaction["type"] == 1:  # PING
        return jsonify({"type": 1})  # PONG
    if interaction["type"] == 2 and interaction["data"]["name"] == "ping":
        return jsonify({
            "type": 4,  # CHANNEL_MESSAGE_WITH_SOURCE
            "data": {"content": "Pong", "flags": 64, "allowed_mentions": {"parse": []}},
        })
    return jsonify({"type": 4, "data": {"content": "Unknown command", "flags": 64}})

flags: 64 is the EPHEMERAL flag, so only the person who ran the command sees the reply. Setting allowed_mentions to an empty parse list follows Discord's advice to filter mentions when a response may contain user data.

Node.js implementation (built-in crypto)

Recent Node.js versions support Ed25519 in the built-in crypto module, so no extra package is needed. The 32-byte public key is imported as a JWK:

import crypto from "node:crypto";

const publicKey = crypto.createPublicKey({
  key: { kty: "OKP", crv: "Ed25519", x: Buffer.from(process.env.DISCORD_PUBLIC_KEY, "hex").toString("base64url") },
  format: "jwk",
});

export function isValidDiscordRequest(rawBody, signature, timestamp) {
  if (!signature || !timestamp) return false;
  const sig = Buffer.from(signature, "hex");
  if (sig.length !== 64) return false;
  const message = Buffer.concat([Buffer.from(timestamp), rawBody]);
  return crypto.verify(null, message, publicKey, sig);
}

With Express, mount the route with express.raw({ type: "application/json" }) so req.body is a Buffer, call isValidDiscordRequest(req.body, req.get("X-Signature-Ed25519"), req.get("X-Signature-Timestamp")), answer 401 when it returns false, and run JSON.parse only afterwards. Discord's own examples use the tweetnacl package; either approach verifies the same signature.

Responding in time

Discord's documentation says you must send an initial response within 3 seconds, or the interaction token is invalidated. With HTTP interactions you usually answer in the body of the same POST with an interaction response object. The callback types you will use most are:

  • 1 PONG, only for PING.
  • 4 CHANNEL_MESSAGE_WITH_SOURCE, reply with a message.
  • 5 DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE, acknowledge now and show a loading state.
  • 6 DEFERRED_UPDATE_MESSAGE and 7 UPDATE_MESSAGE, for components.
  • 9 MODAL, open a pop-up form.

If the work may take longer than a moment (an external API, a database query, an AI model), answer with type 5 immediately, process the job in the background, and then edit the reply with PATCH /webhooks/<application_id>/<interaction_token>/messages/@original. The token stays valid for 15 minutes for edits and follow-up messages. Our note on when to defer in Discord covers the decision in more detail. Because users can click a button twice or run a command again, the patterns in idempotent message handling apply here as well.

Registering commands without a Gateway

Commands are registered through the HTTP API, independently of how interactions are delivered. Global commands use PUT /applications/<application_id>/commands (bulk overwrite) or POST for a single command, authenticated with your bot token. During development, guild commands under /applications/<application_id>/guilds/<guild_id>/commands are convenient for testing on one server. If you already registered commands with discord.js as shown in slash commands in discord.js v14, they keep working; only the delivery path changes when you set the endpoint URL.

A domain and HTTPS for the endpoint

The Interactions Endpoint URL must be public and served over HTTPS, so you need a hostname with a valid certificate. A dedicated subdomain such as interactions.example.com lets you move the handler between servers without touching the Developer Portal setting. You can register a short domain at Namecheap domains and point it at your VPS or container host; the DNS, reverse proxy and certificate steps are in a custom domain and HTTPS for your bot. If you also want a simple landing page or documentation site for the bot, Namecheap hosting can serve static pages while the endpoint runs elsewhere, and Namecheap keeps both in one account. For local testing before you have a public URL, see testing webhooks on localhost.

Common mistakes

  • Parsing JSON before verifying. Re-serialized bodies do not match the signature. Verify the raw bytes first.
  • Returning 500 on bad input. Missing headers or invalid hex should produce 401, the code Discord expects.
  • Forgetting Content-Type: application/json. The PONG must be valid JSON with the right header or the portal will reject the URL.
  • Doing slow work before answering. Anything that can exceed 3 seconds should be deferred.
  • Expecting message events. The endpoint receives interactions only; messages and member events still require the Gateway.
  • Logging full payloads. Interactions contain user data and a token that can edit your replies for 15 minutes. Log IDs, not bodies.

Checklist

  1. Serve a public HTTPS route that accepts POST.
  2. Read the raw body and verify X-Signature-Ed25519 over X-Signature-Timestamp plus body with your public key.
  3. Answer 401 on any verification failure, including malformed headers.
  4. Answer PING with {"type": 1} and a JSON content type.
  5. Reply within 3 seconds, or defer with type 5 and edit the original response later.
  6. Save the URL in the Developer Portal and test a command on a test server.
  7. Keep the bot token server-side and use the public key only for verification.

Sources