Chapter 20

Building and Using HTTP Middleware


  • Understanding how Connect works
  • Making Connect-compatible middleware
  • Making a middleware component that handles errors
  • Using some of the built-in middleware components bundled in Connect
  • Serving static files using Connect middleware
  • Parsing query string, request body, and cookies
  • Maintaining a session

Node is particularly fit to be an HTTP server. It has a great HTTP parser and can efficiently handle many concurrent connections in one single process.

When you are building an HTTP application server, you usually need it to perform some routine tasks like parsing the cookie headers, parsing the query string on the request URL, maintaining and associating a session, persisting session data, serving static files, parsing the request body, logging the request and response, and others. When coding the core logic of your application, you shouldn’t have to explicitly perform these tasks; these should be handled by the HTTP server application logic.

Some of these tasks involve inspecting the request – headers or body – others involve inspecting and changing the response, and some involve both. An example of where you may want to do both is when you want to log the details of each incoming request together with the respective response HTTP status code. In this case you need to inspect both the request and the response objects. You may also want to set or change the response headers, as is the case of when you are maintaining ...

Get Professional Node.js: Building Javascript Based Scalable Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.