Facebook Pixel

Node.js Express Interview Questions Middleware, Routing, and Error Handling

Master Express.js interview questions middleware, routing, error handling, request lifecycle, and best practices for production APIs.

Node.js Express Interview Questions

Express is the most popular Node.js web framework. Here are common interview questions.

Q1: What Is Middleware in Express?

Answer: Middleware is a function that runs during the request-response cycle. It can modify the request, send a response, or call the next middleware.

// Middleware function const logger = (req, res, next) => { console.log(`${req.method} ${req.url}`); next(); // Pass control to the next middleware }; app.use(logger); // Apply to all routes

Q2: What Is the Difference Between app.use and app.get?

Answer:

// app.use Runs for ALL HTTP methods on the given path app.use("/api", authMiddleware); // app.get Runs only for GET requests on the given path app.get("/api/users", getUsersHandler);

Q3: What Are the Types of Middleware?

Answer:

  1. Application-level app.use(logger) Runs for all routes
  2. Router-level router.use(auth) Runs for specific router
  3. Built-in express.json(), express.static()
  4. Error-handling (err, req, res, next) => {} 4 params
  5. Third-party cors(), helmet(), morgan()

Q4: What Is the Express Request-Response Lifecycle?

Answer:

  1. Incoming HTTP request
  2. Express parses the request
  3. Middleware chain runs in order:
    • express.json() (body parsing)
    • cors() (CORS headers)
    • authMiddleware (verify JWT)
    • validationMiddleware (validate input)
  4. Route handler executes
  5. Response is sent
  6. Error middleware catches any thrown errors

Q5: How Does Error Handling Work in Express?

Answer:

// Error-handling middleware (must have 4 parameters) app.use((err, req, res, next) => { console.error(err.stack); const status = err.statusCode || 500; res.status(status).json({ message: err.message || "Internal server error", ...(process.env.NODE_ENV === "development" && { stack: err.stack }) }); }); // Throw errors in route handlers app.get("/users/:id", asyncHandler(async (req, res) => { const user = await User.findById(req.params.id); if (!user) throw new AppError("User not found", 404); res.json({ data: user }); }));

Q6: What Is the asyncHandler Pattern?

Answer: A wrapper that catches async errors and passes them to Express's error handler:

const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; // Usage no try-catch needed router.get("/users", asyncHandler(async (req, res) => { const users = await User.find(); res.json({ data: users }); }));

Q7: What Is Express Router?

Answer: Express Router modularizes routes:

// routes/auth.js const router = express.Router(); router.post("/signup", signupHandler); router.post("/login", loginHandler); module.exports = router; // app.js const authRouter = require("./routes/auth"); app.use("/api", authRouter); // Mount at /api

The Takeaway

Express interview questions cover: middleware (functions in the request-response cycle with next()), app.use vs app.get (all methods vs specific method), middleware types (application, router, built-in, error-handling, third-party), request-response lifecycle, error handling (4-parameter middleware, asyncHandler pattern), and Express Router (modular route organization). Use asyncHandler to avoid try-catch in every route.

Middleware is a function that runs during the request-response cycle. It receives (req, res, next) and can modify the request, send a response, or call next() to pass control. Types: application-level (app.use), router-level, built-in (express.json), error-handling (4 params), and third-party (cors, helmet).

app.use runs for ALL HTTP methods (GET, POST, PUT, DELETE) on the given path. app.get runs only for GET requests. Use app.use for middleware that should run regardless of method, app.get/post/put/delete for specific route handlers.

Error-handling middleware has 4 parameters (err, req, res, next). It's registered after all routes. When an error is thrown or next(err) is called, Express skips remaining middleware and goes to the error handler. Use an asyncHandler wrapper to catch async errors and pass them to next().

A wrapper function: const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next). It catches rejected promises from async route handlers and passes them to Express's error middleware, eliminating the need for try-catch in every handler.

Express Router creates modular route handlers. Create a router in routes/auth.js, define routes on it (router.post('/signup')), export it, and mount in app.js with app.use('/api', authRouter). This keeps app.js clean and groups related routes together.

Ready to master Node.js completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.