---
title: "Keeping your API token on the server"
description: "Why an AudD API token must not ship inside a mobile, browser, desktop, or game client, and how to arrange the call instead: a complete Node proxy with a size cap and a per-IP limit, what a client can hold safely, and how to rotate a token that leaked."
slug: "/resources/concepts/keeping-your-token-server-side"
section: "concepts"
keywords: [audd, api token, api key security, backend proxy, mobile app, browser extension, rate limit, token rotation, setApiToken]
---

# Keeping your API token on the server

All the API requests require the `api_token` from the Dashboard. You can share the longpoll categories with your clients or users, but please don't include your API tokens in the client-side software. If you're building a mobile app, a browser extension, a desktop app, or a game, the client should send the audio to your server, and your server should call AudD with the token.

## Why the token can't ship in a client

An app is just files on someone else's phone or computer, and the token would be one of the strings in those files. If you put your token in an app, anyone who has a copy of the app can use the token to access the AudD API with your account. Once a token has shipped in a client, you should consider the token compromised.

Since the token is the only thing a request needs, whoever has your token can send recognition requests on your account, add and delete your streams, and change the callback URL your results are sent to. They can also read that URL with `getCallbackUrl`, including any secret in it.

There are no rate limits on the standard endpoint: you can send requests in parallel, as many as you need, and so can anyone with your token. Requests beyond your plan's included amount are billed at the plan's rate per 1,000, normally at the end of the billing period, so the bill follows the usage, whoever sends it.

## Put a small server between the client and AudD

Here's how it works: the client sends a file or a URL to your server, and your server checks the request, calls AudD with the token, and sends back only the fields the client shows. Below is a complete server in Node. It uses Express, `multer`, and our SDK, which you can install with `npm install @audd/sdk express multer`:

```ts
// server.ts: the only place your AudD token exists.
import express, { type ErrorRequestHandler, type RequestHandler } from "express";
import multer from "multer";
import { AudD, AudDInvalidAudioError } from "@audd/sdk";

const audd = new AudD(); // reads AUDD_API_TOKEN from the environment
const app = express();
// Behind one reverse proxy or load balancer? Uncomment so req.ip is the client:
// app.set("trust proxy", 1);

// 1. A size cap: 10 MB, the standard endpoint's limit.
const upload = multer({ limits: { fileSize: 10 * 1024 * 1024, files: 1 } });

// 2. A per-IP limit: 20 recognitions per hour, kept in memory.
const WINDOW_MS = 60 * 60 * 1000;
const PER_WINDOW = 20;
const windows = new Map<string, { start: number; count: number }>();

const perIpLimit: RequestHandler = (req, res, next) => {
  const key = req.ip ?? "unknown"; // or your signed-in user's ID
  const now = Date.now();
  const w = windows.get(key);
  if (!w || now - w.start >= WINDOW_MS) {
    windows.set(key, { start: now, count: 1 });
  } else if (++w.count > PER_WINDOW) {
    res.status(429).json({ error: "too_many_requests" });
    return;
  }
  next();
};
setInterval(() => {
  const now = Date.now();
  for (const [key, w] of windows) if (now - w.start >= WINDOW_MS) windows.delete(key);
}, WINDOW_MS).unref();

// 3. One route, multipart form data: a file (field "file") or a URL (field "url").
app.post(
  "/identify",
  perIpLimit,
  upload.single("file"),
  async (req, res) => {
    let source: Uint8Array | URL;
    if (req.file) {
      source = req.file.buffer;
    } else if (typeof req.body?.url === "string" && URL.canParse(req.body.url)) {
      const url = new URL(req.body.url);
      if (url.protocol !== "https:" && url.protocol !== "http:") {
        res.status(400).json({ error: "bad_url" });
        return;
      }
      source = url; // a URL object: the SDK never reads it as a local file path
    } else {
      res.status(400).json({ error: "send_a_file_or_a_url" });
      return;
    }

    try {
      const song = await audd.recognize(source);
      if (!song) {
        res.json({ match: false });
        return;
      }
      // 4. Only the fields the client shows.
      res.json({
        match: true,
        artist: song.artist ?? null,
        title: song.title ?? null,
        album: song.album ?? null,
        songLink: song.songLink ?? null,
      });
    } catch (err) {
      if (err instanceof AudDInvalidAudioError) {
        res.status(422).json({ error: "unreadable_audio" });
        return;
      }
      console.error(err); // the details stay in your logs
      res.status(502).json({ error: "recognition_failed" });
    }
  },
);

const onUploadError: ErrorRequestHandler = (err, _req, res, next) => {
  if (err instanceof multer.MulterError) {
    res.status(err.code === "LIMIT_FILE_SIZE" ? 413 : 400).json({ error: err.code });
    return;
  }
  next(err);
};
app.use(onUploadError);

app.listen(3000);
```

Run it with `AUDD_API_TOKEN=your-api-token npx tsx server.ts` (get your own token at [dashboard.audd.io](https://dashboard.audd.io)), and send it a URL or a file:

```bash
curl -F url=https://audd.tech/example.mp3 http://localhost:3000/identify
curl -F file=@clip.m4a http://localhost:3000/identify
```

```json
{"match":true,"artist":"Tears For Fears","title":"Everybody Wants To Rule The World","album":"Songs From The Big Chair","songLink":"https://lis.tn/NbkVb"}
```

The token comes from the `AUDD_API_TOKEN` environment variable, and it never appears in a response. We recommend that you store it in a dedicated, secure location outside of the repository for your project, such as your platform's secret store. Make sure to never check it into any kind of version control. The standard endpoint accepts files up to 10 MB, so a bigger upload gets `413` and never reaches AudD.

Your server should limit how often a client can call it, since the standard endpoint won't. The example counts requests per IP address, before the upload is read, and a client over the limit gets `429`. If your app has sign-in, count requests per user instead. Note that the counts are kept in memory, so they're reset when the server restarts and aren't shared between instances. If you run several instances, keep the counts in a shared store.

If the server runs behind a reverse proxy or a load balancer, `req.ip` will be the proxy's address, and every client will share one limit. To fix that, set Express's `trust proxy` setting to the number of proxies in front of the app, like the commented line does for one.

The response has only five fields, so the client never sees our error messages or anything else about your account. If the audio can't be read, the server responds with `422`, and for any other error, it responds with `502` and logs the details. A successful call that matched nothing returns `{"match": false}`: this is not an error.

### When the client sends a URL

If the client sends a URL, there's nothing for your server to download: our server will download the file and identify the music. Just don't pass the client's string to the SDK as it is. The SDK reads a string that doesn't start with `http://` or `https://` as the path to a file on your server, so the example turns the string into a `URL` object first and accepts only `http:` and `https:` addresses.

### When the audio is longer than a clip

The standard endpoint is for a short clip with one song. If you need to recognize larger audio files, use the enterprise endpoint instead: it supports even days-long files. We count requests to the enterprise endpoint as 1 request per 12 seconds of audio, so if clients can send long files through your server, set `limit` on every enterprise call. See [Controlling enterprise endpoint cost](/resources/concepts/enterprise-cost-control).

### The client side

We've described the client side of this pattern for several platforms: [React Native](/resources/integrations/react-native), [Chrome extensions](/resources/integrations/chrome-extension), [Electron](/resources/integrations/electron-desktop), [Flutter](/resources/integrations/flutter), and [Unity](/resources/integrations/unity). The React Native and Chrome extension clients post the same `file` field to `/identify` and read the same response, so you can use this server with them as it is. If you want to run the server at the edge, see [Run AudD music recognition in a Cloudflare Worker](/resources/integrations/cloudflare-workers).

## What a client can hold

You can share the longpoll categories with your clients or users. A category identifies one stream: use the `longpoll_category` field from the `getStreams` response, or calculate it on your server with `audd.streams.deriveLongpollCategory(radioId)` in Node. Our widget needs only the category, so you can put its address in a web page: `https://widget.audd.tech/?ch=-<category>&history`. [Longpoll](/resources/concepts/callback-vs-longpoll) still needs a callback URL configured on the account; if you don't have one, set `https://audd.tech/empty/`. The results your server returns, such as `songLink`, are safe to show as well.

## The exception: your own machine

Scripts and command-line tools that you run on your own computer are a different case, since the token never leaves your machine. You can set the token as an environment variable (`export AUDD_API_TOKEN=your-api-token`), or store it in the system credential store with `audd config set token`.

A desktop app in which each user enters their own AudD token is fine too: the [Electron page](/resources/integrations/electron-desktop) reads it from the OS keychain. But a copy of your app that other people install must never contain your token.

## If your token leaked

For a leaked token, rotate the token, copy the new one, and update any services that use the old token. You can rotate it in three places:

- in the [dashboard](https://dashboard.audd.io);
- with the AudD CLI: `audd token rotate` (it needs `audd login`);
- through the [AudD MCP server](/resources/integrations/mcp-server), whose `rotate_api_token` tool needs the `token:write` scope. Clients that register themselves don't get that scope by default.

Note that the old token stops working right away. Until your services have the new one, their requests fail with an authentication error.

### Update a running service

If a service reads the token from an environment variable, restart it with the new value. If it reads the token from a file or a secret store, the SDK can swap the token without a restart: in-flight requests finish on the previous token, and later calls use the new one. In Node:

```ts
import { readFileSync } from "node:fs";
import { AudD } from "@audd/sdk";

const readToken = () => readFileSync(process.env.AUDD_API_TOKEN_FILE!, "utf8").trim();
const audd = new AudD(readToken());

// After a rotation: write the new token to the file, then run `kill -HUP <pid>`.
process.on("SIGHUP", () => audd.setApiToken(readToken()));
```

In Python:

```python
import os
import signal
from audd import AudD

def read_token() -> str:
    with open(os.environ["AUDD_API_TOKEN_FILE"]) as f:
        return f.read().strip()

audd = AudD(read_token())
# After a rotation: write the new token to the file, then run `kill -HUP <pid>`.
signal.signal(signal.SIGHUP, lambda signum, frame: audd.set_api_token(read_token()))
```

The other SDKs have the same method:

| SDK | Method |
|---|---|
| Python | `audd.set_api_token(new_token)` |
| Node.js | `audd.setApiToken(newToken)` |
| Go | `client.SetAPIToken(newToken)` |
| Rust | `audd.set_api_token(new_token)` |
| PHP | `$audd->setApiToken($newToken)` |
| Java | `audd.setApiToken(newToken)` |
| Kotlin | `audd.setApiToken(newToken)` |
| Swift | `try await audd.setApiToken(newToken)` |
| C# | `audd.SetApiToken(newToken)` |
| C | `audd_client_set_api_token(client, new_token)` |
| C++ | `client.set_api_token(new_token)` |

If you receive stream callbacks with a secret in the URL, change that secret too: whoever had the token could read it with `getCallbackUrl`. [Securing your stream callback endpoint](/resources/concepts/securing-your-callback-endpoint) shows how. Then look at your daily usage in the dashboard, or with `audd usage`, to see whether someone else used the old token.

---

**Related**

- [Add music recognition to a React Native app](/resources/integrations/react-native)
- [Webhook callbacks vs longpoll for stream results](/resources/concepts/callback-vs-longpoll)
- [Run AudD music recognition in a Cloudflare Worker](/resources/integrations/cloudflare-workers)
- [Securing your stream callback endpoint](/resources/concepts/securing-your-callback-endpoint)
- [Production checklist](/resources/concepts/production-checklist)
- [Node.js SDK docs](https://docs.audd.io/sdks/node)

## 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.
