Notes › Web Development
Node.js and Express — Building a REST API
Node.js runs JavaScript outside the browser, on the V8 engine, with a non-blocking event loop — great for I/O-heavy servers (APIs, chat, streaming). Express is the most popular minimal web framework for Node.
Node basics
npm init -y # creates package.json
npm install express # dependency
npm install -D nodemon # dev dependency (auto-restart)
// ES modules: add "type": "module" in package.json
import fs from "fs/promises";
const text = await fs.readFile("notes.txt", "utf8");
// built-in modules: fs, path, http, os, events, crypto
// process.env.PORT for configuration
Node is single-threaded for your JavaScript but does I/O in the background — see The JavaScript Event Loop.
A minimal Express server
import express from "express";
const app = express();
app.use(express.json()); // parse JSON request bodies
app.get("/", (req, res) => res.send("Hello"));
app.listen(process.env.PORT || 5000, () => console.log("Server running"));
REST principles
Resources are nouns; HTTP methods are the verbs.
| Method | Route | Action | Success status |
|---|---|---|---|
| GET | /api/courses |
list | 200 |
| GET | /api/courses/:id |
get one | 200 |
| POST | /api/courses |
create | 201 |
| PUT / PATCH | /api/courses/:id |
replace / update | 200 |
| DELETE | /api/courses/:id |
delete | 200 or 204 |
Full CRUD example
const router = express.Router();
let courses = [{ id: 1, title: "DSA" }];
router.get("/", (req, res) => {
const { q } = req.query; // /api/courses?q=dsa
res.json(q ? courses.filter((c) => c.title.toLowerCase().includes(q)) : courses);
});
router.get("/:id", (req, res) => {
const c = courses.find((x) => x.id === Number(req.params.id));
if (!c) return res.status(404).json({ message: "Course not found" });
res.json(c);
});
router.post("/", (req, res) => {
const { title } = req.body;
if (!title) return res.status(400).json({ message: "Title is required" });
const c = { id: Date.now(), title };
courses.push(c);
res.status(201).json(c);
});
router.put("/:id", (req, res) => {
const c = courses.find((x) => x.id === Number(req.params.id));
if (!c) return res.status(404).json({ message: "Course not found" });
c.title = req.body.title ?? c.title;
res.json(c);
});
router.delete("/:id", (req, res) => {
courses = courses.filter((x) => x.id !== Number(req.params.id));
res.json({ message: "Deleted" });
});
app.use("/api/courses", router);
req.params → URL parts (:id), req.query → ?key=value, req.body → JSON body.
Middleware
A function (req, res, next) that runs before the route handler. It can read/modify the request, end the response, or call next().
const logger = (req, res, next) => {
console.log(req.method, req.url);
next();
};
app.use(logger); // every request
const requireAdmin = (req, res, next) =>
req.user?.role === "admin" ? next() : res.status(403).json({ message: "Admins only" });
router.delete("/:id", requireAdmin, handler); // one route
Common middleware: express.json(), cors(), helmet() (security headers), morgan (logging), rate limiting, authentication.
Error handling
// wrap async handlers so thrown errors reach the error middleware (Express 5 does this itself)
const asyncHandler = (fn) => (req, res, next) => fn(req, res, next).catch(next);
app.use((req, res) => res.status(404).json({ message: "Route not found" }));
app.use((err, req, res, next) => { // 4 arguments = error middleware
console.error(err);
res.status(err.status || 500).json({ message: err.message || "Server error" });
});
Status codes to know
| Code | Meaning |
|---|---|
| 200 / 201 / 204 | OK / Created / No Content |
| 400 | Bad Request (invalid input) |
| 401 | Unauthorized (not logged in) |
| 403 | Forbidden (logged in, not allowed) |
| 404 | Not Found |
| 409 | Conflict (e.g. email already used) |
| 429 | Too Many Requests |
| 500 | Internal Server Error |
Project structure
server/
src/
index.js app setup, middleware, routes
routes/ courses.js, auth.js
controllers/ request handling logic (optional layer)
models/ Mongoose schemas
middleware/ auth.js, error.js
utils/
.env secrets (never commit)
Interview one-liners
- Node is single-threaded with non-blocking I/O; CPU-heavy work blocks it.
- Middleware runs in the order it is added;
next()passes control on. - PUT replaces a resource, PATCH updates part of it.
- Keep secrets in environment variables; validate every input on the server.
- Next: MongoDB and Mongoose, Authentication — JWT, Sessions and Cookies, Node.js docs.