API Key Security Best Practices
By Urlzee Team · Published · 6 min read
An API key is a password for a program. Keep it on a server, load it from an environment variable or secrets manager, never put it in a Git repository, browser code or mobile app, and replace it at once if it may have been exposed. Most key leaks are accidents that those few habits prevent.
Why does an API key need protecting?
Because whoever holds it is treated as you. An API has no other way to tell a legitimate caller from someone who found the key in a public repository.
What a stolen key allows depends on the service. With a URL shortener it could mean someone creating links under your account, deleting the ones printed on your packaging, or using up your quota. Urlzee's keys, which begin with uz_live_, give access to all of the account's links: anyone holding one can create, edit and delete them. With a payment or cloud provider the cost of a leaked key can be measured directly in money.
Keys also tend to live for a long time and get copied between machines, which gives them many chances to escape.
Where do API keys leak from?
Almost always from places people forget are public or shared.
| Where | How it happens | Prevention |
|---|---|---|
| Git repositories | Key pasted into code or a committed .env file | Environment variables, .gitignore, secret scanning |
| Front-end JavaScript | Key bundled into a web page | Call the API from your server only |
| Mobile and desktop apps | Key embedded in the binary, then extracted | Route requests through your own backend |
| Logs and error reports | Request headers logged in full | Redact Authorization before logging |
| Screenshots and screen shares | Terminal or dashboard visible | Mask values; rotate after demos |
| Chat, email and tickets | Key pasted to a colleague or into a support request | Share through a secrets manager |
| URLs | Key passed as a query parameter | Send keys in headers, never in URLs |
| CI systems | Key printed in build output | Use the platform's masked secrets |
The URL row deserves a moment. Query strings are recorded in server logs and browser history, and are sometimes passed to other sites in the Referer header. This is why well-designed APIs take the key in a header. Urlzee expects Authorization: Bearer uz_live_... and nothing in the URL.
How do you keep a key out of your code?
Read it from the environment at run time. The code then contains the name of the variable, not the secret.
// Node.js
const key = process.env.URLZEE_API_KEY;
if (!key) throw new Error("URLZEE_API_KEY is not set");
# Python
import os
key = os.environ["URLZEE_API_KEY"] # raises KeyError if missing
Failing loudly when the variable is missing is deliberate. A program that starts without its key and fails later is much harder to debug.
For local development, many projects keep values in a .env file. That is fine provided the file never reaches version control:
# .gitignore
.env
.env.*
!.env.example
Commit a .env.example that lists the variable names with placeholder values, so colleagues know what to set without seeing the real ones.
In production, do not ship a .env file at all. Hosting platforms, container orchestrators and CI services each have a settings area for secrets, which injects them as environment variables and keeps them out of build logs. Larger teams use a dedicated secrets manager, which adds access control and an audit trail.
Why can't the key go in a browser or mobile app?
Because you do not control those devices. Code that runs on a user's machine can be read by that user.
In a web app, a key in your JavaScript bundle is visible in the page source, and every request made with it shows in the browser's Network tab, headers included. Minifying the code or building the key from pieces does not help; the browser has to assemble the real value to send it. Mobile apps are no different. An app package can be unpacked and searched for strings.
The fix is architectural:
- The front end sends a request to your server, authenticated by your own login session.
- Your server checks that the user is allowed to do this, and how often.
- Your server calls the third-party API with the key and returns only the result.
The key stays on a machine you control. Step 2 is not optional: an unauthenticated proxy endpoint just moves the problem, because anyone can call it and spend your quota. There is a working example in how to shorten URLs with JavaScript and Node.js.
How should you manage keys day to day?
Treat keys as disposable and separate.
- One key per application or environment. If your production site, a staging server and a spreadsheet script each have their own key, you can revoke one without breaking the others, and you can tell which one was leaked. Urlzee allows 1 key on the Free plan, 5 on Pro and 20 on Business.
- Name keys after where they are used. "Production website" tells you more than "key 2" on the day you need to revoke something.
- Copy the key once, into its final home. Urlzee displays a new key a single time and stores only a hash of it, so the full value cannot be shown again. If you lose it, create a new key.
- Give people as little as they need. A contractor building a report does not need the production key. Where a service offers scoped or read-only keys, use them. Where it does not, as with Urlzee, limit who can see the key at all.
- Rotate on events, and on a schedule if you can keep to it. Replace keys when someone with access leaves, after any incident, and after the key has been visible in a demo or recording.
- Watch usage. An unexpected jump in requests, or links you do not recognise, is often the first sign of a leak. On the Urlzee API, the
X-Quota-Remainingresponse header shows how much of the month's allowance is left, which makes a sudden drop easy to notice.
Rotation is painless only if the key lives in one configuration value. If changing a key means editing code in six places, fix that first.
What should you do if a key leaks?
Act on the assumption that it has been copied. Speed matters more than certainty.
- Revoke the key. In Urlzee this is done from Dashboard → API keys. A revoked key stops working at once; requests using it receive
401. - Create a replacement and update the configuration of every system that used the old one.
- Review recent activity. Look for links you did not create, changed destinations and deletions. Check any billing or usage pages.
- Undo damage. Remove unknown links and correct anything that was edited.
- Find the route. Was it a commit, a log, a screenshot? Close that route so the new key does not go the same way.
- Clean up history if you wish, but do not rely on it. Rewriting Git history removes the key from your repository, not from clones, forks or caches made in the meantime. Revocation is the step that actually protects you.
Do the steps in that order. People often spend an hour scrubbing a repository while the exposed key is still live.
How can tools catch mistakes before they ship?
Automation is better at spotting key-shaped strings than tired people are.
- Secret scanning on your code host checks pushes for strings that look like credentials. A recognisable prefix helps here, which is one reason keys carry prefixes like
uz_live_. - Pre-commit hooks run a scanner locally, so a key is caught before it is ever committed.
- Log redaction in your HTTP client or logging library should mask the
Authorizationheader by default. - Code review should treat any long random string in a diff as a question to be asked.
None of this replaces the basic rule: the key is read from the environment on a server you control, and nowhere else. For how keys are used in requests, see the URL shortener API getting-started guide and the API documentation.
Frequently asked questions
- Where should I store an API key?
- On the server, outside your source code: in an environment variable for local work, and in your hosting platform's secret settings or a dedicated secrets manager in production. Never in a Git repository, front-end bundle or mobile app.
- Is it safe to use an API key in front-end JavaScript?
- No. Anything sent to a browser can be read by its user, including keys in bundled code and in network requests. Keep the key on your server and have the front end call your own endpoint.
- What should I do if I committed an API key to GitHub?
- Revoke the key immediately and create a new one. Deleting the commit is not enough, because the key remains in the repository's history and may already have been copied. Then check your account for activity you did not make.
- How often should API keys be rotated?
- Rotate immediately after any suspected exposure and whenever someone with access leaves. Beyond that, a regular schedule such as every few months limits how long an unnoticed leak stays useful; choose an interval you will actually keep to.