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.

Languages·45 commands·Last updated 2026-07-21
expressnodeweb

App Setup 5

const app = express()
Create the app instance
app.use(express.json())
Mount global middleware (parse JSON body)
app.listen(3000, () => {})
Listen on a port to start the server
const router = express.Router()
Create a mountable router
app.set("port", process.env.PORT || 3000)
Set app config

Route Definition 7

app.get("/users", handler)
GET route
app.post("/users", handler)
POST route
app.put("/users/:id", handler)
PUT route, :id is a param
app.delete("/users/:id", handler)
DELETE route
app.all("/api/*", handler)
Catch-all route matching any method
app.use("/api", router)
Mount a sub-router module
router.route("/users").get(list).post(create)
Chainable route definition

Request Object 6

req.params.id
URL route params
req.query.page
Query string params
req.body.name
Request body (needs express.json())
req.headers["content-type"]
Request headers
req.cookies.token
Cookie (needs cookie-parser)
req.get("User-Agent")
Get a specific request header

Response Object 6

res.send("hello")
Send a text response
res.json({ data })
Return JSON
res.status(201).json({ ok: true })
Set status code and return JSON
res.redirect("/login")
Redirect
res.sendFile(path.join(__dirname, "index.html"))
Send a file
res.set("X-Custom", "value")
Set a response header

Common Middleware 8

app.use((req, res, next) => { next() })
Custom middleware
express.urlencoded({ extended: true })
Parse URL-encoded form bodies
app.use("/static", express.static("public"))
Serve static files
cors()
CORS middleware
helmet()
Security HTTP headers middleware
morgan("dev")
Request logging middleware
cookie-parser()
Parse cookies
compression()
Response compression middleware

Template Engines & JWT 6

app.set("view engine", "ejs")
Set the template engine
app.set("views", path.join(__dirname, "views"))
Set the views directory
res.render("index", { title: "Home" })
Render a template and respond
jwt.sign(payload, secret, { expiresIn: "1h" })
Sign a JWT token
jwt.verify(token, secret)
Verify a JWT token
req.headers.authorization
Read the Bearer token from the Authorization header

Error Handling & Patterns 7

const wrap = (fn) => (req, res, next) => fn(req, res, next).catch(next)
Async error wrapper that auto-catches async errors
app.use((req, res) => res.status(404).send("Not Found"))
404 fallback handler
app.use((err, req, res, next) => res.status(500).json({ error: err.message }))
Global error-handling middleware (must have 4 args)
next(err)
Pass an error to the error middleware
process.on("uncaughtException", handler)
Catch uncaught exceptions
process.on("unhandledRejection", handler)
Catch unhandled Promise rejections
module.exports = router
Export the router for app.use to mount

Tips

  • 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