Create API key authentication system
✓Works with OpenClaudeYou are a backend authentication engineer. The user wants to create a complete API key authentication system with generation, validation, storage, and rate limiting.
What to check first
- Verify you have a database setup (PostgreSQL/MongoDB) with write permissions
- Run
npm list express dotenv bcryptto confirm authentication dependencies are installed - Check that your environment supports storing secrets (
.envfile or secrets manager)
Steps
- Create an API keys table with columns:
id,key_hash,user_id,name,created_at,last_used,is_active,rate_limit - Generate cryptographically secure random keys using
crypto.randomBytes(32).toString('hex') - Hash keys before storage using bcrypt with salt rounds of 10 to prevent plaintext exposure
- Create middleware to extract API key from
Authorization: Bearer <key>header - Implement key validation by hashing the incoming key and comparing against stored hash
- Add rate limiting per API key using in-memory store or Redis with sliding window counters
- Track
last_usedtimestamp on every successful authentication for audit trails - Return proper HTTP status codes: 401 for missing/invalid keys, 429 for rate limit exceeded
Code
import express from 'express';
import crypto from 'crypto';
import bcrypt from 'bcrypt';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
// In-memory rate limit store (use Redis in production)
const rateLimitStore = new Map();
// Simulated database (replace with real DB client)
const apiKeysDb = new Map();
// Generate new API key
export async function generateApiKey(userId, keyName) {
const rawKey = crypto.randomBytes(32).toString('hex');
const keyHash = await bcrypt.hash(rawKey, 10);
const keyRecord = {
id: crypto.randomUUID(),
key_hash: keyHash,
user_id: userId,
name: keyName,
created_at: new Date(),
last_used: null,
is_active: true,
rate_limit: 1000 // requests per hour
};
// Store hashed key in database
apiKeysDb.set(keyRecord.id, keyRecord);
// Return raw key ONLY on creation (never again)
return {
key_id: keyRecord.id,
api_key: rawKey, // Show once to user
key_name: keyName,
created_at: keyRecord.created_at
};
}
// Validate API key middleware
export async function validateApiKey(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing API key' });
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Authentication Skills
Other Claude Code skills in the same category — free to download.
JWT Auth
Implement JWT authentication from scratch
OAuth Setup
Set up OAuth 2.0 with multiple providers
NextAuth Setup
Configure NextAuth.js/Auth.js
Passport Setup
Set up Passport.js with strategies
Magic Link Auth
Implement passwordless magic link auth
Two Factor Auth
Add 2FA/MFA to authentication flow
Session Management
Implement secure session management
SSO Setup
Set up Single Sign-On (SAML/OIDC)
Want a Authentication skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.