Appearance
Express Basics
1. What is Express.js, and why is it used?
The short answer
Express is a small, unopinionated web framework for Node.js. It gives you routing, which maps a URL and HTTP method to a function, a middleware system for reusable steps such as parsing JSON or checking authentication, and helpers on the request and response objects. It is used because it is simple, stable, flexible and has the largest ecosystem of middleware, so most Node.js APIs and many other frameworks are built on it or on its ideas. Express 5 is the current major version.
A complete small API:
ts
import express from 'express'
const app = express()
app.use(express.json()) // (1)
const products = new Map([['tea', { sku: 'tea', name: 'Earl Grey', pricePence: 450 }]])
app.get('/products/:sku', (req, res) => { // (2)
const product = products.get(req.params.sku)
if (!product) return res.status(404).json({ error: 'not_found' })
res.json(product) // (3)
})
app.post('/products', (req, res) => {
const { sku, name, pricePence } = req.body // (4)
products.set(sku, { sku, name, pricePence })
res.status(201).json(products.get(sku))
})
app.listen(3000, () => console.log('API on :3000'))- Middleware that parses JSON bodies for every request.
- A route: the
GETmethod, a path with a parameter, and a handler. res.jsonsets the content type, turns the object into JSON and sends it.- The parsed body, ready to use. It still needs validation before being trusted (question 64).
Where Express sits among Node.js frameworks:
| Framework | Character |
|---|---|
| Express | Minimal, flexible, the most common |
| Fastify | Faster, schema-based validation and serialisation built in |
| NestJS | Structured, Angular-like, uses Express or Fastify underneath |
| Koa, Hono | Small, modern, middleware-focused |
Express 5, released in late 2024 and the default on npm since 2025, forwards errors from async handlers automatically, tightens route path syntax, and removes old deprecated APIs (question 33).
2. What problem does Express solve compared with the built-in Node.js HTTP module?
The short answer
The built-in http module gives you a raw request and response and nothing else: you must parse the URL and query string yourself, match paths and methods by hand, read and parse the body from a stream, set headers and status codes manually, and organise shared steps such as logging or authentication yourself. Express adds routing with parameters, a middleware pipeline, body parsing, convenient response helpers like res.json and res.status, static files, and error handling, so you write business logic instead of plumbing.
The same endpoint, both ways:
ts
// Plain node:http
import { createServer } from 'node:http'
createServer(async (req, res) => {
const url = new URL(req.url!, `http://${req.headers.host}`)
const match = url.pathname.match(/^\/orders\/([^/]+)$/) // (1)
if (req.method === 'GET' && match) {
const order = await getOrder(match[1])
res.writeHead(order ? 200 : 404, { 'Content-Type': 'application/json' }) // (2)
res.end(JSON.stringify(order ?? { error: 'not_found' }))
return
}
res.writeHead(404).end()
}).listen(3000)
// Express
app.get('/orders/:id', async (req, res) => {
const order = await getOrder(req.params.id) // (3)
if (!order) return res.status(404).json({ error: 'not_found' })
res.json(order)
})- Manual routing with a regular expression for each path.
- Manual headers and serialisation.
- Express does both:
:idis captured for you, andres.jsonhandles headers and JSON.
| Concern | node:http | Express |
|---|---|---|
| Routing with parameters | By hand | app.get('/orders/:id') |
| Shared steps: logging, auth | By hand | Middleware (question 15) |
| JSON body | Read the stream, parse, handle errors | express.json() |
| Responses | writeHead, end, JSON.stringify | res.status().json() |
| Errors | Try/catch everywhere | Central error middleware (question 35) |
3. What are the core features of Express?
The short answer
Express's core features are routing by method and path, with parameters and modular routers; a middleware pipeline that every request passes through in order; request and response helpers, such as req.params, req.query, res.json, res.status and res.redirect; built-in middleware for JSON, form bodies and static files; centralised error-handling middleware; template rendering for server-side HTML; and application settings such as trust proxy. Everything else, such as security headers, CORS or validation, comes from separate middleware packages.
| Feature | Example |
|---|---|
| Routing | app.get('/orders/:id', handler) (question 7) |
| Routers | express.Router() for groups of routes (question 8) |
| Middleware | app.use(requestLogger) (question 15) |
| Body parsing | express.json(), express.urlencoded() (question 6) |
| Static files | express.static('public') |
| Response helpers | res.json, res.status, res.sendFile, res.redirect, res.cookie |
| Error middleware | app.use((err, req, res, next) => …) (question 32) |
| Settings | app.set('trust proxy', 1) (question 28) |
| View rendering | res.render('invoice', data) with a template engine |
What Express deliberately does not include: validation, authentication, database access, security headers, CORS, rate limiting and a project structure. Being unopinionated is its strength and its weakness: you choose every piece, and you must choose well.
4. What do app.listen() and app.use() do?
The short answer
app.listen(port) creates a Node.js HTTP server with your Express app as its request handler and starts listening on that port; it returns the underlying server, which you keep for graceful shutdown. app.use(fn) adds middleware that runs for every request, in the order you add it, or only for paths that start with a given prefix if you pass one, such as app.use('/api', apiRouter). It is how you plug in body parsers, loggers, routers and error handlers.
ts
const app = express()
app.use(requestLogger) // (1) every request
app.use(express.json({ limit: '100kb' })) // (2)
app.use('/api/orders', ordersRouter) // (3) only paths under /api/orders
app.use(notFoundHandler) // (4)
app.use(errorHandler) // (5)
const server = app.listen(3000, () => logger.info('listening on :3000')) // (6)
process.once('SIGTERM', () => server.close())- No path: runs for every request.
- Order matters: the body must be parsed before routes read
req.body. - A mount path: the router sees paths relative to
/api/orders, so itsrouter.get('/:id')matches/api/orders/42. - A catch-all for anything no route handled, returning
404. - The error handler goes last (question 32).
listenreturns the HTTP server, needed for graceful shutdown (the graceful shutdown question).
app.use versus app.get: app.use('/api', fn) matches any method and any path starting with /api. app.get('/api', fn) matches only GET requests to exactly /api.
5. What are the request and response objects in Express?
The short answer
They are Node.js's own IncomingMessage and ServerResponse objects, extended by Express with useful properties and methods. The request, req, describes what the client sent: req.params, req.query, req.body, req.headers, req.method, req.path, req.ip and cookies with a parser. The response, res, is how you answer: res.status(), res.json(), res.send(), res.set(), res.cookie(), res.redirect() and res.sendFile(). Every handler and middleware receives the same two objects for a request.
req | Gives you |
|---|---|
req.params | Path parameters, /orders/:id → { id } |
req.query | Query string, ?page=2 → { page: '2' } |
req.body | Parsed body, once a body parser has run |
req.get('Authorization') | A header, case-insensitive |
req.method, req.path, req.originalUrl | What was asked for |
req.ip, req.protocol, req.secure | Client details, correct only with trust proxy set right (question 28) |
res | Does |
|---|---|
res.status(201) | Sets the status code, returns res for chaining |
res.json(obj) | Sends JSON with the right content type |
res.send(text) | Sends a string or Buffer |
res.set('Cache-Control', 'no-store') | Sets a header |
res.cookie(name, value, options) | Sets a cookie |
res.redirect(302, '/login') | Redirects |
res.locals | Data for this request's later middleware and views (question 27) |
Send one response only. Calling res.json twice, or after next(err), throws "Cannot set headers after they are sent". It usually means a missing return:
ts
if (!order) res.status(404).json({ error: 'not_found' }) // missing return
res.json(order) // runs too: error6. What do express.json(), express.urlencoded(), and express.static() do?
The short answer
They are Express's built-in middleware. express.json() reads request bodies sent as application/json and puts the parsed object on req.body. express.urlencoded() does the same for HTML form posts sent as application/x-www-form-urlencoded. express.static(folder) serves files from a folder, such as images, CSS and a built front end, with correct content types and caching headers. Give the body parsers a size limit, so nobody can send a huge body to exhaust memory.
ts
app.use(express.json({ limit: '100kb' })) // (1)
app.use(express.urlencoded({ extended: false, limit: '50kb' })) // (2)
app.use('/assets', express.static('public/assets', { // (3)
maxAge: '1y',
immutable: true,
index: false,
}))- JSON bodies up to 100 KB. Larger bodies get
413 Payload Too Large. Invalid JSON gives a400error that your error handler should turn into a clean response. - Form bodies.
extended: false, the Express 5 default, uses the simplequerystringparser rather than nested-object parsing. - Static files under
/assets, cached for a year because the file names contain content hashes.index: falsestops it serving directory index files.
Things to know:
| Point | Detail |
|---|---|
| Content type must match | express.json() ignores a body sent as text/plain, leaving req.body empty |
| Express 5 change | req.body is undefined, not {}, when no parser handled the request |
| Static files in production | Often better served by Nginx or a CDN (the Vite deployment question) |
| Uploads | Neither parser handles multipart/form-data; use Multer (the Multer question) |
7. What is routing in Express?
The short answer
Routing decides which code handles a request, based on its HTTP method and URL path. In Express you register routes with app.get, app.post, app.put, app.patch and app.delete, each taking a path pattern, which can include parameters like :orderId, and one or more handler functions. Express checks routes in the order they were added and runs the first one that matches, so more specific routes must come before more general ones.
ts
app.get('/orders', listOrders) // GET /orders
app.get('/orders/export', exportOrders) // (1) must come before /orders/:id
app.get('/orders/:id', getOrder) // GET /orders/42
app.post('/orders', createOrder) // POST /orders
app.patch('/orders/:id', updateOrder) // PATCH /orders/42
app.delete('/orders/:id', cancelOrder) // DELETE /orders/42
app.get('/files/*filePath', serveFile) // (2) Express 5 named wildcard- Order matters. If
/orders/:idcame first, a request for/orders/exportwould match it withid = 'export'. - Wildcards must be named in Express 5, such as
*filePath, and the value arrives inreq.params.filePathas an array of path segments.
Express 5 path syntax changes that break old code: * alone is no longer valid, optional parameters are written /{:page} instead of /:page?, and regular-expression characters in paths are no longer supported. Validate route parameters in the handler or with a validation library instead.
8. What is express.Router(), and when should you use it?
The short answer
express.Router() creates a mini application that holds its own routes and middleware, which you then mount on a path in the main app with app.use('/orders', ordersRouter). Use it to split an API into feature modules, such as orders, products and users, each in its own file, and to apply middleware, such as authentication, to just that group of routes. Every real Express application with more than a handful of routes should use routers.
ts
// routes/orders.ts
import { Router } from 'express'
import { requireUser } from '../middleware/auth.js'
export const ordersRouter = Router()
ordersRouter.use(requireUser) // (1)
ordersRouter.get('/', async (req, res) => { // (2) GET /api/orders
res.json(await orders.listFor(req.user!.id))
})
ordersRouter.get('/:id', async (req, res) => { // GET /api/orders/42
res.json(await orders.getFor(req.user!.id, req.params.id))
})
// app.ts
app.use('/api/orders', ordersRouter) // (3)
app.use('/api/products', productsRouter)- Middleware for this router only: every order route requires a signed-in user; product routes are unaffected.
- Paths are relative to where the router is mounted.
- Mount it under a prefix.
Nested routers need mergeParams to see parameters from the parent path:
ts
const itemsRouter = Router({ mergeParams: true })
itemsRouter.get('/', (req, res) => res.json(listItems(req.params.orderId)))
ordersRouter.use('/:orderId/items', itemsRouter) // /api/orders/42/itemsHow to organise many routers in a large application is covered in question 30.
9. How do route parameters and query parameters work?
The short answer
Route parameters are named parts of the URL path, declared with a colon in the route, such as /orders/:orderId; they identify which resource you mean and appear in req.params. Query parameters come after the ?, such as ?status=paid&page=2; they are optional modifiers, such as filters, sorting and paging, and appear in req.query. Both always arrive as strings, so convert and validate them before use.
ts
// GET /customers/c17/orders?status=paid&page=2&sort=-createdAt
app.get('/customers/:customerId/orders', async (req, res) => {
const { customerId } = req.params // (1) 'c17'
const status = req.query.status // (2) 'paid'
const page = Number(req.query.page ?? 1) // (3) 2
const orders = await ordersRepo.find({ customerId, status, page, sort: req.query.sort })
res.json(orders)
})- Path parameter: identifies the customer.
- Query parameter: an optional filter.
- Convert strings to the type you need.
Number('abc')isNaN, so validate rather than just convert (question 64).
| Route parameter | Query parameter | |
|---|---|---|
| Example | /orders/42 | /orders?status=paid |
| Purpose | Which resource | How to filter, sort or page it |
| Required | Yes, part of the path | Usually optional |
| In Express | req.params | req.query |
A query parameter can be an array or an object if the client repeats it, such as ?status=paid&status=shipped, which gives ['paid', 'shipped']. Code that expects a string can break or be tricked, which is another reason to validate.
10. What is the difference between req.params, req.query, and req.body?
The short answer
They hold three different parts of the request. req.params holds the named parts of the URL path, such as the 42 in /orders/42. req.query holds the query string after ?, such as { page: '2' }. req.body holds the request body, the data sent with POST, PUT and PATCH, and only exists once a body parser such as express.json() has run. Params and query are always strings; the body can be any JSON value.
ts
// PATCH /orders/42?notify=true
// body: { "status": "shipped", "trackingNumber": "RM123GB" }
app.patch('/orders/:id', express.json(), async (req, res) => {
req.params // { id: '42' }
req.query // { notify: 'true' }
req.body // { status: 'shipped', trackingNumber: 'RM123GB' }
})req.params | req.query | req.body | |
|---|---|---|---|
| Comes from | The path | After ? in the URL | The request body |
| Needs a parser | No | No | Yes, such as express.json() |
| Types | Strings | Strings, arrays, objects | Any JSON value |
| Visible in logs and history | Yes | Yes | Usually not |
| Use for | Resource IDs | Filters, paging, options | Data to create or update |
Never put secrets in the URL. Paths and query strings end up in browser history, server logs and proxy logs. Tokens and passwords belong in headers or the body.
11. Which HTTP methods can be handled by Express?
The short answer
Express can route every standard HTTP method: GET, POST, PUT, PATCH and DELETE for normal API work, plus HEAD, which Express answers automatically from GET routes, OPTIONS, which CORS preflight requests use, and less common ones such as PURGE. Each has a matching function, such as app.patch, and app.all(path, fn) handles every method for a path. Express itself does not enforce meaning: following each method's rules is up to you.
| Method | Meaning | Body | Safe | Idempotent |
|---|---|---|---|---|
GET | Read | No | Yes | Yes |
HEAD | Headers of a GET, no body | No | Yes | Yes |
POST | Create, or run an action | Yes | No | No |
PUT | Replace at a known URL | Yes | No | Yes |
PATCH | Change part of a resource | Yes | No | Not necessarily |
DELETE | Remove | Usually no | No | Yes |
OPTIONS | Ask what is allowed; CORS preflight | No | Yes | Yes |
Safe means it does not change anything on the server. Idempotent means doing it twice has the same effect as doing it once, which decides whether a client may safely retry it (question 45).
A classic mistake: a GET /orders/42/cancel link. Browsers, link previews and crawlers fetch GET URLs freely, so an order can be cancelled by someone simply viewing the link. State changes must use POST, PUT, PATCH or DELETE.
12. What is the difference between PUT and PATCH?
The short answer
PUT replaces the whole resource with the representation you send: fields you leave out are removed or reset. PATCH applies a partial change: only the fields you send are modified. PUT is idempotent by definition, because sending the same full representation twice leaves the same result. PATCH is often idempotent in practice, such as "set status to shipped", but not always, such as "add 1 to the quantity".
http
GET /customers/c17
{ "name": "Priya Shah", "email": "priya@shop.example", "phone": "07700 900123" }
PUT /customers/c17
{ "name": "Priya Shah", "email": "priya.s@shop.example" }
→ phone is now gone: PUT replaced everything
PATCH /customers/c17
{ "email": "priya.s@shop.example" }
→ only the email changed; name and phone stayts
app.patch('/customers/:id', async (req, res) => {
const patch = CustomerPatch.parse(req.body) // (1) every field optional
const updated = await customers.update(req.params.id, patch) // (2) only given fields
res.json(updated)
})- A schema where every field is optional, but unknown fields are rejected.
- Update only the fields present. Distinguish "missing", which means leave it, from
null, which means clear it (the null versus undefined question).
PUT | PATCH | |
|---|---|---|
| Sends | The full resource | Only changes |
| Missing fields | Removed or reset | Untouched |
| Idempotent | Yes | Depends on the operation |
| Typical use | Replacing a settings document, uploading to a known path | Editing a profile, changing a status |
13. What is the difference between POST and PUT?
The short answer
POST asks the server to create something, or run an action, under a collection, and the server chooses the new resource's ID: POST /orders creates an order and returns its URL. PUT stores a resource at a URL the client already knows, creating or replacing it: PUT /carts/c42. PUT is idempotent, so repeating it is safe; POST is not, so repeating it can create duplicates unless you add an idempotency key.
POST | PUT | |
|---|---|---|
| URL | The collection: /orders | The exact resource: /carts/c42 |
| Who chooses the ID | The server | The client |
| Repeating it | Can create two orders | Same result as once |
| Success response | 201 Created with a Location header | 200 OK, or 201 if newly created |
ts
app.post('/orders', async (req, res) => {
const order = await orders.create(req.user.id, OrderInput.parse(req.body))
res.status(201).location(`/orders/${order.id}`).json(order) // (1)
})
app.put('/users/:id/preferences', async (req, res) => {
const prefs = await preferences.replace(req.params.id, Preferences.parse(req.body)) // (2)
res.json(prefs)
})POSTcreates a new order with a server-generated ID and tells the client where it lives.PUTreplaces the preferences document at a URL the client knows. Sending it twice changes nothing more.
Why it matters in practice: a phone loses signal after sending POST /orders. Did the order go through? Retrying might create a second order. That is the problem idempotency keys solve (question 46).
14. What is route chaining?
The short answer
Route chaining uses app.route(path) to define handlers for several HTTP methods on the same path in one place, such as app.route('/orders/:id').get(getOrder).patch(updateOrder).delete(cancelOrder). It avoids repeating the path string, keeps everything about one resource together, and reduces typos where one method's path differs from the others. It works the same on routers.
ts
ordersRouter
.route('/:id')
.all(loadOrderOr404) // (1) runs for every method on this path
.get((req, res) => res.json(res.locals.order))
.patch(requireRole('admin'), updateOrder)
.delete(requireRole('admin'), cancelOrder).alladds middleware for every method on that path, here loading the order once and returning404if it does not exist (question 27).
Chaining handlers is a related idea: any route can take several functions in a row, each calling next(), such as app.post('/orders', authenticate, validate(OrderInput), createOrder). That is middleware applied to a single route (question 21).