Skip to content

Interview PrepExpress · Basics

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'))
  1. Middleware that parses JSON bodies for every request.
  2. A route: the GET method, a path with a parameter, and a handler.
  3. res.json sets the content type, turns the object into JSON and sends it.
  4. The parsed body, ready to use. It still needs validation before being trusted (question 64).

Where Express sits among Node.js frameworks:

FrameworkCharacter
ExpressMinimal, flexible, the most common
FastifyFaster, schema-based validation and serialisation built in
NestJSStructured, Angular-like, uses Express or Fastify underneath
Koa, HonoSmall, 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)
})
  1. Manual routing with a regular expression for each path.
  2. Manual headers and serialisation.
  3. Express does both: :id is captured for you, and res.json handles headers and JSON.
Concernnode:httpExpress
Routing with parametersBy handapp.get('/orders/:id')
Shared steps: logging, authBy handMiddleware (question 15)
JSON bodyRead the stream, parse, handle errorsexpress.json()
ResponseswriteHead, end, JSON.stringifyres.status().json()
ErrorsTry/catch everywhereCentral 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.

FeatureExample
Routingapp.get('/orders/:id', handler) (question 7)
Routersexpress.Router() for groups of routes (question 8)
Middlewareapp.use(requestLogger) (question 15)
Body parsingexpress.json(), express.urlencoded() (question 6)
Static filesexpress.static('public')
Response helpersres.json, res.status, res.sendFile, res.redirect, res.cookie
Error middlewareapp.use((err, req, res, next) => …) (question 32)
Settingsapp.set('trust proxy', 1) (question 28)
View renderingres.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())
  1. No path: runs for every request.
  2. Order matters: the body must be parsed before routes read req.body.
  3. A mount path: the router sees paths relative to /api/orders, so its router.get('/:id') matches /api/orders/42.
  4. A catch-all for anything no route handled, returning 404.
  5. The error handler goes last (question 32).
  6. listen returns 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.

reqGives you
req.paramsPath parameters, /orders/:id → { id }
req.queryQuery string, ?page=2 → { page: '2' }
req.bodyParsed body, once a body parser has run
req.get('Authorization')A header, case-insensitive
req.method, req.path, req.originalUrlWhat was asked for
req.ip, req.protocol, req.secureClient details, correct only with trust proxy set right (question 28)
resDoes
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.localsData 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: error

6. 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,
}))
  1. JSON bodies up to 100 KB. Larger bodies get 413 Payload Too Large. Invalid JSON gives a 400 error that your error handler should turn into a clean response.
  2. Form bodies. extended: false, the Express 5 default, uses the simple querystring parser rather than nested-object parsing.
  3. Static files under /assets, cached for a year because the file names contain content hashes. index: false stops it serving directory index files.

Things to know:

PointDetail
Content type must matchexpress.json() ignores a body sent as text/plain, leaving req.body empty
Express 5 changereq.body is undefined, not {}, when no parser handled the request
Static files in productionOften better served by Nginx or a CDN (the Vite deployment question)
UploadsNeither 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
  1. Order matters. If /orders/:id came first, a request for /orders/export would match it with id = 'export'.
  2. Wildcards must be named in Express 5, such as *filePath, and the value arrives in req.params.filePath as 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)
  1. Middleware for this router only: every order route requires a signed-in user; product routes are unaffected.
  2. Paths are relative to where the router is mounted.
  3. 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/items

How 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)
})
  1. Path parameter: identifies the customer.
  2. Query parameter: an optional filter.
  3. Convert strings to the type you need. Number('abc') is NaN, so validate rather than just convert (question 64).
Route parameterQuery parameter
Example/orders/42/orders?status=paid
PurposeWhich resourceHow to filter, sort or page it
RequiredYes, part of the pathUsually optional
In Expressreq.paramsreq.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.paramsreq.queryreq.body
Comes fromThe pathAfter ? in the URLThe request body
Needs a parserNoNoYes, such as express.json()
TypesStringsStrings, arrays, objectsAny JSON value
Visible in logs and historyYesYesUsually not
Use forResource IDsFilters, paging, optionsData 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.

MethodMeaningBodySafeIdempotent
GETReadNoYesYes
HEADHeaders of a GET, no bodyNoYesYes
POSTCreate, or run an actionYesNoNo
PUTReplace at a known URLYesNoYes
PATCHChange part of a resourceYesNoNot necessarily
DELETERemoveUsually noNoYes
OPTIONSAsk what is allowed; CORS preflightNoYesYes

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 stay
ts
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)
})
  1. A schema where every field is optional, but unknown fields are rejected.
  2. Update only the fields present. Distinguish "missing", which means leave it, from null, which means clear it (the null versus undefined question).
PUTPATCH
SendsThe full resourceOnly changes
Missing fieldsRemoved or resetUntouched
IdempotentYesDepends on the operation
Typical useReplacing a settings document, uploading to a known pathEditing 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.

POSTPUT
URLThe collection: /ordersThe exact resource: /carts/c42
Who chooses the IDThe serverThe client
Repeating itCan create two ordersSame result as once
Success response201 Created with a Location header200 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)
})
  1. POST creates a new order with a server-generated ID and tells the client where it lives.
  2. PUT replaces 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)
  1. .all adds middleware for every method on that path, here loading the order once and returning 404 if 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).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Express & REST APIs
Express
REST API design
Testing
Other topics
Nothing picked yet