Express.js Interview Questions and Answers (Express 5)
Last updated 2026-11-19
Express is small enough to learn in a day and subtle enough to be asked about for an hour. Interviewers use it to test whether you understand the request pipeline: how middleware chains, how errors travel and what happens when a handler forgets to respond. This page works through those topics and the practical decisions around security, validation and structure.
Express 5 became the version installed by default from npm in 2025, and it changed several behaviours that older tutorials still show. The answers below mark those differences. Underlying runtime topics are on the Node.js interview questions page, and API design is covered in REST API interview questions.
| Version covered | Express 5 (differences from 4 noted) |
|---|---|
| Core topics | Middleware, routing, error handling, security, structure |
| Questions here | 17 |
Express 5 changes worth memorising
- Rejected promises and thrown errors in async handlers are passed to the error handler automatically.
- Route path syntax follows a newer path-to-regexp: a bare asterisk needs a name, as in /files/*splat, and optional segments use braces such as /:id{.:ext}.
- req.query is no longer writable and the default query parser is simple rather than extended.
- Removed legacy methods such as app.del and res.json(status, body) signatures: use res.status(code).json(body).
- Requires a recent Node.js version, so check the support table for the release you deploy.
Show structure in answers
A common follow-up is how you would organise a larger app. A clean answer separates routes, controllers, services and data access, keeps middleware in its own folder, builds the app in one file and starts the server in another so tests can import the app without opening a port, and centralises error handling in a final middleware.
Express.js Interview Questions and Answers (Express 5): questions with worked answers
1 What is middleware in Express?
easyMiddleware is a function with the signature (req, res, next). It can read and modify 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, so order matters: body parsing must come before routes that read req.body, and the error handler comes last. Examples include express.json, cors and authentication checks.
javascriptapp.use((req, res, next) => { const start = Date.now(); res.on('finish', () => console.log(req.method, req.url, res.statusCode, Date.now() - start + 'ms')); next(); });2 What is the difference between app.use and app.get?
easyapp.use mounts middleware for any HTTP method and matches any path that starts with the given prefix, which is stripped from req.url inside the middleware. app.get handles only GET requests and matches the path exactly, with parameters. Use app.use for cross-cutting concerns and routers, and app.get, app.post and so on for endpoints.
3 How do you read route parameters, query strings and the body?
easyreq.params holds route segments such as /users/:id. req.query holds the parsed query string, and values are strings or arrays. req.body is available only after a body parser: express.json() for JSON and express.urlencoded() for forms, both built into Express. Always validate and convert types, because everything arrives as strings or untrusted JSON.
javascriptapp.use(express.json({ limit: '100kb' })); app.get('/users/:id', (req, res) => { const id = Number(req.params.id); if (!Number.isInteger(id)) return res.status(400).json({ error: 'bad id' }); res.json({ id, verbose: req.query.verbose === 'true' }); });4 How does error handling work, and what changed in Express 5?
mediumAn error-handling middleware has four arguments (err, req, res, next) and is registered after all routes. In Express 4, errors thrown synchronously were caught, but a rejected promise in an async handler was not, so you needed try/catch with next(err) or a wrapper. In Express 5, a returned rejected promise or an async function that throws is forwarded to the error handler automatically.
javascriptapp.get('/orders/:id', async (req, res) => { const order = await Orders.find(req.params.id); // a throw reaches the handler in Express 5 if (!order) throw Object.assign(new Error('Not found'), { status: 404 }); res.json(order); }); app.use((err, req, res, next) => { if (res.headersSent) return next(err); res.status(err.status ?? 500).json({ error: err.status ? err.message : 'Internal error' }); });5 What does next() do, and what are next(err) and next("route")?
mediumnext() hands control to the next matching middleware or route handler. next(err) skips straight to error-handling middleware. next("route") skips the remaining handlers of the current route and moves on to the next matching route, which is useful when a middleware decides another route should answer. next("router") exits the current router. Forgetting to call next or send a response leaves the request hanging.
6 How do you use express.Router to modularise an app?
mediumA Router is a mini application holding its own middleware and routes. Create one per resource, export it, and mount it with app.use("/users", usersRouter). Router-level middleware applies only to that router, so you can protect an admin router with an auth check. Use mergeParams: true when a nested router needs the parent route parameters.
javascript// routes/users.js import { Router } from 'express'; const router = Router(); router.get('/', list); router.post('/', create); router.get('/:id', show); export default router; // app.js app.use('/users', usersRouter);7 How do you handle authentication in Express?
mediumVerify credentials, create a session or token, and protect routes with middleware that checks it. With sessions, use express-session with a persistent store such as Redis and cookies marked HttpOnly, Secure and SameSite. With JWTs, verify the signature and expiry in middleware and attach the user to req. Hash passwords with bcrypt or Argon2, rate limit login, and return the same message for unknown user and wrong password.
javascriptfunction requireAuth(req, res, next) { const token = req.headers.authorization?.split(' ')[1]; try { req.user = jwt.verify(token, process.env.JWT_SECRET); next(); } catch { res.status(401).json({ error: 'unauthorised' }); } }8 Which middleware do you add to harden an Express app?
mediumhelmet sets security headers such as Content-Security-Policy and X-Content-Type-Options. cors with an explicit origin list restricts cross-origin access. express-rate-limit throttles abusive clients. Limit body sizes, disable the X-Powered-By header, validate input with a schema library, and set trust proxy correctly when behind a load balancer so client IPs and secure cookies work. Keep dependencies audited.
9 How do you validate request input?
mediumUse a schema library such as Zod, Joi or express-validator in a reusable middleware, so handlers receive trusted, typed data. Reject with 400 or 422 and a consistent error shape. Validate params, query and body separately, strip unknown fields, and never rely on client-side validation. Keep validation separate from business rules, which belong in the service layer.
javascriptconst schema = z.object({ email: z.string().email(), age: z.coerce.number().int().min(18) }); const validate = (s) => (req, res, next) => { const r = s.safeParse(req.body); if (!r.success) return res.status(422).json({ errors: r.error.flatten() }); req.body = r.data; next(); }; app.post('/signup', validate(schema), signup);10 What is the difference between res.send, res.json and res.end?
mediumres.send sends a response and sets Content-Type based on the argument: a string becomes text or HTML, an object is serialised as JSON, a Buffer is binary. res.json always serialises to JSON and sets application/json. res.end finishes the response without setting headers or content type. Calling any of them twice, or after headers were sent, causes the error "Cannot set headers after they are sent".
11 How do you serve static files and what are the cache considerations?
mediumUse express.static("public"), placed before the routes that might overlap. Set maxAge and immutable for fingerprinted assets so browsers cache them for a long time, and keep HTML short-lived. In production, serve static assets from a CDN or reverse proxy such as Nginx instead of Node. Never expose a folder containing source code or environment files.
12 Why does the order of middleware registration matter? Give an example.
mediumExpress walks the stack in registration order. If a route is registered before express.json(), req.body is undefined in it. If a catch-all 404 handler is registered before your routes, nothing else is reached. If an error handler is registered before routes, it never sees their errors. Authentication middleware must precede the routes it protects.
13 How does Express 5 route syntax differ from Express 4?
hardExpress 5 uses a stricter version of path-to-regexp. Wildcards must be named, so /files/*splat replaces /files/*, and the value is an array in req.params.splat. Optional parameters use braces like /users{/:id}, and the old /:id? form and inline regular expressions are no longer supported. A route string that worked in 4 may throw at startup in 5, so read the migration guide when upgrading.
javascript// Express 4 app.get('/files/*', handler); // Express 5 app.get('/files/*splat', (req, res) => res.json({ path: req.params.splat })); app.get('/users{/:id}', handler);14 How would you structure a production Express project?
hardSeparate app creation from server start so tests can use supertest without listening on a port. Layer the code into routes, controllers for HTTP concerns, services for business logic and repositories for data access. Load configuration once and validate it. Add request IDs, structured logging, health and readiness endpoints, and central error handling. Handle SIGTERM for graceful shutdown.
javascript// app.js export function createApp({ db }) { const app = express(); app.use(express.json(), requestId(), logger()); app.use('/api/users', usersRouter({ db })); app.use(notFound, errorHandler); return app; } // server.js: createApp({ db }).listen(PORT)15 How do you handle file uploads safely?
hardUse multer or busboy to parse multipart bodies. Set limits on file size and count, check the declared and actual file type, rename files rather than trusting the client file name, and never store uploads in a web-served folder. For large files, stream straight to object storage or issue pre-signed upload URLs so the file never passes through your server memory.
16 What is trust proxy and why does it matter?
hardBehind a load balancer, the connecting IP is the proxy, not the user. Setting app.set("trust proxy", 1), the number of proxy hops, makes Express read the X-Forwarded-For and X-Forwarded-Proto headers, so req.ip, req.protocol and secure cookies work and rate limiting keys on the real client. Setting it to true when clients can reach the app directly lets them spoof their IP.
17 How do you stream a large response or download?
hardCreate a readable stream and pipe it to res, setting Content-Type and Content-Disposition, and use stream.pipeline to handle errors and client aborts. This keeps memory flat regardless of file size. Support range requests when serving media. res.sendFile and res.download already handle caching headers and ranges for files on disk.
javascriptimport { pipeline } from 'node:stream/promises'; app.get('/export.csv', async (req, res) => { res.setHeader('Content-Type', 'text/csv'); await pipeline(db.streamRows('select * from orders'), toCsv(), res); });
Frequently asked questions
Is Express still relevant with Fastify and NestJS available?
Yes. Express remains the most widely deployed Node framework, and many companies maintain Express services, so interviews still ask about it.
Should I prepare for Express 4 or 5?
Learn 5 for new work and know the key differences from 4, because plenty of codebases are still on 4 and interviewers may ask either.
What is the most common Express interview question?
Middleware: what it is, how next works and how error-handling middleware is defined, followed by authentication and structuring a project.
Do I need TypeScript with Express?
Not required, but many teams use it. Know how to type request handlers and extend the Request interface for a user property.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- FastAPI Interview Questions and Answers
- Flask Interview Questions and Answers
- Flutter Interview Questions and Answers (Flutter 3, Dart 3)
- Frontend Developer Interview Questions and Answers
- Full Stack Developer Interview Questions and Answers
- Generative AI and LLM Interview Questions and Answers
- Google Cloud (GCP) Interview Questions and Answers
- GraphQL Interview Questions and Answers
- Hibernate and JPA Interview Questions and Answers
- HTML and CSS Interview Questions and Answers
- iOS and Swift Interview Questions and Answers
- Jenkins and CI/CD Interview Questions and Answers