Express.js
Express.js is a minimal web framework for Node.js.
It gives you a clean way to:
- define routes (URLs)
- add middleware (code that runs before/after routes)
- send responses (HTML, JSON, files)
Install
Section titled “Install”npm install expressYour First Server
Section titled “Your First Server”import express from 'express';
const app = express();const port = 3000;
app.get('/', (req, res) => { res.send('Hello from Express!');});
app.listen(port, () => { console.log(`Server running at http://localhost:${port}`);});Routing (The Core Concept)
Section titled “Routing (The Core Concept)”A route matches a request by:
- HTTP method (GET/POST/PUT/PATCH/DELETE)
- path (like
/users)
Examples:
app.get('/health', (req, res) => res.json({ ok: true }));
app.post('/users', (req, res) => { res.status(201).json({ message: 'User created' });});Route Parameters (:id)
Section titled “Route Parameters (:id)”Use route params when you want to address one specific resource.
app.get('/users/:id', (req, res) => { const { id } = req.params; res.json({ id, name: 'Example' });});Request:
GET /users/42
req.params:
{ "id": "42" }Query Parameters (?search=...)
Section titled “Query Parameters (?search=...)”Use query params for filtering, sorting, pagination.
app.get('/users', (req, res) => { const { role, page = '1' } = req.query; res.json({ role, page });});Request:
GET /users?role=admin&page=2
Request / Response Objects
Section titled “Request / Response Objects”Every route handler receives:
req(request): incoming datares(response): what you send back
Common things you use:
app.get('/info', (req, res) => { res.json({ method: req.method, path: req.path, headers: req.headers, });});JSON APIs (Reading the Request Body)
Section titled “JSON APIs (Reading the Request Body)”To read JSON bodies, you need the JSON middleware:
app.use(express.json());
app.post('/echo', (req, res) => { res.json({ youSent: req.body });});Middleware
Section titled “Middleware”Middleware is a function that runs during request processing.
It can:
- log requests
- check auth
- attach data to
req - stop the request with a response
- or pass control to the next handler
Logging Middleware Example
Section titled “Logging Middleware Example”app.use((req, res, next) => { console.log(`${req.method} ${req.path}`); next();});Route-Specific Middleware Example
Section titled “Route-Specific Middleware Example”function requireApiKey(req, res, next) { if (req.headers['x-api-key'] !== 'secret') { return res.status(401).json({ error: 'Unauthorized' }); } next();}
app.get('/private', requireApiKey, (req, res) => { res.json({ secretData: 123 });});Routers (Organizing Routes)
Section titled “Routers (Organizing Routes)”As your API grows, you usually group routes into a router.
Example:
import express from 'express';
const usersRouter = express.Router();
usersRouter.get('/', (req, res) => res.json([{ id: 1, name: 'Alice' }]));usersRouter.get('/:id', (req, res) => res.json({ id: req.params.id }));
export default usersRouter;Then mount it:
import usersRouter from './routes/users.js';
app.use('/users', usersRouter);This creates:
GET /usersGET /users/:id
Status Codes (Quick Examples)
Section titled “Status Codes (Quick Examples)”res.status(200).json({ ok: true });res.status(201).json({ created: true });res.status(404).json({ error: 'Not found' });Error Handling (Simple Pattern)
Section titled “Error Handling (Simple Pattern)”Express treats a function with four arguments as an error handler.
app.get('/boom', (req, res) => { throw new Error('Something broke');});
app.use((err, req, res, next) => { console.error(err); res.status(500).json({ error: 'Internal Server Error' });});Serving Static Files
Section titled “Serving Static Files”If you have a folder like public/, you can serve files from it:
app.use(express.static('public'));Then public/logo.png becomes:
GET /logo.png
Where Express Is Used
Section titled “Where Express Is Used”- REST APIs for web and mobile apps
- Backend-for-frontend (BFF) servers
- Prototypes and small-to-medium backends (and sometimes parts of larger systems)
Industry examples (companies using Node/Express-style backends):
- Netflix: has used Node.js widely for web services
- PayPal: early well-known Node.js adoption for web apps
- Uber: uses Node.js for various services
Related Frameworks (Mentions)
Section titled “Related Frameworks (Mentions)”- NestJS: A more structured Node.js framework (TypeScript-first) inspired by Angular.