---
title: "Securing your stream callback endpoint"
description: "AudD stream callbacks are plain POST requests with no signature. Put a long random secret in the callback URL, check it in constant time, answer 200 fast, and make repeated deliveries harmless, with complete receivers in Node and Python."
slug: "/resources/concepts/securing-your-callback-endpoint"
section: "concepts"
keywords: [audd, streams, callbacks, webhook security, callback secret, constant-time comparison, setCallbackUrl, duplicate callbacks]
---

# Securing your stream callback endpoint

Callbacks are the requests with recognition results our servers will send to your server. The callbacks will be sent to the specified URL as a JSON structure in the POST payload. They aren't signed, so there's no signature header to check, and once your server is configured to receive callbacks, it'll listen for any payload sent to the endpoint you configured. For security reasons, you probably want to limit requests to those coming from AudD.

If you receive stream callbacks on your backend, there are several steps you can take to secure receipt of callbacks delivered by AudD: put a long random secret in the callback URL and compare it in constant time, use an HTTPS URL, respond with `200 OK` before you do the work, and make a repeated result harmless. Below, you'll find a complete receiver in Node and in Python that does all of this.

## Put a secret in the callback URL

AudD sends callbacks with results for all the streams to a single callback URL you set, so put the secret in that URL. The secret is any string you want; you need it to ensure the callbacks are from a trusted source. Use a random string with high entropy (e.g., by taking the output of `openssl rand -hex 32` at the terminal):

```bash
openssl rand -hex 32
# or: python3 -c "import secrets; print(secrets.token_hex(32))"
```

Both commands print 64 hexadecimal characters, which are safe in a URL without encoding. Keep the secret in an environment variable, and set the callback URL with it:

```js
import { AudD } from "@audd/sdk";

const audd = new AudD(); // reads AUDD_API_TOKEN
const secret = process.env.AUDD_CALLBACK_SECRET;
if (!secret) throw new Error("Set AUDD_CALLBACK_SECRET first.");
await audd.streams.setCallbackUrl(`https://yourapp.example/audd-callback/${secret}`);
console.log(await audd.streams.getCallbackUrl());
```

```python
import os
from audd import AudD

audd = AudD()  # reads AUDD_API_TOKEN
secret = os.environ["AUDD_CALLBACK_SECRET"]
audd.streams.set_callback_url(f"https://yourapp.example/audd-callback/{secret}")
print(audd.streams.get_callback_url())
```

Or with curl:

```bash
curl https://api.audd.io/setCallbackUrl/ \
    -F api_token="$AUDD_API_TOKEN" \
    -F url="https://yourapp.example/audd-callback/${AUDD_CALLBACK_SECRET:?}"
```

The examples on this page put the secret in the path. A query parameter works too, and AudD's own [Discord bot](/resources/integrations/discord-bot) uses `?secret=` in its callback URL. If you use a query parameter, give it a name that AudD doesn't use: our server reads `?return=` from the callback URL to add metadata to the results, and `disable-lastsong=true` turns longpoll off for your streams.

Ensure that your receiving server is on an HTTPS connection: the secret is part of the URL, and over plain HTTP, anyone between our servers and yours could read it.

> **Note.** The secret is shared with AudD, so it isn't a private key. We store the callback URL on our side, and anyone with your API token can get it using the `getCallbackUrl` method. Please keep the token on your server; if it leaks, change the secret as well (see [Keeping your API token on the server](/resources/concepts/keeping-your-token-server-side)). And if your reverse proxy logs the paths of requests, the secret is in those logs too.

## A receiver in Node

There's nothing to install for the Node version: it uses only the standard library. Save it as `receiver.mjs` and run it with `AUDD_CALLBACK_SECRET=... node receiver.mjs`:

```js
// receiver.mjs: AUDD_CALLBACK_SECRET=... node receiver.mjs
import { createServer } from "node:http";
import { createHash, timingSafeEqual } from "node:crypto";

const PREFIX = "/audd-callback/";
const MAX_BODY = 1024 * 1024; // 1 MB
const current = process.env.AUDD_CALLBACK_SECRET ?? "";
if (current.length < 32) throw new Error("Set AUDD_CALLBACK_SECRET to a long random string.");
// While you rotate the secret, the previous one keeps working too.
const secrets = [current, process.env.AUDD_CALLBACK_SECRET_OLD].filter(Boolean);

const sha256 = (s) => createHash("sha256").update(s).digest();
const expected = secrets.map(sha256);
function isKnownSecret(given) {
  const g = sha256(given); // equal lengths, so timingSafeEqual can compare
  let match = false;
  for (const e of expected) match = timingSafeEqual(g, e) || match; // no early exit
  return match;
}

const seen = new Set(); // in production: a unique key in your database

function handle(body) {
  if (body?.notification) {
    const n = body.notification;
    if (n.notification_code !== 0) {
      console.warn(`stream ${n.radio_id}: ${n.notification_code} ${n.notification_message}`);
    }
    return;
  }
  const r = body?.result;
  if (!r || !Number.isInteger(r.radio_id) || !Array.isArray(r.results)) {
    console.warn("callback with an unexpected shape:", JSON.stringify(body).slice(0, 200));
    return;
  }
  for (const song of r.results) {
    const key = [r.radio_id, r.timestamp, song?.audio_id, song?.artist, song?.title].join("|");
    if (seen.has(key)) continue; // delivered again: already handled
    seen.add(key);
    if (seen.size > 10_000) seen.delete(seen.values().next().value);
    console.log(`stream ${r.radio_id} at ${r.timestamp}: ${song?.artist} - ${song?.title}`);
  }
}

createServer((req, res) => {
  if (req.method !== "POST") {
    res.writeHead(405, { Allow: "POST", Connection: "close" }).end();
    return;
  }
  const path = (req.url ?? "").split("?")[0]; // the URL may also carry ?return=...
  if (!path.startsWith(PREFIX) || !isKnownSecret(path.slice(PREFIX.length))) {
    res.writeHead(404, { Connection: "close" }).end();
    return;
  }
  if (Number(req.headers["content-length"]) > MAX_BODY) {
    res.writeHead(413, { Connection: "close" }).end();
    return;
  }
  const chunks = [];
  let size = 0;
  req.on("data", (chunk) => {
    size += chunk.length;
    if (size > MAX_BODY) {
      if (!res.headersSent) res.writeHead(413, { Connection: "close" }).end();
      req.destroy();
      return;
    }
    chunks.push(chunk);
  });
  req.on("end", () => {
    if (size > MAX_BODY) return;
    res.writeHead(200).end("OK"); // answer first, then do the work
    let body;
    try {
      body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
    } catch {
      console.warn("callback body is not JSON");
      return;
    }
    setImmediate(() => handle(body));
  });
}).listen(8080, "127.0.0.1"); // behind your HTTPS reverse proxy
```

The receiver accepts only POST requests, and any other method gets `405`. If the secret in the path is wrong, it responds with `404`, as it would for any other unknown path. Note that the secrets are compared with `crypto.timingSafeEqual`, so the check takes the same time no matter how much of the secret is right. The query string is ignored, which means a URL that also carries `?return=spotify` still works.

The receiver reads at most 1 MB of the body; anything bigger gets `413`. As soon as the body is read, it responds with `200 OK`, and only then does it parse and handle the callback. You can't predict how long your own code will take, so it's better to do all of "the real work" after the response. Replace `handle()` with your own code: write to your database, send an alert, or put the body in a queue.

By default, the receiver listens on `127.0.0.1:8080`, so it can be used behind nginx or another HTTPS front end that your public URL points to. You can change this in the last line.

## The same receiver in Python

The Python version needs Flask, which you can install with `pip install flask`. The first line of the file shows how to run it.

```python
# receiver.py: pip install flask, then AUDD_CALLBACK_SECRET=... flask --app receiver run --port 8080
import hmac
import json
import logging
import os
import queue
import threading

from flask import Flask, abort, request

current = os.environ.get("AUDD_CALLBACK_SECRET", "")
if len(current) < 32:
    raise RuntimeError("Set AUDD_CALLBACK_SECRET to a long random string.")
# While you rotate the secret, the previous one keeps working too.
SECRETS = [s.encode() for s in (current, os.environ.get("AUDD_CALLBACK_SECRET_OLD")) if s]

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024  # 1 MB; Flask never reads more than this
log = logging.getLogger("audd-callback")
jobs: queue.Queue = queue.Queue()


def is_known_secret(given: str) -> bool:
    match = False
    for s in SECRETS:
        match = hmac.compare_digest(given.encode(), s) or match  # constant time, no early exit
    return match


@app.post("/audd-callback/<secret>")  # other methods get 405
def audd_callback(secret: str):
    if not is_known_secret(secret):
        abort(404)
    raw = request.get_data()  # 413 if the request says it is larger than 1 MB
    if len(raw) >= app.config["MAX_CONTENT_LENGTH"]:
        abort(413)  # a body sent without a length, cut off at 1 MB
    try:
        jobs.put(json.loads(raw))
    except ValueError:
        log.warning("callback body is not JSON")
    return "OK"  # answer first; the worker thread does the rest


seen: dict[str, None] = {}  # in production: a unique key in your database


def handle(body) -> None:
    if not isinstance(body, dict):
        log.warning("callback with an unexpected shape: %.200s", body)
        return
    n = body.get("notification")
    if isinstance(n, dict):
        if n.get("notification_code") != 0:
            log.warning("stream %s: %s %s", n.get("radio_id"),
                        n.get("notification_code"), n.get("notification_message"))
        return
    r = body.get("result")
    if not isinstance(r, dict) or not isinstance(r.get("radio_id"), int) \
            or not isinstance(r.get("results"), list):
        log.warning("callback with an unexpected shape: %.200s", body)
        return
    for song in r["results"]:
        song = song if isinstance(song, dict) else {}
        key = "|".join(str(v) for v in (r["radio_id"], r.get("timestamp"),
                       song.get("audio_id"), song.get("artist"), song.get("title")))
        if key in seen:
            continue  # delivered again: already handled
        seen[key] = None
        if len(seen) > 10_000:
            seen.pop(next(iter(seen)))
        print(f"stream {r['radio_id']} at {r.get('timestamp')}: "
              f"{song.get('artist')} - {song.get('title')}", flush=True)


def worker() -> None:
    while True:
        body = jobs.get()
        try:
            handle(body)
        except Exception:
            log.exception("callback handling failed")


threading.Thread(target=worker, daemon=True).start()
```

The Flask development server is for trying the receiver only. In production, run it under a WSGI server, such as gunicorn: `gunicorn -b 127.0.0.1:8080 receiver:app`. Note that each worker keeps its own `seen` list, which is one more reason to keep the identity of a result in your database.

## Try it with recorded callbacks

You can test either receiver without a stream. Download two recorded callback bodies from the public [audd-openapi fixtures](https://github.com/AudDMusic/audd-openapi/tree/main/fixtures) and post them with curl:

```bash
export AUDD_CALLBACK_SECRET=$(openssl rand -hex 32)
node receiver.mjs &   # or: flask --app receiver run --port 8080 &
sleep 1

F=https://raw.githubusercontent.com/AudDMusic/audd-openapi/main/fixtures
curl -sO $F/streams_callback_with_result.json
curl -sO $F/streams_callback_with_notification.json

U=http://127.0.0.1:8080/audd-callback/$AUDD_CALLBACK_SECRET
curl -s -w " %{http_code}\n" --data-binary @streams_callback_with_result.json $U        # OK 200
curl -s -w " %{http_code}\n" --data-binary @streams_callback_with_result.json $U        # OK 200, not logged again
curl -s -w " %{http_code}\n" --data-binary @streams_callback_with_notification.json $U  # OK 200
curl -s -o /dev/null -w "%{http_code}\n" --data-binary @streams_callback_with_result.json \
    http://127.0.0.1:8080/audd-callback/wrong-secret                                    # 404
curl -s -o /dev/null -w "%{http_code}\n" $U                                             # 405
```

You'll see the song once and the notification once in the receiver's output:

```text
stream 7 at 2020-04-13 10:31:43: Alan Walker, A$AP Rocky - Live Fast (PUBGM)
stream 3: 650 Recognition failed: can't connect to the audiostream
```

If you want to receive real callbacks on your laptop, you'll need a public HTTPS URL that forwards to it. See [Test stream callbacks locally](/resources/recipes/test-callbacks-locally) for how to set one up, and don't forget to set the callback URL back to your server's when you're done.

## Results and notifications

You'll receive callbacks with results and with notifications. The results contain the recognized songs, and the `status` is `"success"`. Notifications are information about the state of the streams, and the `status` is `"-"`. There are 3 codes: `0` (which means that everything's fine), `650` (which means that we can't connect to the stream) and `651` (which means that we don't receive any music from the stream, only white noise). We've implemented callback parsing in the SDKs, so you don't have to check the keys yourself: `parseCallback(body)` in Node and `audd.streams.parse_callback(body)` in Python take the body you've read and return a match or a notification. Just check the secret and the size first.

A callback contains either `result` or `notification`, never both, so the receivers check which key is there. There can be several songs in one callback, so read all the objects in `result.results`, not just the first one. The exact bodies are in the [stream callback payload reference](/resources/reference/streams-callback-shape), and what to do about `650` and `651` is in [Stream health](/resources/concepts/stream-health).

## When the same result arrives twice

If your server doesn't respond to the callbacks with the `200 OK` status or we can't connect to your server, we'll put the callbacks in a queue. When your server is back online, we'll gradually send all of the backlog. So a result that you've already stored can arrive again if your `200 OK` didn't reach AudD.

Your handler should be idempotent: receiving a result once or several times in a row should have the same effect. To make it so, treat the `radio_id`, the `timestamp` and the song as the identity of a result. For the songs from your custom catalog, the result contains the `audio_id` you set when you uploaded the song, and `artist` and `title` can be `null`, so include the `audio_id` in the key too. In a database, make these columns a unique key and insert with "insert or ignore"; the [radio airplay monitor](/resources/recipes/radio-airplay-monitor) stores plays this way.

The receivers don't rely on the order of arrival either. You can tell the streams apart by the `radio_id` in every result, and the `timestamp` tells you when the song played. If a notification arrives twice, you'll just see the same alert again.

## When the body isn't what you expect

If a request has the right secret, but its body doesn't parse or has neither `result` nor `notification`, log it and respond with `200 OK` anyway. Another status code won't fix the body; it will only put the same callback back in the queue. The only exception is a body over the size cap, which gets `413`, and 1 MB leaves plenty of room for results with metadata blocks.

## Rotating the secret

Set the URL for callbacks using the `setCallbackUrl` API method; you can change the URL at any time using this method. There is one callback URL per account, and the callbacks from all the streams are sent to it, so a new secret applies to all your streams at once. To change it without losing callbacks:

1. Generate a new secret, and restart the receiver with the new secret in `AUDD_CALLBACK_SECRET` and the old one in `AUDD_CALLBACK_SECRET_OLD`. Now both of them work.
2. Send the new URL to the AudD API using the `setCallbackUrl` method. The new URL replaces the old one as a whole, so if the old URL had a `return` or `disable-lastsong` parameter, add it to the new one too. (In the SDKs, the `returnMetadata` option in Node and `return_metadata` in Python add `?return=` for you.)
3. Use the `getCallbackUrl` method to check the current callback URL.
4. Leave the old secret in place for a day or so, in case the callbacks that were in the queue before the change still arrive at the old URL. Then remove `AUDD_CALLBACK_SECRET_OLD` and restart the receiver.

You should change the secret if the URL may have been seen by someone else: in logs, in a screenshot, or in a config file you shared. It's also a good idea to change it when someone who knew it leaves your team, and every time you rotate your API token after a leak.

## What not to rely on

Some services publish the IP addresses they use when delivering webhooks, so you can add them to your server's allow list. We don't publish such a list for callbacks, and they aren't signed, so the secret in the URL is the check.

---

**Related**

- [Stream callback and longpoll payload reference](/resources/reference/streams-callback-shape)
- [Webhook callbacks vs longpoll for stream results](/resources/concepts/callback-vs-longpoll)
- [Stream health](/resources/concepts/stream-health)
- [Test stream callbacks locally](/resources/recipes/test-callbacks-locally)
- [Keeping your API token on the server](/resources/concepts/keeping-your-token-server-side)
- [Streams docs](https://docs.audd.io/streams)

## Sitemap

See the [resources sitemap](https://audd.io/resources/sitemap.md) for every guide and the [glossary](https://audd.io/resources/reference/glossary.md) for AudD terms.
