Now let’s protect our POST route using the checkAuth middleware from Lesson 3. This shows how to apply security to write operations, though remember this is basic auth for learning purposes.
First, add the checkAuth function from Lesson 3:
function checkAuth(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: "Missing authorization header" });
}
if (authHeader !== "Bearer secret123") {
return res.status(403).json({ error: "Access denied" });
}
next();
}
Now apply it to the POST route:
// Protected POST route - requires authentication
app.post("/users", checkAuth, (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: "Name and email are required" });
}
const newId = Date.now();
const newUser: User = { id: newId, name, email };
users.push(newUser);
res.status(201).json(newUser);
});
Important: This is the same “Bearer secret123” approach from Lesson 3. This is not real security - it’s just for learning how middleware works with CRUD operations. Module 3 will cover proper authentication.
Testing: You’ll need to include the Authorization: Bearer secret123 header when testing this route.