673 B
673 B
tags | created | |
---|---|---|
|
Saturday, August 09, 2025 |
Add API key authorization Express
Basically you add it as a piece of middlewear:
// auth.js
const validateApiKey = (req, res, next) => {
const apiKey = req.headers["x-api-key"];
if (!apiKey) {
return res.status(401).json({
error: "API key is required.",
});
}
if (apiKey !== process.env.API_KEY) {
return res.status(403).json({ error: "Invalid API key" });
}
next();
};
export { validateApiKey };
And then apply it to all routes, e.g.:
import { validateApiKey } from "./middlewear/auth.js";
app.use("/", validateApiKey);