38 lines
673 B
Markdown
38 lines
673 B
Markdown
|
---
|
||
|
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);
|
||
|
```
|