Node.js and Express
Node.js runs JavaScript outside the browser. Express is the most common minimal web framework on top of it.
Hello server
npm init -y
npm install express
const express = require("express");
const app = express();
app.use(express.json()); // parse JSON bodies
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on ${port}`));
Routing
const notes = [];
app.get("/notes", (req, res) => res.json(notes));
app.post("/notes", (req, res) => {
const { text } = req.body;
if (!text) return res.status(400).json({ error: "text is required" });
const note = { id: notes.length + 1, text };
notes.push(note);
res.status(201).json(note);
});
app.get("/notes/:id", (req, res) => {
const note = notes.find((n) => n.id === Number(req.params.id));
if (!note) return res.status(404).json({ error: "not found" });
res.json(note);
});
Middleware
Middleware are functions (req, res, next) that run in order.
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}
function requireAuth(req, res, next) {
if (!req.headers.authorization) return res.status(401).end();
next();
}
app.use(logger);
app.get("/private", requireAuth, (req, res) => res.json({ ok: true }));
Error handling
// must have 4 parameters
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "internal server error" });
});
Project structure
src/
server.js entry point
routes/ route definitions
controllers/ request handling
services/ business logic
models/ data access
middleware/ auth, validation, logging
.env configuration (not committed)
Essentials for production
- Read configuration from environment variables.
- Validate input (for example with Zod or Joi).
- Use
helmetfor secure headers,corswith an allow-list, and rate limiting. - Log in a structured format and handle uncaught errors.
Loading Comments...