Sequence NODE_247
MediumImplement Simple API Key Authentication
Express.js
Node.js
Technical Specification
Create middleware that checks for an API key in headers (x-api-key) and rejects requests if it's missing or incorrect.
Input/Output Samples
Input:No x-api-key header
Output:401 Unauthorized
Optimal Logic Path
const API_KEY = process.env.API_KEY || "secret123";
function apiKeyAuth(req, res, next) {
const key = req.header("x-api-key");
if (!key || key !== API_KEY) {
return res.status(401).json({ error: "Unauthorized" });
}
next();
}
// Protect routes:
app.use("/admin", apiKeyAuth);Architectural Deep-Dive
API key middleware allows simple token-based protection for specific routes or groups.