Open In App

How to Implement Visitor Counter in Node.js ?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Implementing a visitor counter in Node.js can be a useful feature for many web applications. It allows you to track the number of visits or hits a particular page or your entire website receives. In this article, we’ll guide you through creating a simple visitor counter using Node.js and Express. We will use a text file to store the visitor count, making it a lightweight solution for small-scale applications.

Approach

To implement visitor counter in Node.js, we

  • First require express and mongoose
  • Create the connection to the local MongoDB Database
  • Define the mongoose Schema to store the records. It has two fields one “name” of String data type and the other “count” of Numeric data type.
  • Create the mongoose Model from the Schema
  • Define the root GET request and make the app listen to the local port.

The GET request has one special case when the app has been hit for the very first time. For that case, we need to create the default record with the count of visitors equals 1(one). For other times just increment its value by one.

Installation Steps

Step 1: Make a folder structure for the project.

mkdir myapp

Step 2: Navigate to the project directory

cd myapp

Step 3: Initialize the NodeJs project inside the myapp folder.

npm init -y

Step 4: Install the necessary packages/libraries in your project using the following commands.

npm install express mongoose

Project Structure:

Project structure

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.19.2",
"mongoose": "^8.4.3",
}

Example: We use the findOne() function of mongoose which takes a parameter as the searching condition. It returns the first record which matches our condition. If no record matches then it returns a null value. Now let’s see the full code of the “app.js” file.

Node
// app.js

// Requiring express to handle routing
const express = require('express')

// Creating app 
const app = express()

// Requiring mongoose to handle mongoDB Database
const mongoose = require('mongoose')

// Connecting to local MongoDB
mongoose.connect("mongodb://localhost:27017/visitCounterDB", {
    useNewUrlParser: true
});

// Creating visitor Schema to hold the
// count of visitors
const visitorSchema = new mongoose.Schema({
    name: String,
    count: Number
})

// Creating Visitor Table in visitCounterDB
const Visitor = mongoose.model("Visitor",visitorSchema)

// Get request to app root
app.get('/', async function(req,res){
    
    // Storing the records from the Visitor table
    let visitors = await Visitor.findOne({name: 'localhost'})

    // If the app is being visited first
    // time, so no records
    if(visitors == null) {
        
        // Creating a new default record
        const beginCount = new Visitor({
            name : 'localhost',
            count : 1
        })

        // Saving in the database
        beginCount.save()

        // Sending the count of visitor to the browser
        res.send(`<h2>Counter: `+1+'</h2>')

        // Logging when the app is visited first time
        console.log("First visitor arrived")
    }
    else{
        
        // Incrementing the count of visitor by 1
        visitors.count += 1;

        // Saving to the database
        visitors.save()

        // Sending the count of visitor to the browser
        res.send(`<h2>Counter: `+visitors.count+'</h2>')

        // Logging the visitor count in the console
        console.log("visitor arrived: ",visitors.count)
    }
})

// Creating server to listen at localhost 3000
app.listen(3000,function(req,res){

    // Logging when the server has started
    console.log("listening to server 3000")
})

Step to Run Application: Run the application using the following command from the root directory of the project

node app.js

Output: Now load the app in your browser by hitting http://localhost:3000

After closing the server and again restarting, when we visit the root page we saw that the count of visitors is preserved and incremented by one. We are logging these all steps into the console also to verify and understand the output.

console

Conclusion

Creating a visitor counter in Node.js is straightforward with the help of Express.js and a text file for storage. This simple implementation is ideal for small projects or for learning purposes. By following the steps outlined in this guide, you can set up a basic visitor counter and expand upon it with additional features or a more sophisticated data storage solution as your project grows.



Next Article

Similar Reads