Twitch EventSub with webhooks

With EventSub, Twitch sends you events such as raids, follows or the start of your stream the moment they happen. By webhook they go to an address of your choice, if it meets a few conditions. This guide shows the whole way, with code you can use.

Updated 10 minute read

What Twitch requires

For EventSub by webhook, your address has to meet three conditions:

  1. HTTPS on port 443 with a valid certificate. An address such as https://bot.yourchannel.tv/eventsub works, https://bot.yourchannel.tv:8080/eventsub does not.
  2. Answer a verification. When you create a subscription, Twitch sends a request with a challenge that you return unchanged. Only then do events come.
  3. Check signatures. Every message is signed with a secret only you and Twitch know. You refuse messages without a valid signature.

Then the practical part: the service has to run when the event happens, and answer quickly. On EStage you enter your domain, we fetch the certificate and pass requests to your service, which listens on PORT.

Preparation

  1. Create an application in the Twitch developer console. You get a client ID and a client secret.
  2. Make up an EventSub secret: 10 to 100 characters, random. Twitch signs the messages to you with it.
  3. Create the secrets on EStage: TWITCH_CLIENT_ID, TWITCH_CLIENT_SECRET and EVENTSUB_SECRET.

The receiver

This server accepts messages on /eventsub, checks them and handles two events: the start of your stream and incoming raids. It needs no library, only Node.js.

// eventsub.js: receives EventSub webhooks from Twitch and checks every message.
import http from 'node:http';
import crypto from 'node:crypto';

const SECRET = process.env.EVENTSUB_SECRET;   // 10 to 100 characters, known only to you and Twitch
const seen = new Set();                       // IDs of messages already handled

function valid(req, body) {
  const id = req.headers['twitch-eventsub-message-id'];
  const time = req.headers['twitch-eventsub-message-timestamp'];
  const signature = req.headers['twitch-eventsub-message-signature'];
  if (!id || !time || !signature) return false;
  // Messages older than ten minutes count as replays.
  if (Math.abs(Date.now() - Date.parse(time)) > 10 * 60 * 1000) return false;
  const expected = 'sha256=' + crypto.createHmac('sha256', SECRET).update(id + time + body).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(String(signature));
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

function handle(event, type) {
  if (type === 'stream.online') console.log(`${event.broadcaster_user_name} is live`);
  if (type === 'channel.raid') console.log(`Raid from ${event.from_broadcaster_user_name} with ${event.viewers} viewers`);
}

const server = http.createServer(async (req, res) => {
  if (req.method !== 'POST' || req.url !== '/eventsub') {
    res.writeHead(404).end();
    return;
  }
  let body = '';
  for await (const chunk of req) body += chunk;

  if (!SECRET || !valid(req, body)) {
    res.writeHead(403).end();
    return;
  }
  const kind = req.headers['twitch-eventsub-message-type'];
  const msg = JSON.parse(body);

  if (kind === 'webhook_callback_verification') {
    // Verification: return the challenge unchanged as text.
    res.writeHead(200, { 'Content-Type': 'text/plain' }).end(msg.challenge);
    return;
  }
  // Answer at once, then process. Otherwise Twitch sends the message again.
  res.writeHead(204).end();

  const id = req.headers['twitch-eventsub-message-id'];
  if (seen.has(id)) return;
  seen.add(id);
  if (seen.size > 1000) seen.delete(seen.values().next().value);

  if (kind === 'notification') handle(msg.event, msg.subscription.type);
  if (kind === 'revocation') console.warn(`Subscription ended: ${msg.subscription.type} (${msg.subscription.status})`);
});

server.listen(Number(process.env.PORT) || 8000);
process.on('SIGTERM', () => server.close(() => process.exit(0)));

The important parts:

  • The signature is an HMAC-SHA256 over message ID, timestamp and the unchanged body. That is why the server reads the body as text before parsing it as JSON. The comparison uses timingSafeEqual, so an attacker cannot tell from the response time how much of their signature is right.
  • The timestamp must not be older than ten minutes. That way nobody can send an old, valid message again.
  • The verification returns the challenge as plain text, with status 200.
  • Events get an answer at once and are processed afterwards. The server recognises duplicates by their ID.
  • Revocations arrive when Twitch ends a subscription, for example because a permission was withdrawn. The server writes them to the log so you notice.

Creating subscriptions

You create subscriptions once, not on every start. This script gets an app token, looks up your channel’s ID and registers the two subscriptions:

// subscribe.js: registers the subscriptions with Twitch. Run once by hand.
const { TWITCH_CLIENT_ID: id, TWITCH_CLIENT_SECRET: secret, EVENTSUB_SECRET, CHANNEL, CALLBACK } = process.env;

// 1. Get an app token (client credentials).
const tokenRes = await fetch('https://id.twitch.tv/oauth2/token', {
  method: 'POST',
  body: new URLSearchParams({ client_id: id, client_secret: secret, grant_type: 'client_credentials' }),
});
const { access_token: token } = await tokenRes.json();
const headers = { 'Client-Id': id, Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };

// 2. Look up the channel's ID.
const users = await (await fetch(`https://api.twitch.tv/helix/users?login=${CHANNEL}`, { headers })).json();
const channelId = users.data[0].id;

// 3. Create the subscriptions. Twitch then sends a verification for each to CALLBACK.
const subs = [
  { type: 'stream.online', version: '1', condition: { broadcaster_user_id: channelId } },
  { type: 'channel.raid', version: '1', condition: { to_broadcaster_user_id: channelId } },
];
for (const sub of subs) {
  const res = await fetch('https://api.twitch.tv/helix/eventsub/subscriptions', {
    method: 'POST',
    headers,
    body: JSON.stringify({ ...sub, transport: { method: 'webhook', callback: CALLBACK, secret: EVENTSUB_SECRET } }),
  });
  console.log(sub.type, res.status, (await res.json()).data?.[0]?.status ?? '');
}

Run it from your PC once the receiver is running:

CHANNEL=yourchannel CALLBACK=https://bot.yourchannel.tv/eventsub \
TWITCH_CLIENT_ID=... TWITCH_CLIENT_SECRET=... EVENTSUB_SECRET=... \
node subscribe.js

If both subscriptions show 202 and webhook_callback_verification_pending, Twitch has accepted the request and sends the verification to your receiver. You see it arrive in the receiver’s logs. After that the status is enabled.

stream.online and channel.raid need no consent from the channel. Other events, such as follows, subs or channel points, need a permission the channel grants your application once by signing in. Which one is listed with each event type in the Twitch documentation.

Bringing it online on EStage

  1. Push, with a Dockerfile like this:
FROM node:24-slim
WORKDIR /app
COPY . .
USER node
CMD ["node", "eventsub.js"]
  1. Create the secrets as described above.
  2. Enter a domain, such as bot.yourchannel.tv, and confirm it.
  3. Create the subscriptions with the script once the service runs.

And then

Writing an event to the log is the start. It gets interesting when it triggers something: an alert in the overlay, a message in Discord, points in the database. How an overlay gets alerts from another service is in the guide OBS overlay on your own domain.

Common questions

Why does no verification arrive from Twitch?

Mostly because the address is not reachable on port 443 with a valid certificate. Twitch refuses an address with its own port such as :8080. Also check that your server answers on exactly the path you gave as the callback.

Webhook or WebSocket, which should I use?

Webhooks, if your service runs all the time anyway and has an HTTPS address, as on EStage. The WebSocket route if you have no public address, in a desktop app for example. It needs a user token instead of an app token.

Why do I get the same event twice?

Twitch resends a message when your answer takes too long or does not come. So answer at once with a 2xx status and remember the IDs of messages you have already handled, as in the code below.

Ready when you are

EStage launches in early 2027. Tell us what you want to run, and we will set up the first channels together.

Early access See pricing