Skip to content

Commit 260593d

Browse files
committed
feat: add off-the-shelf middleware example
1 parent 53374b3 commit 260593d

5 files changed

Lines changed: 979 additions & 0 deletions

File tree

middleware-off-the-shelf/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Off-the-shelf middleware example
2+
3+
This Express app replaces the custom logger with the `morgan` middleware.
4+
The `requireApiKey` middleware is still custom.
5+
6+
## Run locally
7+
8+
```bash
9+
npm install
10+
npm start
11+
```
12+
13+
Set a custom API key (optional):
14+
15+
```bash
16+
API_KEY=my-secret npm start
17+
```
18+
19+
## Try it
20+
21+
```bash
22+
curl http://localhost:3001/health
23+
curl http://localhost:3001/messages
24+
curl -X POST http://localhost:3001/messages \
25+
-H "Content-Type: application/json" \
26+
-H "x-api-key: cyf" \
27+
-d '{"user":"Azin","message":"Hello"}'
28+
```
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module.exports = function requireApiKey(req, res, next) {
2+
const expectedKey = process.env.API_KEY || "cyf";
3+
const providedKey = req.header("x-api-key");
4+
5+
if (providedKey !== expectedKey) {
6+
return res.status(401).json({ error: "Invalid API key" });
7+
}
8+
9+
next();
10+
};

0 commit comments

Comments
 (0)