Introduction

Getting started

Simple Example with CURL

First we'll generate a random key to subscribe on

RANDOM_KEY=$(uuidgen)

Subscribe to topic

curl -N https://webhook.stream/sse/$RANDOM_KEY

Post to the topic - In a different terminal window

curl -H 'Content-type: application/json' -d '{"hello": "world"}' \
    https://webhook.stream/post/$RAMDOM_KEY
  1. Now the subscriber will get the message

Using JS event source

In javascript SSE are handled automatically with reconnects and parsing out of the box

Subscribe

import { v4 as uuidv4 } from 'uuid'
const RANDOM_KEY = uuidv4()
const eSource = new EventSource(`https://webhook.stream/sse/${RANDOM_KEY}`)
eSource.onmessage = (m) => {
  console.log('New Message: ', m)
}

Publish

We can post again from bash with curl or from js like this:

import axios from 'axios'

axios.post(`https://webhook.stream/post/${RANDOM_KEY}`, { hello: 'world' })

Real world example with Telegram

Let's say we want to listen to a Telegram bot messages and respond on incoming messages

Set Telegram webhook

We call Telegram to set the webhook url to post to our topic on webhook.stream on any new update

curl -d {"url":"https://webhook.stream/post/$TOPIC_ID"} \
    http://api.telegram.org/bot$YOUR_BOT_TOKEN/setWebhook \
    -H "Content-Type: application/json"

Handle Messages

Now we can build a simple bot that runs everywhere

const eSource = new EventSource(`https://webhook.stream/sse/${TOPIC_ID}`)
eSource.onmessage = (m) => {
  console.log('New Message: ', m)
}
// This will print any incoming message

Or adapt it to respond with echo message

const eSource = new EventSource(`https://webhook.stream/sse/${TOPIC_ID}`)
eSource.onmessage = (m) => {
  const msg = JSON.parse(m.data)
  axios.post(`https://api.telegram.org/bot${telegramToken}/sendMessage`, {
    chat_id: msg.event.message.chat.id,
    text: msg.event.message.text,
  })
}
Previous
What is this