Guided Notes

Middleware, Authentication & Error Handling

How Express middleware works, writing logging/auth middleware, the order of middleware, async errors, security middleware, and graceful error responses.

What middleware is

Slide 1 / 5

Middleware are functions that run in order for each request: (req, res, next) => { … }. Each can: • read or modify req/res (add req.user), • end the request (res.status(401).json(...)), • or call next() to pass control to the next middleware/route.

app.use(logger); app.use(express.json()); app.use("/api", requireAuth); app.use("/api/notes", notesRouter); app.use(notFound); app.use(errorHandler); // (err, req, res, next)

← Building a REST API with Express