Complete Express.js Interview Questions & Answer Bank
50 curated Express.js interview questions covering fundamental request-response flow, custom middleware pipelines, async patterns, security, and enterprise architecture.
Q1: What is Express.js and why is it widely used in Node.js applications?
Express.js is a minimal, fast, and unopinionated web application framework for Node.js. It provides a robust layer of fundamental web application features without hiding core Node.js capabilities.
Core Advantages
- Middleware Pipeline: Simplifies request processing, authentication, parsing, and logging.
- Routing: Offers an intuitive API for defining routes based on HTTP verbs and URL paths.
- Decoupling: Decouples HTTP handling logic into modular components.
- Performance: High throughput due to minimal abstraction overhead.
- Express sits on top of Node.js's native
httpmodule, providing abstraction for routing and middleware. - It is unopinionated, allowing developers to structure applications according to project requirements.
Q2: How does Express.js differ from using native Node.js HTTP module?
Building an API with native Node.js requires manual parsing of request streams, URL string splitting, and explicit header management. Express encapsulates these operations into clean higher-level interfaces.
Manual IF/ELSE or Regex matching vs Declarative `app.get()`, `app.post()`Manual Buffer concatenation (`req.on('data')`) vs Built-in `express.json()`Custom pipeline logic vs Built-in `app.use()` pipeline architecture(req, res, next) signatures.- Express drastically cuts boilerplate code compared to raw Node.js HTTP servers.
- Native
reqandresobjects are extended by Express rather than replaced.
Q3: How do the Express `req` and `res` objects relate to Node's native HTTP objects?
In Express, req (Request) and res (Response) are enhanced versions of Node's native http.IncomingMessage and http.ServerResponse prototypes.
Express adds helpful properties and helper functions directly onto these prototypes:
req.query,req.params,req.body,req.cookiesres.status(),res.json(),res.send(),res.sendFile(),res.cookie()
- Express prototype-inherits from Node's HTTP stream classes.
- You can still call standard Node native methods like
res.write()orres.end().
Q4: What is Middleware in Express.js and what is its role?
A middleware function is a callback that has access to the request object (req), response object (res), and the next callback function in the application's request-response cycle.
Responsibilities of Middleware
- Execute arbitrary execution logic.
- Make modifications to
reqandresobjects. - End the request-response cycle by sending a response.
- Pass execution control to the next middleware by invoking
next().
- Express is essentially a series of middleware function calls executed sequentially.
- Failing to call
next()or send a response leaves the request hanging indefinitely.
Q5: What is the role of the `next()` function in Express middleware?
The next() callback instructs Express to invoke the next middleware function registered in the execution pipeline.
Calling Modes
next(): Pass control to the immediate next middleware.next('route'): Skip remaining middleware in current router block and jump to next route matching current path.next(error): Skip all remaining processing middleware and jump straight to registered Error-Handling Middleware.
- Passing any truthy argument into
next(err)triggers Express error-handling mode. - Always return after calling
next()if code execution continues below it.
Q6: What are the 5 types of middleware in Express.js?
Express categorizes middleware based on mounting scope and signature:
- Application-level: Bound to
app.use()orapp.METHOD(). - Router-level: Bound to
router.use()orrouter.METHOD()instances. - Built-in: Included natively (
express.json(),express.urlencoded(),express.static()). - Third-party: Installed via NPM (e.g.,
cors,helmet,morgan). - Error-handling: Takes 4 parameters
(err, req, res, next).
- Application-level middleware applies globally across the app instance.
- Error-handling middleware is uniquely identified by accepting exactly 4 arguments.
Q7: What is the difference between `app.use()`, `app.all()`, and `app.get()`?
app.use(path, fn): Matches any HTTP method whose URL path begins with the target prefix. Used for mounting middleware.app.all(path, fn): Matches all HTTP verbs for an exact match of the target route path.app.get(path, fn): Matches only HTTPGETrequests on an exact path match.
// Matches GET, POST, PUT on /api, /api/users, /api/v1/etc.
app.use('/api', authMiddleware);
// Matches GET, POST, DELETE specifically on /users/export
app.all('/users/export', exportHandler);
// Matches ONLY GET requests on /users
app.get('/users', getUsersHandler);- Use
app.use()for broad pipeline processing. - Use
app.all()for applying route-level security logic across methods.
Q8: What is `express.Router()` and why is it useful?
express.Router() creates an isolated instance of middleware and routes. It acts as a 'mini-app' capable only of performing middleware and routing functions.
Benefits
- Modularizes complex applications into sub-modules.
- Groups related routes (e.g.,
/api/v1/users,/api/v1/orders) into separate files. - Encapsulates route-specific middleware rules.
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
router.get('/profile', (req, res) => res.json({ user: 'John' }));
module.exports = router;
// server.js
const userRoutes = require('./routes/userRoutes');
app.use('/users', userRoutes); // Mounts on /users/profile- Routers allow modular separation of endpoints by domain logic.
- Routes defined on routers inherit the path prefix where the router is mounted.
Q9: What is the difference between `req.params`, `req.query`, and `req.body`?
These three properties capture client inputs from different locations in an HTTP request:
req.params: Captures dynamic path segments defined in route templates (/users/:id).req.query: Captures key-value URL query parameters appended after the?symbol (/users?status=active).req.body: Captures payload data submitted in the HTTP request body (requires body parsing middleware).
- Path params reflect resource identifiers; query params reflect modifiers like page or filter.
req.bodyisundefinedby default until body-parser orexpress.json()middleware is mounted.
Q10: What is the purpose of `express.json()` and `express.urlencoded()`?
Both are built-in body parsing middleware functions introduced in Express 4.16+ (re-integrated from body-parser).
express.json(): Parses incoming HTTP requests carryingapplication/jsonpayload headers and populatesreq.bodywith a JavaScript object.express.urlencoded({ extended: true }): Parses incoming request payloads carryingapplication/x-www-form-urlencodedheaders (standard HTML forms). Theextended: trueoption uses theqslibrary allowing nested object parsing.
- Body parsers read raw incoming stream buffers and format them into
req.body. extended: truepermits parsing deeply nested form payloads.