Express.js Middleware Cheatsheet

Quick reference for built-in, third-party, custom, and error-handling middleware in Express.js.

MiddlewareDescriptionExampleCategory
express.json()Parse JSON request bodiesapp.use(express.json());Built-in
express.urlencoded()Parse URL-encoded bodiesapp.use(express.urlencoded({ extended: true }));Built-in
express.static()Serve static filesapp.use(express.static("public"));Built-in
corsEnable Cross-Origin Resource Sharingimport cors from "cors"; app.use(cors());Third-Party
morganHTTP request loggerimport morgan from "morgan"; app.use(morgan("dev"));Third-Party
helmetSecure HTTP headersimport helmet from "helmet"; app.use(helmet());Third-Party
cookie-parserParse cookiesimport cookieParser from "cookie-parser"; app.use(cookieParser());Third-Party
body-parserParse request bodiesimport bodyParser from "body-parser"; app.use(bodyParser.json());Third-Party
Custom LoggerLog request infoapp.use((req,res,next)=>{console.log(req.method, req.url); next();});Custom
Auth MiddlewareCheck authenticationapp.use((req,res,next)=>{if(req.user) next(); else res.status(401).send("Unauthorized");});Custom
Error HandlerCatch errorsapp.use((err, req, res, next)=>{console.error(err); res.status(500).send("Server Error");});Error Handling