Quick Reference Express.js Cheatsheet
Express.js quick reference — setup, routing, params/query, middleware, request/response,
routers, errors, static files, body parsing, auth sketches, and colorized snippets.
import express from "express";
const app = express();
const PORT = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send("Hello Express");
});
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
}); app.get("/users", listUsers);
app.post("/users", createUser);
app.put("/users/:id", replaceUser);
app.patch("/users/:id", updateUser);
app.delete("/users/:id", deleteUser);
app.route("/books")
.get(listBooks)
.post(createBook);
app.all("/health", (req, res) => {
res.sendStatus(200);
}); app.get("/users/:id", (req, res) => {
const id = req.params.id;
res.json({ id });
});
app.get("/search", (req, res) => {
const q = req.query.q;
const page = Number(req.query.page || 1);
res.json({ q, page });
});
app.get("/files/:name", handler);
app.use(express.json());
app.use(logger);
function logger(req, res, next) {
console.log(req.method, req.url);
next();
}
app.use("/api", apiKeyGuard);
req.method; req.url; req.path; req.hostname;
req.headers["authorization"];
req.params; req.query; req.body;
req.cookies; req.ip;
res.status(201).json({ ok: true });
res.send("text");
res.sendStatus(204);
res.redirect(302, "/login");
res.type("html").send("<h1>Hi</h1>");
res.set("X-Request-Id", "abc");
res.cookie("sid", "1", { httpOnly: true });
res.download("./report.pdf");
import { Router } from "express";
const router = Router();
router.get("/", (req, res) => {
res.json([]);
});
router.get("/:id", (req, res) => {
res.json({ id: req.params.id });
});
export default router;
import users from "./routes/users.js";
app.use("/users", users);
app.get("/boom", async (req, res, next) => {
try {
throw new Error("Nope");
} catch (err) {
next(err);
}
});
app.use((req, res) => {
res.status(404).json({ error: "Not found" });
});
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500)
.json({ error: err.message || "Server error" });
}); import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
app.use(express.static(path.join(__dirname, "public"));
app.use("/assets", express.static("assets", {
maxAge: "1d",
index: false
})); app.use(express.json({ limit: "1mb" }));
app.use(express.urlencoded({ extended: true });
app.post("/users", (req, res) => {
const { name, email } = req.body;
res.status(201).json({ name, email });
});
function requireAuth(req, res, next) {
const hdr = req.get("authorization");
if (!hdr?.startsWith("Bearer ")) {
return res.status(401).json({ error: "Unauthorized" });
}
req.token = hdr.slice(7);
next();
}
app.get("/me", requireAuth, (req, res) => {
res.json({ token: req.token });
});
⚠️Gotchas & Interview Tips - Middleware order is everything — parsers and auth before routes that need them.
- Always call
next() or send a response; hanging requests = forgotten next/res. - Async route errors are not auto-caught — use try/catch or a wrapper →
next(err). - Error middleware must have four parameters or Express will not treat it as an error handler.
- Put 404 after routes; put error handler last.
req.query values are strings (or arrays) — coerce and validate. - Don't trust
req.body shape; validate (zod/joi) before using. - Prefer
Router modules over a single giant app.js.
Next: Express tutorial ·
Cheatsheet hub ·
Node.js |