eolas/zk/Add_API_key_authorization_Express.md

38 lines
673 B
Markdown
Raw Permalink Normal View History

2025-08-13 16:52:42 +01:00
---
tags: ["node-js"]
created: Saturday, August 09, 2025
---
# Add API key authorization Express
Basically you add it as a piece of [middlewear](./Middleware_in_NodeJS.md):
```js
// 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.:
```js
import { validateApiKey } from "./middlewear/auth.js";
app.use("/", validateApiKey);
```