Building an e-Commerce website with Node – Part 07 – Creating a HTTP request logger middleware for Node.js with morgan

This is Part 7 from the series “Building an e-Commerce website with Node.js”.

Morgan is a library for Node.js used for automated logging of requests, responses and related data.

First we require the library.

var morgan = require(‘morgan’);

Next we have to create a middleware, basically, a way to invoke the morgan object.

app.use(morgan('dev'));

require morgan library

Now, we have to install morgan. Open the terminal and switch to your project folder then install morgan by typing the following command in your terminal:

npm install morgan --save

install morgan for Node.js

Everything seems to be fine. Now let’s run the server and check if everything works well.
First, open your browser and go to http://localhost:3000 (to the home route we have created) then go to http://localhost:3000/page (a route that we haven’t created yet).

test morgan

If morgan works well you should get those messages in the terminal. 304 means successful and 404 means error.

This is how morgan works. It will log all of the requests to the server. That’s why it is called a logger.

Leave a Reply