Precision in Analytics - Implementing an IP-Based User Counter with Node.js and MongoDB

Roshan Paudel
21 Dec 2024

In today's digital landscape, understanding user behavior and engagement on your website is paramount to its success. To unlock precise insights, we delve into the realm of web analytics, presenting an insightful guide on building an advanced visitor counter. By harnessing the power of Node.js and MongoDB, we not only accurately track unique visitors but also integrate intelligent IP address tracking. Join us on this journey as we unravel the intricacies of user interaction, providing you with a comprehensive understanding of how to craft an intuitive visitor counter that empowers your web analytics strategy.



To prevent counting multiple visits from the same IP address and to ensure that the user count is accurate even when the app is deployed on the cloud, we can use a more robust data storage solution like a database. In this example, I'll use MongoDB to store visitor information.

Let's proceed with the modifications:

Step 1: Setting Up MongoDB

  1. Install MongoDB: Make sure you have MongoDB installed and running. If not, follow the official instructions to install it: https://docs.mongodb.com/manual/installation/
  2. Create a MongoDB Database: Create a new database in MongoDB to store visitor information. For example, you can name it visitor_counter.

Step 2: Implementing the Visitor Counter with MongoDB

  1. Install Dependencies: Install the necessary dependencies including expressmongoose, and dotenv for managing environment variables:

npm install express mongoose dotenv
  1. Create a .env file: Create a .env file in your project directory and add your MongoDB connection string:

MONGODB_URI=mongodb://<username>:<password>@<mongodb_host>:<mongodb_port>/visitor_counter
  1. Update app.js: Update the app.js file to include MongoDB integration and IP-based visit tracking:

require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 3000;

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// Define a schema for visitor data
const visitorSchema = new mongoose.Schema({
  ipAddress: String,
  visitedAt: { type: Date, default: Date.now },
});

// Create a model using the schema
const Visitor = mongoose.model('Visitor', visitorSchema);

app.use(async (req, res, next) => {
  const ipAddress = req.ip;
  const existingVisitor = await Visitor.findOne({ ipAddress });

  if (!existingVisitor) {
    // Create a new visitor entry
    const newVisitor = new Visitor({ ipAddress });
    await newVisitor.save();
  }

  next();
});

app.get('/', async (req, res) => {
  const visitorCount = await Visitor.countDocuments();
  res.send(`Total visitors: ${visitorCount}`);
});

app.listen(port, () => {
  console.log(`Server started on http://localhost:${port}`);
});

Step 3: Testing the Visitor Counter

  1. Run the Server: In your terminal, run:

node app.js
  1. Access the Website: Open your web browser and navigate to http://localhost:3000. You should see a message indicating the total number of unique visitors.
  2. Access from the Same IP: Open a new tab in your browser or use a different device to access the website. The visitor count should increase only once for each unique IP address.

With these modifications, you've implemented a visitor counter that accurately tracks unique visitors using their IP addresses and stores the data in a MongoDB database. This approach ensures that even when the app is deployed on the cloud, the visitor count remains accurate. Remember to replace <username><password><mongodb_host>, and <mongodb_port> in your .env file with your actual MongoDB credentials and server details.

Share this article in social media

    © 2024 Roshan Paudel