Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

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
  1. A(req, res, next)
  2. B(err, req, res, next)Correct answer
  3. C(err, next)
  4. D(req, res)

Why: Four arguments mark it as an error handler.

2What does calling next() do?Asked almost every time
  1. AEnds the response
  2. BPasses control to the next matching middlewareCorrect answer
  3. CRestarts the server
  4. DRetries the request

Why: next(err) jumps to error handlers.

3Which built-in middleware parses JSON bodies?Asked almost every time
  1. AbodyParser.xml()
  2. Bexpress.parse()
  3. Capp.json()
  4. Dexpress.json()Correct answer

Why: Built into Express 4.16+.

4Where should request validation happen?Asked almost every time
  1. AIn middleware before the handlerCorrect answer
  2. BIn the database only
  3. CIn the browser only
  4. DAfter sending the response

Why: Reject bad input at the edge.

5Which is NOT true about CORS?Asked almost every time
  1. APreflight uses OPTIONS
  2. BOrigins can be allowlisted
  3. CIt protects your server from all attackersCorrect answer
  4. DBrowsers enforce it

Why: Non-browser clients ignore CORS.

6Which pipes a stream to the response with error handling?Asked almost every time
  1. Ares.json
  2. Bstream.pipelineCorrect answer
  3. Cres.send(stream)
  4. Dfs.readFileSync

Why: Handles backpressure and errors.

7In Express 5, a rejected promise in an async handler…Very often asked
  1. AIs forwarded to error middlewareCorrect answer
  2. BIs ignored
  3. CReturns 200
  4. DCrashes the server

Why: Express 5 handles async errors.

8Which package sets common security headers?Very often asked
  1. Acors
  2. Bmorgan
  3. Ccompression
  4. DhelmetCorrect answer

Why: Helmet configures headers like CSP and HSTS.

9Where is :id from /users/:id available?Very often asked
  1. Areq.query.id
  2. Breq.params.idCorrect answer
  3. Creq.body.id
  4. Dres.locals.id

Why: Route parameters live in req.params.

10Which tool tests Express routes without a running port?Very often asked
  1. APuppeteer
  2. BPostman only
  3. Ccurl
  4. DSupertestCorrect answer

Why: It accepts the app object.

11Which logger is a fast structured choice for Express?Very often asked
  1. Aconsole.log
  2. Balert
  3. Cdebug only
  4. DpinoCorrect answer

Why: JSON logs with pino-http.

12Which endpoint tells a load balancer an instance can take traffic?Very often asked
  1. AA 404 handler
  2. BA static route
  3. CThe root route
  4. DA readiness checkCorrect answer

Why: Checks dependencies.

13Where does a catch-all 404 middleware go?Very often asked
  1. AInside each route
  2. BAfter the error handler
  3. CAfter all routes, before the error handlerCorrect answer
  4. DFirst

Why: Order matters.

14Which option makes a cookie unreadable by JavaScript?Very often asked
  1. Asigned
  2. BhttpOnlyCorrect answer
  3. Csecure
  4. DsameSite

Why: Protects against XSS theft.

15Which defence stops SQL injection?Very often asked
  1. ACompression
  2. BParameterised queriesCorrect answer
  3. CHelmet
  4. DCORS

Why: Never concatenate input.

16Which creates modular route handlers?Often asked
  1. Aexpress.group()
  2. Bnew Route()
  3. Cexpress.Router()Correct answer
  4. Dapp.module()

Why: Routers are mounted with app.use.

17What does trust proxy affect?Often asked
  1. ADatabase pooling
  2. Breq.ip and req.protocol behind a proxyCorrect answer
  3. CStatic caching
  4. DSession length

Why: It reads X-Forwarded-* headers.

18Which middleware serves files from a folder?Often asked
  1. Aexpress.files
  2. Bexpress.serve
  3. Cres.sendDir
  4. Dexpress.staticCorrect answer

Why: express.static serves static assets.

19Why does middleware order matter?Often asked
  1. AIt doesn't
  2. BMiddleware runs in the order it is registeredCorrect answer
  3. CExpress sorts it alphabetically
  4. DOnly for errors

Why: Earlier middleware runs first.

20Which method sends different formats by Accept header?Often asked
  1. Ares.formatCorrect answer
  2. Bres.type only
  3. Cres.negotiate
  4. Dreq.format

Why: Content negotiation.

21Which multer setting prevents huge uploads?Often asked
  1. Alimits.fileSizeCorrect answer
  2. Bdest
  3. Cstorage only
  4. DpreservePath

Why: Reject large files.

22Which mounts version 1 of an API?Often asked
  1. Aapp.use('/v1', v1Router)Correct answer
  2. Bapp.version(1)
  3. Crouter.v1()
  4. Dapp.set('v', 1)

Why: One router per version.

23Which renders a view template?Often asked
  1. Ares.template
  2. Bres.html
  3. Cres.renderCorrect answer
  4. Dres.view

Why: Needs a view engine.

24Which runs one Express process per CPU core?Often asked
  1. APM2 cluster modeCorrect answer
  2. Bnodemon
  3. Cnpm start
  4. Dts-node

Why: Or the cluster module.

25Which middleware parses cookies into req.cookies?Often asked
  1. Ahelmet
  2. Bcors
  3. Cmulter
  4. Dcookie-parserCorrect answer

Why: Also verifies signed cookies.

26Which status suits an upstream timeout?Often asked
  1. A301
  2. B418
  3. C504Correct answer
  4. D200

Why: Gateway timeout.

27Which package handles multipart file uploads?Sometimes asked
  1. AmulterCorrect answer
  2. Bhelmet
  3. Ccors
  4. Ddotenv

Why: Multer parses multipart/form-data.

28Which logs HTTP requests?Sometimes asked
  1. AmorganCorrect answer
  2. Bnodemon
  3. Clodash
  4. Duuid

Why: Morgan is a request logger middleware.

29Which object passes data between middleware for one request?Sometimes asked
  1. Aapp.globals
  2. Breq.session only
  3. Cprocess.env
  4. Dres.localsCorrect answer

Why: res.locals is scoped to the request.

30Which framework runs on Web standard Request/Response across runtimes?Sometimes asked
  1. AHonoCorrect answer
  2. BExpress
  3. CKoa only
  4. DSails

Why: Node, Bun, Deno and edge.

31Cursor pagination is preferred because…Sometimes asked
  1. AIt stays stable as data changesCorrect answer
  2. BIt needs no index
  3. CIt shows page numbers
  4. DIt is shorter

Why: Offsets skip or repeat items.

Track what you have practised and search every bank in your dashboard.

Start learning