If you're building an API in Express.js and plan to expose it publicly — maybe to clients, third-party devs, or internal tools — you need some way to control access.
One of the most common and effective ways to do this is using API keys.
In this post, I’ll walk you through a simple way to implement API key protection in your Express API. No fancy gateways, no unnecessary bloat — just straightforward logic you can build on.
🚧 Why API Keys?
API keys are unique tokens (usually strings) that your users include in their requests. You can:
- Identify who's calling your API.
- Set limits (like 1,000 requests per day).
- Revoke keys if needed.
- Analyze usage by key/project/client.
Perfect for public or semi-public APIs that don’t need full OAuth complexity.
🛠️ Basic API Key Middleware in Express
Here’s a minimal implementation:
// middleware/apiKey.js
const validApiKeys = [
'abc123', // In real use, store these in a DB
'def456',
];
export function apiKeyMiddleware(req, res, next) {
const apiKey = req.header('x-api-key');
if (!apiKey || !validApiKeys.includes(apiKey)) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
}
And in your Express app:
import express from 'express';
import { apiKeyMiddleware } from './middleware/apiKey.js';
const app = express();
app.use('/api', apiKeyMiddleware);
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello, world!' });
});
app.listen(3000, () => console.log('Server running on port 3000'));
🧠 A Few Tips
- Store API keys in a database (with metadata like usage, owner, status).
- Add rate limiting to prevent abuse.
- Consider rotating keys over time.
- Log each request to track usage per key.
⚡ Want to Skip the Boilerplate?
If you don’t want to build all this from scratch, you can use a tool like Limitly — it handles API key creation, validation, usage limits (daily, weekly, etc.), and request tracking with an SDK you can plug into your Express app.
I built it because I was tired of reinventing this every time I launched an API.
Let me know if you use a different method or have feedback — always happy to learn new approaches!
Top comments (0)