How to Implement Visitor Counter in Node.js ?
Last Updated :
01 Aug, 2024
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.
Similar Reads
How to Take Input in Node.js ?
Taking input in a Node.js application is essential for building interactive command-line interfaces, processing user input, and creating dynamic applications. Node.js provides several methods for receiving input from users, including reading from standard input (stdin), command-line arguments, and u
2 min read
How to run Cron Jobs in Node.js ?
Cron jobs are scheduled tasks that run at specific intervals in the background, commonly used for maintenance or repetitive tasks. Users can schedule commands the OS will run these commands automatically according to the given time. It is usually used for system admin jobs such as backups, logging,
4 min read
How to Get Count of Instagram followers using Node.js ?
To get the count of Instagram followers using Node.js, you can use several approaches. The most common methods involve using Instagram's unofficial APIs, scraping data from Instagram, or leveraging third-party APIs that provide access to Instagram data. Instagram's official API requires you to have
2 min read
How to implement JWT authentication in Express app ?
Authentication is important in web apps to make sure only the right people can access certain pages or information. It helps keep user data safe and prevents unauthorized access. Implementing JSON Web Token (JWT) authentication in an Express.js application secures routes by ensuring that only authen
6 min read
How to Set Cookies Session per Visitor in JavaScript?
Managing session cookies in JavaScript is essential for web developers to maintain user state and preferences across multiple sessions. The document. cookie property provides a basic mechanism for cookie management, utilizing JavaScript libraries or frameworks can offer enhanced security and flexibi
4 min read
How to Setup View Engine in Node.js ?
View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with
2 min read
How to generate unique ID with node.js?
In this article, we are going to learn how to generate a unique ID using Node.js. Unique ID means a string contains a unique identity throughout the program. Table of Content Using UUIDUsing CryptoPrerequisitesJavaScript Node JSApproach 1: Using UUIDUUID is a module of NPM (Node Package Manager). UU
1 min read
How to uniquely identify computers visiting web site in JavaScript?
If you want to identify computers visiting your website, you will have to store the cookies of your website on the visiting computers. Cookies: In simple words, HTTP cookies are small notes which store the user's preferences about a particular website. For example, when a user shops online without l
4 min read
How to Access HTTP Cookie in Node.js ?
Cookies are small pieces of data sent by a server and stored on the client side, typically in the user's browser. They are often used to maintain stateful information such as user sessions, preferences, or tracking data. In Node.js, accessing and managing cookies is a common requirement for building
3 min read
How to Count Page Views in PHP?
Counting page views is a common requirement in web development to track website traffic, and user engagement. PHP offers simple and efficient method to implement a page view counter. In this article, we will see how to count page views in PHP. Table of Content Why Count Page Views?What is a session?
3 min read