Express.js Cheatsheet - Express Middleware & API Reference
This reference is for Node.js developers building REST APIs and web apps on Express, from a small internal service to a full EJS-rendered site. It covers the app/router setup, defining routes with params/query, reading the request and shaping the response, wiring the middleware ecosystem (express.json, static, cors, helmet, morgan, compression), serving EJS views, adding JWT auth, and the async error-handling pattern. Unlike a generic Express snippet list, entries are grouped by the layer of the request lifecycle you are working on. After reading you should be able to stand up an app, mount routers and middleware in the right order, and centralize async error handling instead of scattering try/catch.
App Setup 5
const app = express()app.use(express.json())app.listen(3000, () => {})const router = express.Router()app.set("port", process.env.PORT || 3000)Route Definition 7
app.get("/users", handler)app.post("/users", handler)app.put("/users/:id", handler)app.delete("/users/:id", handler)app.all("/api/*", handler)app.use("/api", router)router.route("/users").get(list).post(create)Request Object 6
req.params.idreq.query.pagereq.body.namereq.headers["content-type"]req.cookies.tokenreq.get("User-Agent")Response Object 6
res.send("hello")res.json({ data })res.status(201).json({ ok: true })res.redirect("/login")res.sendFile(path.join(__dirname, "index.html"))res.set("X-Custom", "value")Common Middleware 8
app.use((req, res, next) => { next() })express.urlencoded({ extended: true })app.use("/static", express.static("public"))cors()helmet()morgan("dev")cookie-parser()compression()Template Engines & JWT 6
app.set("view engine", "ejs")app.set("views", path.join(__dirname, "views"))res.render("index", { title: "Home" })jwt.sign(payload, secret, { expiresIn: "1h" })jwt.verify(token, secret)req.headers.authorizationError Handling & Patterns 7
const wrap = (fn) => (req, res, next) => fn(req, res, next).catch(next)app.use((req, res) => res.status(404).send("Not Found"))app.use((err, req, res, next) => res.status(500).json({ error: err.message }))next(err)process.on("uncaughtException", handler)process.on("unhandledRejection", handler)module.exports = routerTips
- Middleware order matters: body-parsers must come before routes, and error middleware must be last.
- Error-handling middleware needs 4 args (err, req, res, next), or Express won't recognize it.
- In production, use helmet() for security headers and configure cors() whitelist as needed.
- express.static can serve multiple directories, searched in order.
- Routers modularize routes; mount sub-routes with app.use('/api', router).
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us