Express.js is the most widely used web framework on top of Node.js, and its core concept is middleware. A middleware function receives the request object (req), the response object (res), and a next function. It can run arbitrary code, modify req or res, end the request-response cycle, or call next() to pass control to the next middleware in the chain. Middleware executes in the order it is defined with app.use() or route methods, flowing top-down. If a middleware never calls next() and does not send a response, the request hangs indefinitely. Error-handling middleware is distinguished by having four parameters, (err, req, res, next), and should always be defined last so it can catch errors propagated from earlier middleware.
Express supports several kinds of middleware. Application-level middleware is bound to the app with app.use(). Router-level middleware is bound to an express.Router() instance, useful for modular route organization. Built-in middleware such as express.json() and express.urlencoded() parse incoming request bodies, while express.static() serves files. Third-party middleware like cors, helmet, and morgan add features like cross-origin support, security headers, and request logging.
Creating a REST API in Express is straightforward: create an app, attach middleware such as express.json() to parse JSON bodies, then define routes for each endpoint using HTTP verbs. Route parameters, defined with a colon prefix like /users/:id, are accessed via req.params and identify a specific resource. Query strings, the part of a URL after a question mark such as /users?role=admin, are accessed via req.query and are typically used for filtering, sorting, or pagination. RESTful design recommends using nouns for endpoints (/api/users rather than /api/getUsers), using proper HTTP methods (GET, POST, PUT, DELETE), returning appropriate HTTP status codes (200, 201, 204, 400, 401, 403, 404, 500), keeping requests stateless, and supporting filtering and pagination. Cross-origin requests from browsers can be enabled with the cors middleware, and incoming data should be validated with libraries like express-validator or Joi to ensure that requests meet expected formats before processing.