Q1. How do you create custom middleware in Express?
Custom middleware is simply a function with (req, res, next) signature. Example: const logger = (req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }; Then use it: app.use(logger). It can perform any logic before passing control.
Q2. What is the CORS middleware and why use it?
CORS (Cross-Origin Resource Sharing) is a security mechanism. The cors package adds CORS headers to responses, allowing your API to be accessed from different domains. Example: const cors = require('cors'); app.use(cors());. Without it, browsers block cross-origin requests.
Q3. What was body-parser and why was it used?
body-parser was a popular third-party middleware to parse request bodies. Before Express 4.16, it was needed for JSON and URL-encoded data. Now, its functionality is built into Express (express.json(), express.urlencoded()), so you rarely need the separate package.
Q4. How do you create middleware with configuration options?
Create a function that accepts options and returns the middleware. Example: const requestLogger = (format) => (req, res, next) => { console.log(format, req.method, req.url); next(); }; Then use: app.use(requestLogger('Request:'));. This pattern is common in third-party middleware.
Q5. What are some commonly used third-party middleware?
Popular ones include: morgan (logging), helmet (security headers), cors (CORS support), compression (gzip compression), express-session (session management), multer (file uploads), and passport (authentication).
