Unique visitor counter for Express.js

Viewed 793

I ran into a problem that I cannot do. I will be glad if you help me.

I am writing a website in blog style with node.js. But I couldn't find a way to measure how many people viewed blog posts.

I want a system like this;

When someone enters the site, they will be counted as a visitor and 1 will be added to the counter.

When the same person re-enters the site, this time she will not count as a visitor. Number will not be added to the counter

1 Answers

Use express-visitor-counter...

const express = require('express');
const expressSession = require('express-session');
const expressVisitorCounter = require('express-visitor-counter');
const MongoClient = require('mongodb').MongoClient;

(async () => {
  const dbConnection = await MongoClient.connect('mongodb://localhost/test', { useUnifiedTopology: true });
  const counters = dbConnection.db().collection('counters');

  const app = express();
  app.enable('trust proxy');
  app.use(expressSession({ secret: 'secret', resave: false, saveUninitialized: true }));
  app.use(expressVisitorCounter({ collection: counters }));
  app.get('/', async (req, res, next) => res.json(await counters.find().toArray()));
  app.listen(8080);
})();
Related