API Key Security Best Practices: Seven Habits That Keep Your Balance Safe

CQTAI

11/16/2026

#Security#API Keys#Best Practices#Secrets Management#DevOps
API Key Security Best Practices: Seven Habits That Keep Your Balance Safe

An API key is not just an identifier. It is a bearer credential: whoever holds the string can make calls and spend the balance of the account behind it, with no password and no second step. That is what makes keys convenient, and it is also why a single leaked key can turn into a surprise bill.

The good news is that most leaks come from a handful of predictable mistakes, and each one has a cheap fix. This guide walks through seven habits, shows what the platform lets you enforce per key, and ends with a checklist you can paste into your team wiki.

1. Keep the key on the server, never in client code

Anything you ship to a browser or a phone is public. That includes JavaScript bundles, mobile app binaries, and "hidden" config files. Someone only has to open the network tab to read a header.

So the rule is simple: the key lives on a server you control, and your frontend talks to your server. Your server adds the key and forwards the request. Here is a minimal proxy in Node that never exposes the key to the browser:

import express from "express";

const app = express();
app.use(express.json());

app.post("/api/chat", async (req, res) => {
  const upstream = await fetch("https://api.novapi.ai/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.NOVAPI_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "MODEL_ID",
      messages: [{ role: "user", content: String(req.body.prompt ?? "").slice(0, 2000) }],
    }),
  });
  res.status(upstream.status).json(await upstream.json());
});

app.listen(3000);

Two details matter here. The prompt is length-limited, so a visitor cannot make one request arbitrarily expensive. And in a real app you would also add your own authentication and rate limit in front of this route, otherwise the proxy simply becomes a public door to your key.

2. Load keys from the environment, not from source files

A key that is typed into a source file will eventually be committed. Put it in an environment variable and read it at runtime.

# .env  (listed in .gitignore, never committed)
NOVAPI_API_KEY=sk-your-key-here
curl https://api.novapi.ai/v1/chat/completions \
  -H "Authorization: Bearer $NOVAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "MODEL_ID", "messages": [{"role": "user", "content": "Hello"}]}'
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["NOVAPI_API_KEY"],
    base_url="https://api.novapi.ai/v1",
)
reply = client.chat.completions.create(
    model="MODEL_ID",
    messages=[{"role": "user", "content": "Hello"}],
)
print(reply.choices[0].message.content)
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.NOVAPI_API_KEY,
  baseURL: "https://api.novapi.ai/v1",
});
const reply = await client.chat.completions.create({
  model: "MODEL_ID",
  messages: [{ role: "user", content: "Hello" }],
});
console.log(reply.choices[0].message.content);

Replace MODEL_ID with an id from the models page. The key above is a placeholder; never paste a real one into a blog post, a screenshot or a code review comment.

In production, prefer your platform's secret store (your cloud provider's secrets manager, your CI system's encrypted variables, or a vault) over a .env file on disk. Also run a secret scanner such as gitleaks in CI or as a pre-commit hook. It is much cheaper to catch a key before the push than after.

3. Use one key per project and per environment

Do not share a single key across your laptop, staging, production and that script a colleague wrote last spring. Create a separate key for each, and give it a name that says who owns it and what it is for, such as prod-chat-backend or staging-batch-jobs.

Separate keys give you three things: you can disable one without breaking the rest, you can set different limits for each, and when something looks odd you know where to start looking.

4. Use the limits the platform gives every key

When you create or edit a key on the API Keys page, you can set boundaries. They are enforced by the gateway on every request, so a leaked key can only do what the key was allowed to do.

SettingWhat it doesWhat a violating request gets
Usage limitCaps what this key itself can spend. 0 means unlimited.HTTP 400
ExpiryThe key stops working at the time you choose. Blank means it never expires.HTTP 401
IP allowlistOnly requests from the listed addresses are accepted. Empty means any source.HTTP 403
Allowed modelsOnly the listed models or channels can be called. Empty means every model.HTTP 403, model_not_allowed

Some practical notes:

  • The usage limit is a ceiling, not a budget for your account. It only caps the key's own usage, and real spending is still bound by your balance. For a demo or a customer, a small limit plus a short expiry is the cheapest insurance you can buy.
  • IP allowlists suit servers with fixed addresses. Entries are IP addresses, and * works as a wildcard inside an entry (for example 203.0.113.*). If your code runs on a platform whose outbound addresses change from run to run, an allowlist will block you, so leave it empty and lean on the other limits instead.
  • An empty model list means "all models", not "none". The console warns you when removing the last entry would turn a restricted key into an unrestricted one. Read that warning.
  • Prefer narrow keys. A key for a cron job that summarizes text only needs one model and one server address. Give it exactly that.

5. Rotate keys on a schedule, and rotate without downtime

Long-lived keys accumulate risk: more copies, more places they have been pasted, more people who once had access. The console helps by flagging any enabled key that has been around for more than 90 days with an "In use for N days, consider replacing" tag and a banner above the list. We may also send a reminder email, but treat that as a courtesy rather than a guarantee, and check the list yourself.

A rotation that never interrupts traffic looks like this:

  1. Create a new key with the same limits.
  2. Deploy the new key to your secret store and roll your services.
  3. Watch your logs until nothing uses the old key.
  4. Disable the old key. Disabling can be undone, deleting cannot.
  5. After a quiet week, delete the old key.

The full key is shown only once, right after you create it, so copy it straight into your secret store. If you lose it, nobody can recover it for you: create a replacement and retire the old one.

6. Keep keys out of logs, tickets, chats and screenshots

Most real-world leaks are not hacks. They are a key in a debug log, in a support ticket, in a screenshot of a terminal, in a pasted curl command in a team chat.

  • Never log request headers. If you must log a key to debug, log only the first few characters.
  • When asking anyone for help, including our support team, give the key's name, not its value. Nobody should need the full key to look into a problem.
  • Before sharing a screenshot or a recording, check the terminal, the browser address bar and any open .env file.
  • Search your repository history once in a while. git log -S"sk-" --all --oneline lists commits that added or removed text containing sk-.

7. Watch usage so you notice quickly

A limit protects you, but noticing protects you faster. Open the Logs page now and then to scan for models you do not use or activity at odd hours. In Settings you can turn on balance alerts by email, DingTalk or Feishu, so you hear about a sudden drop in balance without opening the console.

If you ever see something unexpected, follow the steps in our leaked-key checklist. The first move is always the same: disable the key.

A checklist you can reuse

  • No key in frontend code, mobile apps, public repos or screenshots
  • Keys read from environment variables or a secret store
  • One key per project and environment, with a descriptive name
  • Usage limit and expiry set on every key that is not core production
  • Model allowlist (and IP allowlist where your addresses are fixed) set
  • A rotation date on the calendar, at most every 90 days
  • Balance alerts switched on
  • Everyone on the team knows how to disable a key

FAQ

Can I view my key again after I close the creation dialog? No. The full key is displayed once, at creation. Afterwards the list shows only a masked version. If you lose it, create a new key.

I set a low usage limit. Is it safe to embed the key in my mobile app? It limits the damage, but it is still not safe. Anyone can extract the key and use up the limit, and your users will hit errors when they do. Route requests through your own server instead.

Disable or delete: which first? Disable. It stops the key from being accepted and you can switch it back on if you disabled the wrong one. Delete only when you are sure nothing depends on it.

Takeaways

  • A key is a bearer credential: treat it like a password that can spend money.
  • Keep it on the server, read it from the environment, and never commit it.
  • Use one key per project, and set expiry, usage limit and model limits on each.
  • Rotate on a schedule, disable before you delete, and watch your usage.

Want to read more? See how the platform protects your keys, and browse the documentation for the endpoints you can call with a key.