I would like to know if is there any way of getting the total number of request in a certain path with Expressjs?
Asked
Active
Viewed 6,896 times
5
-
Why not maintain a counter variable and do `counter++` inside route? @Nicekor – Vishnudev Krishnadas Jan 09 '19 at 04:31
3 Answers
5
Why not to count it by yourself?
let pingCount = 0;
app.get('/ping',(req, res) => {
pingCount++;
res.send(`ping world for ${pingCount} times`);
});

dhilt
- 18,707
- 8
- 70
- 85
-
1I have done that way, was curious if there was any specific method to do it. Thank you! – Jan 09 '19 at 20:45
4
I created a middleware that will attach with all routes and count visits. Put this before your routes in app.js
let page_visits = {};
let visits = function (req, res, next) {
let counter = page_visits[req.originalUrl];
if(counter || counter === 0) {
page_visits[req.originalUrl] = counter + 1;
} else {
page_visits[req.originalUrl] = 1;
}
console.log(req.originalUrl, counter);
next();
};
app.use(visits);

Vishnudev Krishnadas
- 10,679
- 2
- 23
- 55
-
I have done that way, was curious if there was any specific method that would return it. Thank you! – Jan 09 '19 at 20:47
-
@Nicekor Good to hear that. If you find the answer helpful please upvote it. – Vishnudev Krishnadas Jan 10 '19 at 09:29
-
1
1
let count=0;
function countMiddleware(req,res,next){
count++;
if(next)next();
}
app.use(countMiddleware);
function countMiddleware is acting as middleware ,so it will be executed for every request.count variable is incremented for every request that is logged on your server

Tarun Rawat
- 244
- 3
- 9