Express.js interview questions and answers: middleware, errors and production

Express.js interview questions are mostly about the middleware chain: what runs in which order, what next() and next(err) do, and why the error handler needs four arguments. Interviewers then test how you handle async errors (Express 5 forwards rejected promises, Express 4 does not), validate input, secure the app and shut it down cleanly. A strong Express developer answer traces one request through every function it touches.

By Published 8 min read

What Express interviews look like

Express is the default web layer in many Node.js codebases, so its questions show up in backend, full-stack and MERN or MEVN stack interviews. Pure trivia is rare. You are more likely to get a small API to finish, a buggy middleware stack to fix, or a question such as "the server hangs on this route, why?" The Node runtime itself (event loop phases, streams, worker threads) is a separate topic; this page stays on the framework and the HTTP layer.

  1. Phone screenWhat middleware is, app.use versus app.get, how req.params, req.query and req.body differ, and how errors reach the handler.
  2. Coding roundBuild or extend a small REST API: routes, validation, error responses, maybe auth and a test with supertest. Often a take-home.
  3. Debugging and designRead a stack of middleware with a bug in it, then discuss rate limiting, sessions or tokens, file uploads and running several instances.

Fundamentals: the request, the response and the chain

Express basics
QuestionWhat it testsWhat a strong answer shows
What is middleware in Express?Core modelA function with (req, res, next) that can read or change the request and response, end the cycle, or pass control on with next(). Routes are middleware too.
What is the difference between app.use and app.get?Matchingapp.use matches any method and any path that starts with the mount path. app.get matches GET (and HEAD) on the exact route pattern.
What happens if middleware neither responds nor calls next?Hanging requestsThe request hangs until the client or a proxy times out. It is one of the most common Express bugs.
How do req.params, req.query and req.body differ?Inputsparams come from named route segments, query from the URL query string, body from the parsed request body, which only exists when a body parser such as express.json() ran.
What is the difference between res.send, res.json and res.end?Responsesres.json serializes and sets the JSON content type; res.send picks a type from the argument; res.end finishes the response with no extra handling.
What does the error "Cannot set headers after they are sent" mean?Control flowCode responded twice, usually a missing return after an early res.status().json() or a callback that fires after the response. Return when you respond.
What is express.Router for?ModularityA mini app with its own middleware and routes, mounted under a prefix. It keeps each resource in its own file.
What are res.locals and app.locals?Scoped datares.locals lives for one request, useful for passing the authenticated user to later middleware or templates. app.locals lasts for the app's life.
How does Express serve static files?Built-in middlewareexpress.static with a root folder, ideally behind a CDN or reverse proxy in production, with cache headers set on it.
Express basics. Scroll sideways on a small screen.

A small app that shows the order that matters

const express = require("express");
const crypto = require("node:crypto");

const app = express();
app.use(express.json({ limit: "100kb" }));

app.use((req, res, next) => {
  req.id = req.get("x-request-id") || crypto.randomUUID();
  res.set("x-request-id", req.id);
  next();
});

const orders = express.Router();
const db = new Map([["1", { id: "1", total: 40 }]]);

orders.get("/:id", async (req, res) => {
  const order = db.get(req.params.id);
  if (!order) {
    const err = new Error("order not found");
    err.status = 404;
    throw err; // Express 5 forwards this; Express 4 needs try/catch and next(err)
  }
  res.json(order);
});

orders.post("/", (req, res) => {
  if (typeof req.body?.total !== "number") {
    return res.status(400).json({ error: "total must be a number" });
  }
  const id = String(db.size + 1);
  db.set(id, { id, total: req.body.total });
  res.status(201).location("/orders/" + id).json(db.get(id));
});

app.use("/orders", orders);

app.use((req, res) => {
  res.status(404).json({ error: "no route for " + req.method + " " + req.path });
});

app.use((err, req, res, next) => {
  if (res.headersSent) return next(err);
  const status = err.status || err.statusCode || 500;
  res.status(status).json({
    error: status < 500 ? err.message : "internal error",
    requestId: req.id,
  });
});

module.exports = app;
Body parser, request id, a router, the 404 handler and the error handler, in that order. Run with Express 5: GET /orders/99 returned 404 with a request id, malformed JSON returned 400, an unknown path returned the 404 body. Not run on Express 4.

Walk an interviewer through it top to bottom. The JSON parser runs first so routes see req.body, and its own parse errors carry a 400 status that the error handler respects. The 404 handler has no path, so it catches anything the routers did not answer. The error handler is last and has four parameters, which is how Express recognizes it. Internal errors return a generic message, so stack traces and SQL never reach the client, while the request id lets you find the full error in the logs.

Errors and async code

  • How do errors reach the error handler? Synchronous throws inside a handler are caught by Express. Calling next(err) skips the remaining normal middleware and jumps to error middleware. In Express 5, a rejected promise from an async handler is treated the same way.
  • What happens in Express 4 when an async handler throws? The promise rejects outside Express's try block and nothing calls next. On current Node versions an unhandled rejection crashes the process by default; if the app installed a process-level handler that only logs, the process survives but that request hangs. Wrap handlers with try/catch and next(err), or use a small wrapper that adds .catch(next).
  • Why check res.headersSent in the error handler? If streaming already started, you cannot send a new status. Delegate to Express's default handler, which closes the connection.
  • How do you return consistent error bodies? Custom error classes with a status and a code, thrown from services, mapped in one handler. Validation libraries such as zod or Joi feed the same shape.
  • What should you never send to the client in production? Stack traces, raw database errors and internal hostnames. Log them with the request id instead.
  • What does process.on('unhandledRejection') have to do with Express? It is a last-resort log for bugs that escaped the chain. After an uncaught exception the process state is unknown, so log and exit and let the supervisor restart it.

Routing details and Express 5 changes

Routing questions, including version differences
QuestionWhat it testsWhat a strong answer shows
Two routes, /users/me and /users/:id. Which order?Route orderRegister /users/me first. Express matches in order, so the parameter route would capture "me" as an id.
What does router.param do?Shared loadingRuns a callback whenever a named parameter appears, for example to load the user for :userId once and attach it to the request.
What changed about route patterns in Express 5?UpgradesExpress 5 moved to a newer path-to-regexp. Wildcards need a name, optional parts use braces, and some regex-like characters in string paths are no longer accepted. Check the migration guide when upgrading.
What else commonly breaks in an Express 4 to 5 upgrade?MigrationRemoved deprecated method signatures, changed defaults in body and query parsing, and stricter path syntax. Run the test suite and read the release notes rather than relying on memory.
How would you version an API?API designMount routers at /v1 and /v2, share services underneath, and mark old routes deprecated with a header or docs.
How do you validate requests?Input safetyA schema per route (zod, Joi or JSON Schema with Ajv) in a validation middleware that returns 400 with field details, before the handler runs.
Routing questions, including version differences. Scroll sideways on a small screen.

Security and production

Questions for experienced Express developers
QuestionWhat it testsWhat a strong answer shows
Which security middleware would you add first?Hardeninghelmet for security headers, cors with an explicit origin list, a body size limit, and rate limiting on login and other expensive routes.
What does trust proxy do?ProxiesIt tells Express to read the client IP and protocol from X-Forwarded headers set by your load balancer. Without it, req.ip is the proxy; set it too broadly and clients can spoof their IP.
Sessions or JWTs?Auth designServer sessions in a shared store such as Redis are easy to revoke and keep tokens off the client. JWTs avoid a lookup but are hard to revoke; keep them short-lived. Cookies need HttpOnly, Secure and SameSite either way.
How do you prevent injection?SecurityParameterized queries or an ORM for SQL, schema validation for input shape, and care with Mongo-style operators in JSON bodies. Never build queries by string concatenation.
How do you handle file uploads?StreamingA multipart parser such as multer or busboy with size and type limits, streaming straight to object storage rather than buffering the whole file in memory.
How do you shut down gracefully?DeploysOn SIGTERM, stop accepting connections with server.close, fail the readiness check, let in-flight requests finish within a timeout, close database pools, then exit.
How do you run Express on every CPU core?ScalingSeveral processes (cluster module, PM2 or one container per core) behind a load balancer. Keep the app stateless: sessions, rate limit counters and caches live in a shared store.
How do you log requests?ObservabilityA structured logger such as pino with the request id, method, path, status and duration, plus tracing for calls to other services.
Questions for experienced Express developers. Scroll sideways on a small screen.

Testing and framework comparisons

  • How do you test an Express route? Export the app without calling listen, then use supertest (or fetch against a server on port 0) to send requests and assert on status and body. Mock the data layer or use a test database.
  • What is the point of separating app.js from server.js? Tests import the app without opening a port, and the server file owns listen, signals and shutdown.
  • Express or Fastify? Fastify has schema-based validation and serialization and is designed for throughput; Express has the largest middleware ecosystem and the most familiar API. Many teams stay on Express for that ecosystem.
  • Express or NestJS? NestJS adds modules, dependency injection and decorators on top of Express or Fastify. It suits large teams that want structure; plain Express suits small services.
  • How would you structure a medium Express codebase? Routes that only parse and respond, services that hold business rules, a data layer, and middleware for cross-cutting concerns. Controllers should not import the database driver directly.

Fictional example

Answering "Some requests to /reports hang until the load balancer times them out"
Interviewer
We are on Express 4. The /reports route is an async function that queries the database and renders a CSV. The app has a process.on('unhandledRejection') handler that writes to the console. Under load, some requests never finish.
Candidate
On Express 4, if the query rejects inside an async handler, nothing calls next. Without that console handler, current Node would crash the process on the rejection; with it, the process lives on and the client simply waits until a timeout, and the only trace is a console line that may never reach your log system. I would check for that first and wrap the handler with a helper that adds .catch(next), so failures reach the error handler and return a 500 with a request id. Second, a route that builds a large CSV in memory can stall the event loop, so I would stream rows with a cursor and pipe them to the response. Third, I would add a server-side timeout and log slow requests with their duration. Longer term, upgrading to Express 5 removes the wrapper need, but I would still keep the streaming change.

Express practice plan for a week

  • Day 1: write an app with five middleware functions that log their order, then break it by forgetting next and by responding twice.
  • Day 2: add routers, validation with a schema library and a single error handler with custom error classes.
  • Day 3: write supertest or fetch-based tests for success, 400, 404 and 500 paths.
  • Day 4: add helmet, CORS, rate limiting and session or token auth, and explain each choice in a sentence.
  • Day 5: stream a large download, add graceful shutdown and test it with a slow request in flight.
  • Days 6 and 7: practice the debugging questions above out loud and time a full take-home style build.

Runtime questions (event loop phases, streams, worker threads) are covered in Node.js interview questions, and API design that applies to any framework is in REST API interview questions. If the team weighs a Python service instead, see FastAPI interview questions; for the front end that calls your API, see Vue.js interview questions. Broader server-side rounds are in backend developer interview questions.

For practice, Natively, an AI interview assistant for Mac and Windows, can transcribe your mock Express round on your computer, so you can reread how you traced a request through the middleware. While rehearsing, it can read a buggy handler from a screenshot and suggest a fix, and with Pro or the free trial it uses the résumé and job description you add to shape its suggestions. The transcript and notes are kept so you can review them.

Questions people ask

What Express.js questions are asked in interviews?

Expect middleware and next(), app.use versus route methods, req.params, query and body, the four-argument error handler, async errors, routers, validation, security middleware such as helmet and CORS, sessions versus JWTs, testing and graceful shutdown.

What is middleware in Express.js?

A function that receives the request, the response and next. It can change them, end the response, or call next to pass control to the following function, in the order the middleware was registered.

How do you handle errors in Express?

Register one error-handling middleware with four parameters after all routes. Send errors to it with next(err) or by throwing; in Express 5 rejected async handlers reach it automatically, while Express 4 needs try/catch or a wrapper.

What is the difference between Express.js and Node.js?

Node.js is the JavaScript runtime with a low-level http module. Express is a framework on top of it that adds routing, middleware, request parsing and response helpers.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP