Express Basics
Express is a minimal web framework for Node. It handles routing, request parsing, and middleware so you do not have to.
Install and Start
npm install express
import express from "express";
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.send("Hello, Express!");
});
app.listen(3000, () => console.log("http://localhost:3000"));
express.json() parses JSON bodies into req.body.
Routes
A route matches an HTTP method and a path:
app.get("/users", (req, res) => res.json([]));
app.post("/users", (req, res) => res.status(201).json(req.body));
app.put("/users/:id", (req, res) => res.json({ id: req.params.id }));
app.delete("/users/:id", (req, res) => res.status(204).end());
:idis a route parameter, read fromreq.params.- Query strings come from
req.query.
app.get("/search", (req, res) => {
res.json({ q: req.query.q ?? "" });
});
Middleware
Middleware are functions that run in order before your handler. Each one can read or change the request, or stop the chain:
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next(); // pass control to the next handler
}
app.use(logger);
Order matters — middleware runs top to bottom.
Sending Responses
res.send("text"); // string or Buffer
res.json({ ok: true }); // JSON + Content-Type
res.status(404).json({ error: "Not found" });
res.redirect("/login");
Error Handling
Express catches errors passed to next:
app.get("/boom", (req, res, next) => {
next(new Error("Something broke"));
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
});
The error handler must have four arguments.
Best Practices
- Organize routes with
express.Router()— Keep files small. - Validate input — Never trust
req.body. - Use a central error handler — One place to log and respond.
- Add security middleware —
helmet, CORS, rate limits.
Common Mistakes
- Forgetting
express.json()—req.bodyisundefined. - Putting routes after the 404 handler — They never run.
- Three-argument error handlers — Express needs four.
- Not calling
next()— The request hangs.