Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 43 ยท Practice and Review

Express Interview Questions

Prepare for Express.js interviews with short answers on middleware, next(), routing, error handling, Express 4 vs 5, security and scaling, plus runnable demos.

Express interviews tend to circle the same ideas: how a request travels through middleware, how errors are handled, what changed in Express 5, and how you keep an app safe and fast. This lesson collects the questions that come up most, with short answers you can say out loud. Where an idea is easier to see than to explain, a runnable demo uses the mini Express from Inside Express; real Express code is read-only.

Do not memorize the answers. Interviewers can tell. Run the demos, change them, and explain them in your own words.

What interviewers probe

Middleware Order, next(), short-circuiting.
Errors Four arguments, async failures.
Express 5 What changed from 4.
Security Headers, limits, trust proxy.

Scaling and deployment come up in senior interviews.

1 / 2

Fundamentals

What is Express? A small, unopinionated web framework for Node.js. It adds routing, middleware and response helpers on top of node:http. It has no ORM, template language or project structure of its own.

What is middleware? A function (req, res, next) that runs between the request arriving and the response leaving. It can read or change req and res, end the response, or call next() to pass control on. Most of Express (body parsing, static files, logging, auth) is middleware. See How Middleware Works.

What does next() do? It hands the request to the next matching layer. next(err) skips normal layers and jumps to error handlers. next('route') skips the remaining handlers of the current route. Forgetting to call it (or to respond) leaves the request hanging.

Does order matter? Yes, completely. Layers run in registration order, so body parsers must come before routes that read req.body, and the 404 fallback and error handler must come last.

app.use versus app.get? app.use(path?, fn) matches every method and any path starting with the prefix. app.get(path, fn) matches only GET and the exact path pattern.

req.params, req.query, req.body? Params come from the path (/users/:id), the query holds ?key=value pairs, and the body holds the parsed payload. In Express 5, req.body is undefined until a body parser runs, and req.query is a getter that cannot be reassigned.

Seeing next() in action

A good answer shows the order of execution. This demo prints each layer as it runs and shows next('route') skipping the rest of a route.

Node.js Order of layers and next()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Errors and async code

How do you write an error handler? A middleware with four parameters, (err, req, res, next), registered after the routes. Express identifies it by fn.length. See Error Handling.

What happens to errors in async handlers?

  • Express 4: a rejected promise (or a throw after an await) was not caught. The request hung unless you wrapped the handler in try/catch and called next(err), or used a helper such as express-async-errors.
  • Express 5: if a handler or middleware returns a promise that rejects, Express calls next(err) for you.

The demo below runs the same async handler against both behaviors. The forwardRejections flag is the stand-in's switch for "Express 4 vs 5".

Node.js Rejected promises: Express 4 style vs 5 style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In real Express 4 you would write this instead:

JavaScript
app.get('/user', async (req, res, next) => {
  try {
    res.json(await findUser(req.params.id));
  } catch (err) {
    next(err);
  }
});

Express 4 versus Express 5

What changed in Express 5? The ones interviewers ask about most:

  • Rejected promises from handlers are forwarded to the error handler.
  • Path syntax follows path-to-regexp 8: a bare * must be named (/files/*path), ? optional markers became {/:id} style braces, and regex characters in paths are no longer supported. See Route Parameters.
  • req.body is undefined when no body parser handled the request.
  • req.query is read-only (a getter) and the default query parser is "simple".
  • Removed deprecated signatures such as res.send(status), res.json(status, obj) and app.del(). Use res.status(code).send(...).
  • res.redirect('back') is gone; read req.get('Referrer') yourself.
  • Needs a modern Node.js version.

Say you would upgrade by installing express@5, running tests and fixing deprecation warnings, as covered in Deployment and Production.

Routing, requests and responses

Why use express.Router? To group related routes and middleware in a module, then mount it under a prefix with app.use('/api/v1/users', router). See Modular Routing.

What does mergeParams do? A child router normally cannot see params from its mount path. express.Router({ mergeParams: true }) makes /posts/:postId/comments handlers see req.params.postId.

res.send versus res.json versus res.end? res.send picks a content type from the value; res.json stringifies and sets JSON headers; res.end is the raw Node call with no helpers. See The Response Object.

Why does "Cannot set headers after they are sent" happen? Code tried to respond twice, often a missing return before res.send followed by more logic, or calling next() after responding. Return after sending.

How do you read a client's IP behind a proxy? Set app.set('trust proxy', 1) (the number of proxies you control) so req.ip uses X-Forwarded-For. Never set it to true blindly, because clients can then spoof their IP.

Security

What is helmet? Middleware that sets protective HTTP headers (CSP, HSTS, X-Content-Type-Options and more). It is a starting point, not a full defense.

How do you stop abuse? Rate limiting (express-rate-limit), body size limits (express.json({ limit: '100kb' })), validation of every input, and timeouts. See Security Best Practices.

How do you store passwords? Never in plain text. Hash with a slow, salted algorithm such as argon2id, scrypt or bcrypt.

Where should a JWT live? There is no perfect answer. httpOnly cookies resist XSS theft but need CSRF protection; tokens in localStorage are readable by any injected script. Explain the trade-off. See JWT Authentication.

Scaling and production

Node is single-threaded; how do you use many cores? Run several processes: the cluster module, PM2 or one container per core behind a load balancer. Keep the app stateless so any instance can answer any request.

What blocks the event loop? CPU-heavy work (big JSON parsing, crypto in loops, sync file calls). Move it to worker threads or a queue.

Why a reverse proxy? nginx or a load balancer terminates TLS, serves static files, buffers slow clients and balances traffic. See Performance and Caching.

What is graceful shutdown? On SIGTERM, stop accepting new connections with server.close(), let in-flight requests finish, close database pools, then exit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does next(err) do in Express?

    With an argument (other than 'route'), next jumps ahead to error-handling middleware, which has four parameters.
  2. 2. In Express 5, what happens when an async handler throws after an await?

    Express 5 handles the returned promise and calls next(err) if it rejects. Express 4 did not.
  3. 3. Why should trust proxy be set to a number of hops rather than true?

    Trusting every forwarded header lets any client claim any IP address. A hop count trusts only your own proxies.
  4. 4. Which is a correct way to use multiple CPU cores with Express?

    One Node process runs JavaScript on one thread. Clustering, PM2 or multiple containers give you more processes.

Summary

  • Middleware is a function chain; order matters and every layer must respond or call next().
  • Error handlers have four parameters; Express 5 forwards rejected promises, Express 4 did not.
  • Know the Express 5 changes: path syntax, req.body default, read-only req.query, removed signatures.
  • Security answers: helmet, rate limits, validation, hashed passwords, careful trust proxy.
  • Scale with several processes and stateless code, and shut down gracefully.

Next: Express Cheat Sheet.