Express.js interview questions and answers for Node.js backend roles
Express.js interview questions are mostly about one mechanism: a request passes through an ordered chain of middleware functions until one of them sends a response or hands an error to the error handler. Interviewers check that you can order that chain correctly, structure routes with Routers, validate input, handle async errors, and secure and test an Express API. Senior rounds add what changed in Express 5, how to keep handlers fast, and how you would debug a request that hangs.
By Evin JohnPublished 8 min read
How Express questions show up in interviews
Express is the default web framework many Node.js developers learn first, so it appears in backend, full-stack and MERN or MEAN stack interviews, and in take-home tasks that ask for a small REST API. Interviewers use it to see whether you understand HTTP as a pipeline: what runs before a route, what happens when nothing matches, and where errors land. Runtime topics such as the event loop and streams belong to Node.js interview questions; this page stays on the framework.
- Quick conceptsMiddleware, next(), app.use versus app.get, route params versus query strings, and what res.json does.
- Build or extend an endpointAdd a resource with validation and proper status codes, often as a take-home or in a shared editor.
- Review an existing appSpot the middleware in the wrong order, the async handler that swallows errors, or the route that never responds.
- Production discussionSecurity middleware, logging with request ids, rate limiting, graceful shutdown and running behind a proxy.
Express fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is middleware in Express? | Core model | A function with (req, res, next) that can read or change the request and response, end the cycle by sending a response, or call next() to pass control on. Express runs them in the order they were registered. |
| What happens if middleware neither responds nor calls next()? | Request lifecycle | The request hangs until the client or a proxy times out. Every path through a middleware must do one or the other. |
| app.use versus app.get? | Mounting | app.use matches any method and any path that starts with the given prefix, which suits middleware and Routers. app.get matches GET requests on the exact route pattern. |
| What is express.Router for? | Structure | A mini app with its own middleware and routes, mounted under a prefix such as /users. It keeps each resource in its own module. |
| req.params, req.query and req.body? | Inputs | params come from named route segments, query from the URL query string, body from the parsed request body. All three are untrusted input and need validation. |
| Why do you need express.json()? | Body parsing | Express does not parse bodies by default. express.json() reads JSON bodies with a size limit; express.urlencoded() handles form posts. |
| res.send, res.json and res.end? | Responses | send picks a content type from what you pass, json serializes and sets the JSON type, end closes the response without a body helper. Calling any of them twice causes a headers-already-sent error. |
| How do you serve static files? | Built-in middleware | express.static with a folder, mounted before the routes. In production a CDN or reverse proxy often serves them instead. |
| Which status code for a successful create, a bad input and a missing record? | HTTP basics | 201 with a Location header, 400 (or 422 if the team uses it) with a clear message, and 404. |
| What does app.listen return? | Server | A Node.js http.Server. You keep it to close the server during graceful shutdown or tests. |
Middleware, routing and error handling
const express = require("express");
const app = express();
app.use(express.json());
// Middleware runs in registration order; next() hands over control.
app.use((req, res, next) => {
req.startedAt = Date.now();
next();
});
const users = new Map([["1", { id: "1", name: "Ada" }]]);
// In Express 5 a rejected promise from an async handler reaches the error handler.
app.get("/users/:id", async (req, res) => {
const user = users.get(req.params.id);
if (!user) {
const err = new Error("User not found");
err.status = 404;
throw err;
}
res.json(user);
});
app.post("/users", (req, res) => {
if (typeof req.body?.name !== "string") {
return res.status(400).json({ error: "name is required" });
}
const id = String(users.size + 1);
users.set(id, { id, name: req.body.name });
res.status(201).location(`/users/${id}`).json(users.get(id));
});
// Unknown routes fall through to here.
app.use((req, res) => res.status(404).json({ error: "Not found" }));
// Four arguments mark the error handler; register it last.
app.use((err, req, res, next) => {
const status = err.status ?? 500;
res.status(status).json({ error: status === 500 ? "Internal error" : err.message });
});
module.exports = app;- How does Express know a function is an error handler? By its arity: four parameters
(err, req, res, next). Drop the unused next and Express treats it as ordinary middleware, so errors skip right past it. - Why put the 404 handler after every route? Middleware runs in order, so a catch-all placed earlier would answer requests that a later route should have handled.
- How do you pass an error on from a callback-style API? Call
next(err). Anything passed to next other than nothing or the strings "route" and "router" is treated as an error and skips to the error handlers. - What did async errors look like in Express 4? A rejected promise in a handler was not caught, so the request hung or the process logged an unhandled rejection. Teams wrapped handlers in a helper that called
.catch(next). Express 5 forwards rejections itself. - What does next("route") do? Skips the remaining handlers for the current route and moves to the next matching route, handy for a conditional fast path.
- How do you share data between middleware and handlers? Attach it to
res.localsfor the life of one request (a common place for the authenticated user or a request id), rather than to a module-level variable that every request would share. - How would you validate input? A schema library or hand-written checks in a middleware per route, returning 400 with field-level messages, and never trusting types from req.query, which arrive as strings.
- How do you apply middleware to only some routes? Pass it in the route definition (
app.get(path, auth, handler)) or mount it on a Router so it covers that prefix only.
Express 5 questions
Express 5 is now the current major version, and interviewers who maintain older apps like to ask what an upgrade breaks. The changes below were checked against an Express 5 install; read the official migration guide for the full list before quoting anything else.
const express = require("express");
const app = express();
// Wildcards must be named; the value is an array of path segments.
app.get("/files/*path", (req, res) => res.json(req.params.path));
// Optional segments use braces instead of a trailing question mark.
app.get("/posts{/:id}", (req, res) => res.json(req.params.id ?? "list"));
// No body parser registered for this route, so req.body stays undefined.
app.post("/raw", (req, res) => res.json({ body: req.body === undefined ? "undefined" : req.body }));| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is the biggest behavior change for async code? | Error flow | Rejected promises from handlers and middleware are passed to next automatically, so wrapper helpers become unnecessary, though leaving them in is harmless. |
| Why do some routes fail to register after upgrading? | Path syntax | The path-matching library changed. Unnamed wildcards and the old optional and regex-like characters are rejected, so routes need named wildcards and braces. |
| How would you plan the upgrade? | Risk | Run the test suite on the new version, fix route patterns first since they fail at startup, search for removed helpers and changed defaults, then roll out behind normal monitoring. |
Senior Express and scenario questions
| Scenario | Likely cause | What to say you would check |
|---|---|---|
| Some requests hang until the load balancer times out. | A path that never responds | A middleware branch that forgets next() or a response, an awaited call with no timeout, or an error thrown in an Express 4 async handler. Log a request id at entry and exit to find the gap. |
| "Cannot set headers after they are sent" in the logs. | Double response | A missing return after res.json in an if branch, or a handler that responds and then calls next(err). |
| Latency spikes for every route at once. | Blocked event loop | A synchronous task inside one handler, such as hashing, large JSON work or a sync file read, holds up all requests. Measure event loop delay and move the work off the main thread. |
| req.ip shows the proxy's address. | Proxy settings | Set trust proxy to match the real number of proxies, so Express reads X-Forwarded-For correctly. Trusting everything lets clients spoof their address. |
| CORS errors only in the browser. | Preflight | The OPTIONS preflight is not answered with the right headers, or credentials are allowed with a wildcard origin, which browsers refuse. |
| Memory grows slowly over days. | Leak | A module-level cache or array keyed by request data that never shrinks, or listeners added per request. Take heap snapshots under load and compare. |
- How do you secure an Express API? Helmet or equivalent security headers, a body size limit, input validation, rate limiting on login and expensive routes, parameterized database queries,
x-powered-bydisabled, and secrets kept in the environment rather than in code. - How do you test routes without opening a port? Export the app separately from the code that calls listen, then drive it in tests with a library such as Supertest, which handles the server for you. Test the error handler with a route that throws on purpose.
- How do you shut down gracefully? On SIGTERM stop accepting connections with server.close(), let in-flight requests finish within a deadline, close database pools, then exit. Health checks should fail first so the load balancer stops sending traffic.
- How do you structure a large Express codebase? Routers per resource, thin handlers that call service functions, shared middleware for auth and validation, and one error handler. Teams that want this structure enforced often move to a framework such as NestJS.
- Express or a newer framework? Express has the largest middleware ecosystem and the most familiar code. Fastify adds schema-based validation and serialization and is often chosen for throughput. The honest answer depends on the team and the workload, and on measuring.
- How would you log usefully? Structured JSON logs with a request id set by the first middleware, the route, status and duration at the end of the request, and no bodies or tokens in the log.
Fictional example
- Interviewer
- Users report that saving a profile sometimes spins forever. Other endpoints are fine. How do you approach it?
- Candidate
- Since only one route is affected, I would start with its code path rather than the infrastructure. I would look for any branch that neither responds nor calls next, for example a validation check that returns early without sending a 400. Then I would check whether the handler awaits something with no timeout, such as an external API. If the app is still on Express 4, a rejected promise there would also hang the request, because Express 4 does not catch it. To confirm, I would add request-id logging at entry and before each response, reproduce with the failing input, and see where the log stops. The fix would be the missing response or a timeout, plus a test that sends that input.
Express practice plan
- Days 1 and 2: build a CRUD API for one resource with a Router, validation and correct status codes. Write the route list from memory first.
- Day 3: add a central error handler and a 404 fallback. Throw inside an async handler and watch where the error goes.
- Day 4: break things on purpose: remove a next(), respond twice, put the 404 handler first. Read each symptom so you recognize it in a review question.
- Day 5: security and operations: security headers, a rate limit, request-id logging and graceful shutdown.
- Day 6: tests for every route with the app exported separately from listen.
- Day 7: a timed mock: extend an unfamiliar Express app with one endpoint and explain each choice out loud.
Related reading: modern syntax questions in ES6 interview questions, backend-as-a-service trade-offs in Firebase interview questions, and ORM questions for .NET backends in Entity Framework interview questions.
Code-review questions reward a calm, ordered walk through the pipeline, and it is hard to judge your own order while you talk. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of a practice round on your machine so you can check whether you traced middleware before guessing at the database. While practicing, it can read a route file or a stack trace from a screenshot and suggest where to look, and with Pro or the free trial it can draw on your résumé and the job description you add. Notes from each session are kept for review.
Questions people ask
What Express.js questions are asked in interviews?
What middleware is and why order matters, next(), app.use versus app.get, Routers, params versus query versus body, body parsing, error-handling middleware, async errors, CORS, security middleware and how to test routes.
How do you handle errors in Express?
Register one error-handling middleware with four arguments after all routes, pass errors to it with next(err) or by throwing in an async handler (Express 5 forwards rejected promises), and map known errors to status codes.
What changed in Express 5?
Rejected promises from async handlers reach the error handler automatically, route wildcards must be named, optional segments use braces, and several old helpers were removed. Check the official migration guide before upgrading.
Is Express still worth learning for interviews?
Yes. Many Node.js codebases and take-home tasks still use it, and its middleware model is the base that frameworks such as NestJS build on.
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.
