50 Topics
Chapter•420 Minutes

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?

Difficulty:EasyTopic:Fundamentals

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.
Key Takeaways
  • Express sits on top of Node.js's native http module, 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?

Difficulty:EasyTopic:Architecture

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

Routing

Manual IF/ELSE or Regex matching vs Declarative app.get(), app.post()

Express provides dedicated routing abstractions per HTTP method.

Body Parsing

Manual Buffer concatenation (req.on('data')) vs Built-in express.json()

Native HTTP requires stream buffering; Express parses payload bodies natively.

Middleware Support

Custom pipeline logic vs Built-in app.use() pipeline architecture

Express utilizes standardized middleware functions with (req, res, next) signatures.

Key Takeaways
  • Express drastically cuts boilerplate code compared to raw Node.js HTTP servers.

  • Native req and res objects are extended by Express rather than replaced.

Q3: How do the Express `req` and `res` objects relate to Node's native HTTP objects?

Difficulty:EasyTopic:Request-Response Cycle

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.cookies
  • res.status(), res.json(), res.send(), res.sendFile(), res.cookie()
Key Takeaways
  • Express prototype-inherits from Node's HTTP stream classes.

  • You can still call standard Node native methods like res.write() or res.end().

Q4: What is Middleware in Express.js and what is its role?

Difficulty:EasyTopic:Middleware

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

  1. Execute arbitrary execution logic.
  2. Make modifications to req and res objects.
  3. End the request-response cycle by sending a response.
  4. Pass execution control to the next middleware by invoking next().
Express Middleware Execution Chain
Key Takeaways
  • 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?

Difficulty:EasyTopic: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.
Key Takeaways
  • 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?

Difficulty:EasyTopic:Middleware

Express categorizes middleware based on mounting scope and signature:

  1. Application-level: Bound to app.use() or app.METHOD().
  2. Router-level: Bound to router.use() or router.METHOD() instances.
  3. Built-in: Included natively (express.json(), express.urlencoded(), express.static()).
  4. Third-party: Installed via NPM (e.g., cors, helmet, morgan).
  5. Error-handling: Takes 4 parameters (err, req, res, next).
Key Takeaways
  • 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()`?

Difficulty:EasyTopic:Routing
  • 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 HTTP GET requests on an exact path match.
Routing Scope Differentiation
// 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.

Key Takeaways
  • 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?

Difficulty:EasyTopic:Routing

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.
Modular Routing with Express Router
// 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

Router instances are exported and mounted cleanly on main application prefixes.

Key Takeaways
  • 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`?

Difficulty:EasyTopic:Request Processing

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).
Key Takeaways
  • Path params reflect resource identifiers; query params reflect modifiers like page or filter.

  • req.body is undefined by default until body-parser or express.json() middleware is mounted.

Q10: What is the purpose of `express.json()` and `express.urlencoded()`?

Difficulty:EasyTopic:Parsing Middleware

Both are built-in body parsing middleware functions introduced in Express 4.16+ (re-integrated from body-parser).

  • express.json(): Parses incoming HTTP requests carrying application/json payload headers and populates req.body with a JavaScript object.
  • express.urlencoded({ extended: true }): Parses incoming request payloads carrying application/x-www-form-urlencoded headers (standard HTML forms). The extended: true option uses the qs library allowing nested object parsing.
Key Takeaways
  • Body parsers read raw incoming stream buffers and format them into req.body.

  • extended: true permits parsing deeply nested form payloads.

Q11: What is the difference between `res.send()`, `res.json()`, and `res.end()`?

Difficulty:EasyTopic:Response Processing
  • res.send(): Generic response method. Accepts Buffer, String, Object, or Array. Automatically sets Content-Type header based on parameter type.
  • res.json(): Explicitly formats input parameter using JSON.stringify() and explicitly sets Content-Type: application/json header. Converts null and undefined to 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.
Key Takeaways
  • Use res.json() when building RESTful APIs to guarantee proper JSON response headers.

  • res.send() invokes res.json() internally when passed an Object or Array.

Q12: How do you serve static files in Express.js?

Difficulty:EasyTopic:Static Serving

Static assets (images, CSS, frontend client bundles) are served using the built-in express.static middleware.

Serving Static Files safely with absolute paths
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.

Key Takeaways
  • Pass absolute paths to express.static using path.join(__dirname, 'dir') for reliability.

  • Multiple static folders can be mounted simultaneously.

Q13: How do you write an Error-Handling Middleware in Express?

Difficulty:MediumTopic:Error Handling

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.

Centralized Error Handler Implementation
// 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).

Key Takeaways
  • 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?

Difficulty:EasyTopic:Routing

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.

Catch-All 404 Handler
// 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.

Key Takeaways
  • 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?

Difficulty:MediumTopic:Async Execution

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.

Async Error Handling Pattern in Express 4
// 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.

Key Takeaways
  • 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?

Difficulty:EasyTopic:Security

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.

Configuring Restricted CORS Policies
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.

Key Takeaways
  • Never use wildcard origin (*) in production applications handling sensitive credentials.

  • The cors middleware handles preflight OPTIONS requests automatically.

Q17: What is Helmet middleware and why should you use it?

Difficulty:MediumTopic:Security

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.
Key Takeaways
  • 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?

Difficulty:MediumTopic:Security

Injections occur when unvalidated user input is passed directly into database queries or rendered client HTML.

Prevention Strategies

  • NoSQL Injection: Use express-mongo-sanitize to strip out dangerous MongoDB operator keys like $gt or $ne from req.body or req.query.
  • SQL Injection: Always use parameterized queries or trusted ORMs (e.g., Prisma, Sequelize, Knex).
  • XSS Attacks: Sanitize HTML strings using libraries like xss-clean or sanitize-html, set httpOnly flags on authorization cookies.
Key Takeaways
  • 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?

Difficulty:MediumTopic:Security

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.

Configuring Rate Limiter Middleware
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.

Key Takeaways
  • 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?

Difficulty:MediumTopic:Authentication

JSON Web Tokens (JWT) enable stateless authentication across REST endpoints. Authentication middleware verifies tokens passed in the Authorization request header.

JWT Guard Middleware
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.

Key Takeaways
  • Return 401 Unauthorized if the token is missing; return 403 Forbidden if the token is invalid.

  • Attach decoded user details onto req.user to make them accessible to downstream route handlers.

Q21: What is the difference between Session-based and JWT-based authentication in Express?

Difficulty:MediumTopic:Authentication
  • Session-based (express-session): Stateful. Server stores session data in memory or Redis and issues a session_id cookie 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.
Key Takeaways
  • 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?

Difficulty:MediumTopic:File Processing

Express express.json() cannot parse multipart/form-data uploads. Multi-part uploads are handled using third-party middleware like multer.

Multer Upload Handler
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.

Key Takeaways
  • Use upload.single('field') for single files or upload.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?

Difficulty:EasyTopic:Request Scoping

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.

Sharing Data via res.locals
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.

Key Takeaways
  • Variables attached to res.locals persist 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?

Difficulty:MediumTopic:Architecture

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 supertest to fire API requests at app without starting real network port bindings.
  • Environment Separation: Permits wrapping the app in HTTPS servers, HTTP/2 servers, or cluster workers easily.
Modular App and Server Separation
// 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.

Key Takeaways
  • 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()`?

Difficulty:EasyTopic:Routing

app.route() allows defining chained handlers for a single route path. It reduces code duplication when multiple HTTP methods target the same URI path.

Chaining HTTP Verbs with app.route()
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.

Key Takeaways
  • 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?

Difficulty:MediumTopic:Validation

Request payload and parameter validation is handled using validation middleware like express-validator or zod.

Validating Inputs using express-validator
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.

Key Takeaways
  • 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?

Difficulty:EasyTopic:Server Rendering

Template engines dynamically render server-side HTML files populated with backend data values.

Configuring EJS View Engine
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.

Key Takeaways
  • 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?

Difficulty:MediumTopic:Performance
  • req.fresh: Returns true if client conditional cache headers (If-None-Match, If-Modified-Since) match current response headers, indicating the client's cache is fresh.
  • req.stale: Inverse of req.fresh. Returns true if client cached data is stale, indicating updated data must be transmitted.
Key Takeaways
  • If req.fresh is true, respond with res.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?

Difficulty:AdvancedTopic:Scaling

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.

Multi-Core Scaling via Node Cluster
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.

Key Takeaways
  • Utilizes all available server CPU cores, increasing request processing capacity.

  • Requires stateless session management (e.g., Redis) since worker processes operate isolated memory spaces.