We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Middleware

Middleware is a way to wrap a handler with additional functionality. It is a common pattern in web applications that allows us to write DRY code. For example, we can write a middleware that logs every request to the server. We can then wrap our handler with this middleware and every request will be logged without us having to write the logging code in every handler.

Middleware in Express

Middleware in Express has the following function signature:

type Middleware = (req: Request, res: Response, next: NextFunction) => void;
  • req: The request object.
  • res: The response object.
  • next: A function that, when called, will pass control to the next middleware in the chain.

You can register middleware on an application level using the express app's .use method.

app.use(middlewareLogging);

You can also apply it to specific routes by passing it as an argument to the route's handler.

app.get("/users", middlewareLogging, handlerGetUsers);

In fact, you can use as many middleware functions as you like:

app.get('/users', middlewareLogging, middlewareAuth, ...,  handlerGetUsers);

Assignment

There's been an increase in non-OK responses in the Chirpy API. The developer team's KPIs are suffering, and they need to know what's going on. They've asked you to write a middleware that logs every request that returns a non-OK status code.

res.on("finish", () => {
  //...
});

Express's Response object extends Node's http.ServerResponse, which is a writable stream. This means you can listen for events on it.

[NON-OK] <http_method> <url> - Status: <status_code>

Replace <http_method>, <url>, and <status_code> with the actual values. You can get these with method and url properties on the Request object.

npm run dev | tee server.log

Run and submit the CLI tests from the project directory in another terminal.