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.
Native Node.js vs Express.js Comparison
Manual IF/ELSE or Regex matching vs Declarative app.get(), app.post()
Express provides dedicated routing abstractions per HTTP method.
Manual Buffer concatenation (req.on('data')) vs Built-in express.json()
Native HTTP requires stream buffering; Express parses payload bodies natively.
Custom pipeline logic vs Built-in app.use() pipeline architecture
Express utilizes standardized middleware functions with (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);app.use acts as a path prefix match, app.all matches exact paths across verbs, and app.get filters by HTTP method.
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/profileRouter instances are exported and mounted cleanly on main application prefixes.
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.
Q11: What is the difference between `res.send()`, `res.json()`, and `res.end()`?
res.send(): Generic response method. Accepts Buffer, String, Object, or Array. Automatically setsContent-Typeheader based on parameter type.res.json(): Explicitly formats input parameter usingJSON.stringify()and explicitly setsContent-Type: application/jsonheader. Convertsnullandundefinedto valid JSON.res.end(): Node native method used to end response cycle quickly without sending data or auto-setting headers. Useful for 204 No Content responses.
Use
res.json()when building RESTful APIs to guarantee proper JSON response headers.res.send()invokesres.json()internally when passed an Object or Array.
Q12: How do you serve static files in Express.js?
Static assets (images, CSS, frontend client bundles) are served using the built-in express.static middleware.
const path = require('path');
// Mount public directory under root prefix
app.use(express.static(path.join(__dirname, 'public')));
// Mount under specific virtual route path
app.use('/static', express.static(path.join(__dirname, 'public')));Using path.join with __dirname prevents path resolution issues when launching Node apps from different directory contexts.
Pass absolute paths to
express.staticusingpath.join(__dirname, 'dir')for reliability.Multiple static folders can be mounted simultaneously.
Q13: How do you write an Error-Handling Middleware in Express?
Express error-handling middleware must explicitly declare four parameters: (err, req, res, next). Omitting any parameter (even next) causes Express to treat it as standard middleware.
// Must be registered LAST, after all app.use() and route calls
app.use((err, req, res, next) => {
console.error(err.stack);
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
status: 'error',
message: err.message || 'Internal Server Error'
});
});Global error handling middleware intercepts uncaught operational errors forwarded via next(err).
Must accept exactly 4 arguments
(err, req, res, next).Must be mounted at the bottom of the middleware chain after all route handlers.
Q14: How do you handle 404 (Not Found) errors in Express?
In Express, a 404 is not an error generated by next(err)—it is simply the result of reaching the end of the middleware chain without any route matching the requested path.
// Placed right before global error-handling middleware
app.use((req, res, next) => {
res.status(404).json({
error: 'Resource Not Found',
path: req.originalUrl
});
});If no routes handle the request, control falls through to this catch-all middleware.
Place 404 middleware after all defined valid routes.
404s are fallback routes, not uncaught system runtime exceptions.
Q15: How are asynchronous errors handled in Express 4 vs Express 5?
In Express 4, unhandled promise rejections inside async route handlers bypass Express error handling and crash the Node process unless explicitly caught or passed to next(err).
In Express 5, route handlers returning rejected Promises automatically forward the caught error to next(err) natively without requiring wrapper libraries.
// Express 4 requires try-catch or explicit wrappers
app.get('/users/:id', async (req, res, next) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).send('Not Found');
res.json(user);
} catch (error) {
next(error); // Manual pass to global error handler
}
});Express 4 requires explicit try-catch wrapping or async handler utility wrappers like express-async-errors.
Express 4 requires manually catching async exceptions and invoking
next(err).Express 5 automatically catches rejected promises in async route handlers.
Q16: How do you handle Cross-Origin Resource Sharing (CORS) in Express?
CORS security headers prevent unauthorized browsers from making cross-origin requests to your backend API. CORS is typically enabled using the third-party cors middleware.
const cors = require('cors');
const corsOptions = {
origin: ['https://myapp.com', 'https://admin.myapp.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
};
app.use(cors(corsOptions));Restricting allowed origins prevents rogue client-side applications from making cross-origin requests.
Never use wildcard origin (
*) in production applications handling sensitive credentials.The
corsmiddleware handles preflightOPTIONSrequests automatically.
Q17: What is Helmet middleware and why should you use it?
helmet is a third-party middleware that secures Express applications by automatically setting various HTTP response security headers.
Key Protections
X-DNS-Prefetch-Control: Controls browser DNS prefetching.X-Frame-Options: Prevents clickjacking attacks.X-Content-Type-Options: Prevents MIME type sniffing.Strict-Transport-Security(HSTS): Enforces HTTPS connections.Content-Security-Policy(CSP): Prevents XSS script injection.
Mount
app.use(helmet())near the top of your middleware chain for immediate header protection.Helps hide backend implementation headers like
X-Powered-By: Express.
Q18: How do you prevent NoSQL/SQL Injection and XSS attacks in Express?
Injections occur when unvalidated user input is passed directly into database queries or rendered client HTML.
Prevention Strategies
- NoSQL Injection: Use
express-mongo-sanitizeto strip out dangerous MongoDB operator keys like$gtor$nefromreq.bodyorreq.query. - SQL Injection: Always use parameterized queries or trusted ORMs (e.g., Prisma, Sequelize, Knex).
- XSS Attacks: Sanitize HTML strings using libraries like
xss-cleanor sanitize-html, sethttpOnlyflags on authorization cookies.
Never concatenate raw client inputs directly into database query strings.
Sanitize incoming user payloads before passing them to persistent storage layers.
Q19: How do you implement Rate Limiting in Express applications?
Rate limiting protects APIs from Denial of Service (DoS) attacks and brute-force credential attempts. It is commonly implemented using express-rate-limit backed by Redis.
const rateLimit = require('express-rate-limit');
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minute window
max: 5, // Limit each IP to 5 requests per window
message: { error: 'Too many login attempts. Please try again later.' },
standardHeaders: true, // Return standard X-RateLimit-* headers
});
app.use('/api/v1/auth/login', authLimiter);Rate limiting blocks brute-forcing by returning HTTP 429 Too Many Requests when limits are exceeded.
Apply restrictive rate limits on sensitive endpoints like auth and payment processing.
In multi-node cluster deployments, use a centralized Redis store backing the rate limit counter.
Q20: How do you implement JWT Authentication middleware in Express?
JSON Web Tokens (JWT) enable stateless authentication across REST endpoints. Authentication middleware verifies tokens passed in the Authorization request header.
const jwt = require('jsonwebtoken');
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Extract Bearer TOKEN
if (!token) return res.status(401).json({ error: 'Access token missing' });
jwt.verify(token, process.env.JWT_SECRET, (err, decodedUser) => {
if (err) return res.status(403).json({ error: 'Invalid or expired token' });
req.user = decodedUser; // Attach user payload to request
next();
});
};
app.get('/api/protected', authenticateToken, (req, res) => {
res.json({ message: 'Secure data', user: req.user });
});The middleware extracts, decodes, and attaches the payload user object to req before proceeding.
Return 401 Unauthorized if the token is missing; return 403 Forbidden if the token is invalid.
Attach decoded user details onto
req.userto make them accessible to downstream route handlers.
Q21: What is the difference between Session-based and JWT-based authentication in Express?
- Session-based (
express-session): Stateful. Server stores session data in memory or Redis and issues asession_idcookie to the client. Easy to invalidate immediately on the server, but requires shared session storage when scaling horizontally. - JWT-based: Stateless. Server signs a cryptographic token containing user claims and sends it to the client. Server doesn't maintain session storage, but token revocation requires token blacklisting techniques.
Sessions are stateful and require centralized database lookup; JWTs are stateless.
JWTs scale horizontally easily across server nodes without shared state dependencies.
Q22: How do you handle multi-part file uploads in Express.js?
Express express.json() cannot parse multipart/form-data uploads. Multi-part uploads are handled using third-party middleware like multer.
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
// Single file input field named 'avatar'
app.post('/profile', upload.single('avatar'), (req, res) => {
console.log(req.file); // Metadata of uploaded file
console.log(req.body); // Text fields submitted with form
res.send('File uploaded successfully');
});Multer intercepts multi-part data, saves files to destination directories, and attaches metadata to req.file.
Use
upload.single('field')for single files orupload.array('fields')for multiple files.Always restrict file upload size limits and enforce file extension validation rules.
Q23: What is `res.locals` and how is it used?
res.locals is an object scoped exclusively to the lifetime of the current request-response cycle. It is used to pass request-scoped variables across middleware functions and template view engines.
app.use((req, res, next) => {
res.locals.user = req.user;
res.locals.appName = 'My Enterprise App';
next();
});
app.get('/dashboard', (req, res) => {
// Accessible inside template rendering or downstream handlers
res.render('dashboard', { title: 'User Dashboard' });
});res.locals variables are automatically available to view engines like EJS or Pug.
Variables attached to
res.localspersist throughout the request pipeline, but clear automatically when the request finishes.Ideal for sharing data with view templates or downstream response formatters.
Q25: Why should you separate your Express app logic from your server listener?
Separating the Express application setup (app.js) from the HTTP server initialization (server.js) is an architectural best practice.
Benefits
- Integration Testing: Allows testing tools like
supertestto fire API requests atappwithout starting real network port bindings. - Environment Separation: Permits wrapping the app in HTTPS servers, HTTP/2 servers, or cluster workers easily.
// app.js
const express = require('express');
const app = express();
app.use(express.json());
app.get('/health', (req, res) => res.send('OK'));
module.exports = app; // Export app without binding to port
// server.js
const app = require('./app');
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));Decoupling app configuration from server listening simplifies supertest integration tests.
Decouples application setup from network port binding.
Enables fast, clean integration testing without port conflicts.
Q26: What is route chaining and how do you use `app.route()`?
app.route() allows defining chained handlers for a single route path. It reduces code duplication when multiple HTTP methods target the same URI path.
app.route('/api/v1/products')
.get((req, res) => {
res.json({ action: 'Get all products' });
})
.post((req, res) => {
res.json({ action: 'Create a new product' });
})
.put((req, res) => {
res.json({ action: 'Update products' });
});Chaining routes avoids repeating URL paths across different HTTP verb handlers.
DRY (Don't Repeat Yourself) route definition pattern.
Improves code organization when handling CRUD routes on single endpoints.
Q27: How do you validate incoming request payloads in Express?
Request payload and parameter validation is handled using validation middleware like express-validator or zod.
const { body, validationResult } = require('express-validator');
app.post('/user',
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 8 }),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.json({ success: true });
}
);Validation middleware sanitizes and inspects incoming request fields before proceeding.
Validate payload body fields, params, and query strings before touching database layers.
Reject invalid requests early with 400 Bad Request responses.
Q28: How do template engines (EJS, Pug, Handlebars) integrate with Express?
Template engines dynamically render server-side HTML files populated with backend data values.
const path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/index', (req, res) => {
res.render('index', { user: 'Alice', title: 'Home Page' });
});res.render compiles the named template file located in the views directory using local variables.
Configure engines using
app.set('view engine', 'engine_name').Express calls
res.render()to inject data properties into rendered views.
Q29: How do `req.fresh` and `req.stale` support HTTP Caching?
req.fresh: Returnstrueif client conditional cache headers (If-None-Match,If-Modified-Since) match current response headers, indicating the client's cache is fresh.req.stale: Inverse ofreq.fresh. Returnstrueif client cached data is stale, indicating updated data must be transmitted.
If
req.freshistrue, respond withres.status(304).end()to save network bandwidth.Helps automate HTTP/1.1 cache validation responses.
Q30: How do you scale an Express application using the Node.js Cluster module?
Node.js runs single-threaded by default. The Cluster module forks multiple Express worker processes across all available CPU cores, sharing the master server port.
const cluster = require('cluster');
const os = require('os');
const app = require('./app');
if (cluster.isMaster) {
const numCPUs = os.cpus().length;
console.log(`Master process running. Forking ${numCPUs} workers...`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork(); // Fork worker processes
}
} else {
app.listen(3000); // Worker process listens on shared port 3000
}Master process forks workers across CPU cores; operating system load balances connections across workers.
Utilizes all available server CPU cores, increasing request processing capacity.
Requires stateless session management (e.g., Redis) since worker processes operate isolated memory spaces.