Interview questions with answers
Express interview questions and answers
Middleware, routing, error handling, security and Express 5. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.
- Subjective
- 31
- Objective
- 31
Subjective questions 31
1What is middleware in Express?Asked almost every time
Functions (req, res, next) that run in order for matching requests. Each can read or change the request and response, end the response, or call next() to pass control on. Logging, body parsing, authentication, CORS and compression are all middleware; route handlers are the last step. Order of app.use calls matters.
2How does error handling work in Express?Asked almost every time
Error-handling middleware has four arguments (err, req, res, next) and is registered after routes. Calling next(err) skips to it. In Express 5, rejected promises from async handlers are passed to it automatically; in Express 4 you must catch and call next(err) yourself (or use a wrapper). Send safe messages to clients and log details.
3How do you structure a larger Express application?Asked almost every time
Split routes by feature with express.Router(), keep handlers thin and move logic into services, put data access in repositories, centralise configuration, validation and error handling, and keep app creation separate from listen() so tests can import the app.
4How do you secure an Express API?Asked almost every time
Use Helmet for security headers, configure CORS narrowly, validate and sanitise input (Zod, Joi, express-validator), use parameterised queries, rate-limit (express-rate-limit), authenticate with sessions or JWTs and authorise per route, limit body size, keep dependencies patched, and hide stack traces in production.
5How do you validate requests in Express?Asked almost every time
Validate body, params and query at the edge with a schema library (Zod, Joi or express-validator) in middleware, return 400 with clear field errors, and pass the parsed, typed data on (for example in res.locals). Never trust client input inside handlers.
6How do you implement logging and request tracing?Asked almost every time
Use a structured logger such as pino (pino-http) with a request ID per request (from a header or generated), log method, path, status and duration, propagate the ID to downstream calls and keep logs JSON so they can be searched.
7How do you handle CORS correctly?Asked almost every time
Use the cors middleware with an allowlist of origins rather than * when credentials are involved, set allowed methods and headers, handle preflight OPTIONS requests, and remember CORS is enforced by browsers only; it is not server-side security.
8What changed in Express 5?Very often asked
Rejected promises in handlers and middleware go to error handling automatically, path matching uses a newer path-to-regexp with stricter syntax (named wildcards, no regex characters in strings), some deprecated methods were removed (for example res.send(status) forms, app.del), req.query is read-only, and Node 18+ is required.
9app.use vs. app.get vs. router?Very often asked
app.use(path, fn) mounts middleware for all methods on paths starting with path. app.get(path, fn) handles GET requests on an exact route pattern. express.Router() is a mini-app with its own middleware and routes, mounted with app.use('/users', usersRouter).
10How do you parse request bodies?Very often asked
express.json() for JSON and express.urlencoded({ extended: true }) for form posts, both built in, with size limits. File uploads need a multipart parser such as multer or busboy. Raw bodies (for webhook signatures) use express.raw() on that route.
11How do you test Express routes?Very often asked
Export the app without calling listen, and use Supertest to send requests (request(app).get('/users').expect(200)) in Jest or Vitest. Stub external services, and use a test database or transactions rolled back after each test.
12Sessions vs. JWT for authentication?Very often asked
Server sessions store state on the server (or Redis) and send a cookie with an ID; they are easy to revoke. JWTs are signed tokens holding claims, verified without a lookup; good across services but hard to revoke before expiry. For browser apps, httpOnly secure cookies are safer than storing tokens in localStorage.
13How do you implement pagination and filtering in an Express API?Very often asked
Accept validated limit, cursor (or page) and filter parameters, cap the limit, query the database with indexes, and return items with a nextCursor and maybe a total. Cursor pagination stays stable as data changes.
14How do you build a health check endpoint?Very often asked
Expose /healthz (liveness: the process is up) and /readyz (readiness: database and dependencies reachable) returning quick JSON responses, so load balancers and orchestrators route traffic only to healthy instances.
15How do you protect against common web attacks in Express?Very often asked
Helmet for headers, parameterised queries against SQL injection, output encoding against XSS, CSRF tokens or SameSite cookies for cookie-based auth, rate limiting against brute force, body size limits, and validating redirect targets.
16How do you stream a large response?Very often asked
Pipe a readable stream to res with stream.pipeline(source, res) so data flows with backpressure and errors are handled, set the right content headers, and avoid loading whole files into memory.
17How do you version a REST API in Express?Very often asked
Mount routers per version (app.use('/v1', v1Router)), or use a header, keep old versions until clients migrate, and share services between versions so only the HTTP layer differs.
18How do you upload files safely with multer?Very often asked
Limit file size and count, check MIME type and extension, store to disk or stream to object storage rather than memory for big files, generate your own file names, and scan or process files in a background job.
19How do you serve static files and set caching?Often asked
express.static('public', { maxAge: '1y', immutable: true }) serves files with cache headers; use hashed file names so long caching is safe. In production a CDN or reverse proxy usually serves them.
20How do route parameters and query strings work?Often asked
/users/:id exposes req.params.id; query strings appear in req.query. Both are strings, so validate and convert them. router.param can preload resources for a parameter.
21Why put Express behind a reverse proxy?Often asked
Nginx or a cloud load balancer handles TLS, compression, static files, buffering slow clients and load balancing. Set app.set('trust proxy', ...) so req.ip and req.secure reflect the original client.
22How do you handle async errors in Express 4?Often asked
Wrap async handlers in a helper such as const wrap = fn => (req, res, next) => fn(req, res, next).catch(next), or use the express-async-errors package, so rejections reach the error middleware instead of becoming unhandled rejections.
23What does res.locals hold?Often asked
Data scoped to the current request, available to later middleware and views, such as the authenticated user or validated input. It is reset for every request.
24How do you implement content negotiation?Often asked
Use res.format({ json: () => ..., html: () => ... }) or check req.accepts('json') to send the representation the client asked for in the Accept header.
25How do you handle 404s for unknown routes?Often asked
Add a final middleware after all routes that responds with 404 (or calls next with a NotFound error), placed before the error-handling middleware.
26How do you run Express in a cluster or with PM2?Often asked
Use the cluster module or PM2 in cluster mode to run one process per CPU core sharing a port, or run one process per container and let the orchestrator scale replicas. Keep the app stateless so any instance can serve any request.
27How do you set and read cookies?Often asked
res.cookie(name, value, { httpOnly: true, secure: true, sameSite: 'lax', maxAge }) sets them; cookie-parser makes them available in req.cookies, and signed cookies use a secret to detect tampering.
28How do you render server-side views?Often asked
Set a view engine (app.set('view engine', 'ejs') or Pug or Handlebars) and call res.render('page', data). Many modern apps use Express only as an API and render with a frontend framework instead.
29How do you handle timeouts for slow requests?Often asked
Set server timeouts (server.requestTimeout, headersTimeout), add per-route timeouts with AbortController for downstream calls, and return 503 or 504 rather than hanging connections.
30Express vs. Fastify vs. NestJS?Sometimes asked
Express is minimal and has the largest ecosystem. Fastify is faster, schema-based and plugin-oriented. NestJS adds an opinionated architecture with DI on top of Express or Fastify. Choose by performance needs, team size and how much structure you want.
31How does Express compare with Hono?Sometimes asked
Hono is a small, fast framework built on Web standard Request and Response that runs on Node, Bun, Deno and edge runtimes. Express is Node-specific with the largest middleware ecosystem.
Objective questions 31
1What signature does error-handling middleware have?Asked almost every time
Why: Four arguments mark it as an error handler.
2What does calling next() do?Asked almost every time
Why: next(err) jumps to error handlers.
3Which built-in middleware parses JSON bodies?Asked almost every time
Why: Built into Express 4.16+.
4Where should request validation happen?Asked almost every time
Why: Reject bad input at the edge.
5Which is NOT true about CORS?Asked almost every time
Why: Non-browser clients ignore CORS.
6Which pipes a stream to the response with error handling?Asked almost every time
Why: Handles backpressure and errors.
7In Express 5, a rejected promise in an async handler…Very often asked
Why: Express 5 handles async errors.
8Which package sets common security headers?Very often asked
Why: Helmet configures headers like CSP and HSTS.
9Where is :id from /users/:id available?Very often asked
Why: Route parameters live in req.params.
10Which tool tests Express routes without a running port?Very often asked
Why: It accepts the app object.
11Which logger is a fast structured choice for Express?Very often asked
Why: JSON logs with pino-http.
12Which endpoint tells a load balancer an instance can take traffic?Very often asked
Why: Checks dependencies.
13Where does a catch-all 404 middleware go?Very often asked
Why: Order matters.
14Which option makes a cookie unreadable by JavaScript?Very often asked
Why: Protects against XSS theft.
15Which defence stops SQL injection?Very often asked
Why: Never concatenate input.
16Which creates modular route handlers?Often asked
Why: Routers are mounted with app.use.
17What does trust proxy affect?Often asked
Why: It reads X-Forwarded-* headers.
18Which middleware serves files from a folder?Often asked
Why: express.static serves static assets.
19Why does middleware order matter?Often asked
Why: Earlier middleware runs first.
20Which method sends different formats by Accept header?Often asked
Why: Content negotiation.
21Which multer setting prevents huge uploads?Often asked
Why: Reject large files.
22Which mounts version 1 of an API?Often asked
Why: One router per version.
23Which renders a view template?Often asked
Why: Needs a view engine.
24Which runs one Express process per CPU core?Often asked
Why: Or the cluster module.
25Which middleware parses cookies into req.cookies?Often asked
Why: Also verifies signed cookies.
26Which status suits an upstream timeout?Often asked
Why: Gateway timeout.
27Which package handles multipart file uploads?Sometimes asked
Why: Multer parses multipart/form-data.
28Which logs HTTP requests?Sometimes asked
Why: Morgan is a request logger middleware.
29Which object passes data between middleware for one request?Sometimes asked
Why: res.locals is scoped to the request.
30Which framework runs on Web standard Request/Response across runtimes?Sometimes asked
Why: Node, Bun, Deno and edge.
31Cursor pagination is preferred because…Sometimes asked
Why: Offsets skip or repeat items.
Track what you have practised and search every bank in your dashboard.
Start learning