Middleware
Middleware are functions that run between the request arriving and the response being sent. They can read or change the request, end it early, or call next() to pass it on. Use them for logging, parsing JSON, auth checks, and more.
import express from "express"
const app = express()
app.use(express.json()) // built-in: parse JSON bodies
// Custom logger
app.use((req, res, next) => {
console.log(req.method, req.url)
next() // pass to the next middleware
})
// Only on one route
function requireAuth(req, res, next) {
if (!req.headers.authorization) return res.status(401).send("Unauthorized")
next()
}
app.get("/profile", requireAuth, (req, res) => res.send("Secret"))