API Authentication: Pick the Right Method
Every API needs authentication, but there are many ways to do it. The right choice depends on who's calling your API (users vs servers) and what security guarantees you need.
Method Comparison
| Method | Best For | Stateless? | Complexity |
|---|---|---|---|
| API Keys | Server-to-server, public APIs | Yes | Low |
| JWT (Bearer Token) | SPAs, mobile apps, microservices | Yes | Medium |
| Session Cookies | Traditional web apps (SSR) | No (server-side state) | Low |
| OAuth 2.0 | Third-party access, social login | Depends | High |
| Basic Auth | Internal tools, debugging | Yes | Lowest |
API Keys
// Client sends key in header
GET /api/data HTTP/1.1
X-API-Key: sk_live_abc123def456
// Server validates
app.use((req, res, next) => {
const key = req.headers['x-api-key'];
const client = await db.apiKeys.findByKey(key);
if (!client) return res.status(401).json({ error: 'Invalid API key' });
req.client = client;
next();
});Pros: simple, no expiration management. Cons: if leaked, access until revoked. Not user-specific.
JWT Bearer Tokens
// Client sends token in Authorization header
GET /api/profile HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
// Server validates and extracts user info
import jwt from 'jsonwebtoken';
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.replace('Bearer ', '');
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
req.user = payload;
next();
} catch {
res.status(401).json({ error: 'Invalid or expired token' });
}
}Pros: stateless, scalable, carries user info. Cons: can't revoke individual tokens (without a blacklist).
Session Cookies
// Server creates session on login
app.post('/login', async (req, res) => {
const user = await authenticate(req.body);
req.session.userId = user.id;
res.json({ message: 'Logged in' });
});
// Browser automatically sends cookie
// Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=StrictPros: automatic (browser handles it), HttpOnly prevents XSS theft, easy to invalidate. Cons: requires server-side session store, CSRF protection needed, doesn't work well for mobile/SPAs.
When to Use What
| Scenario | Recommended |
|---|---|
| Public API for developers | API Keys |
| SPA calling your own API | JWT + Refresh Token |
| Server-rendered web app | Session Cookies |
| Mobile app | JWT + Refresh Token |
| "Login with Google" | OAuth 2.0 |
| Microservice to microservice | JWT or mTLS |
| Quick internal tool | Basic Auth (over HTTPS) |
Security Essentials
- Always use HTTPS. Any auth method is insecure over HTTP.
- Store secrets properly. API keys in env vars, tokens in httpOnly cookies or secure storage.
- Implement rate limiting on auth endpoints to prevent brute force.
- Short-lived tokens with refresh tokens > long-lived tokens.
- Log auth events — failed logins, token refreshes, key creation.
Decode your tokens: JWT Decoder — inspect token claims, expiration, and signatures.