Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DEV Community

Cover image for Build a Simple Visitor Counter with Me Using Node.js and Redis
Arbythecoder
Arbythecoder

Posted on

Build a Simple Visitor Counter with Me Using Node.js and Redis

Image description

Introduction

Hey there! 🎉 Today, I’m excited to share a fun and engaging project: building a simple visitor counter using Node.js and Redis. As someone who loves hands-on projects, I find that diving into coding is always an exhilarating experience. Most of my projects focus on beginners because I remember the challenges I faced when I first entered the tech world. I want to make this journey easier for you!

What is Node.js?

Node.js is a fantastic JavaScript runtime that lets you run JavaScript on the server side. It's perfect for building applications that need real-time data processing, like chat apps and RESTful APIs. If you’re already familiar with JavaScript on the front end, using it on the back end with Node.js feels like a natural extension.

What is Redis?

Redis is an in-memory data structure store that serves as a fast database. It's ideal for applications that require quick data access. In our project, we'll use Redis to keep track of how many times our page has been visited.

Project Overview

In this project, we’ll set up a Node.js server that connects to a Redis database. Each time a user visits the page, we’ll increment the visit count by one. It’s a simple but powerful way to learn how to link a database with your Node.js application!

Setting Up the Environment

Step 1: Install Redis

To get started, I used Docker to set up Redis. If you don’t have Docker installed, you can download it from [Docker's official site].

Once Docker is ready, run this command in your terminal to create and run a Redis container:

docker run --name redis -p 6379:6379 -d redis
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up the Node.js Project

  1. Create a project directory:
   mkdir redis-visitor-counter
   cd redis-visitor-counter
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a new npm project:
   npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install the necessary packages:
   npm install express redis
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the Server

Next, create an app.js file and add the following code:

const express = require('express');
const redis = require('redis');

const app = express();
const client = redis.createClient();

client.connect()
  .then(() => console.log("Connected to Redis"))
  .catch(err => console.error("Error connecting to Redis:", err));

// Initialize visitor count
client.set('visits', 0);

// Define the route
app.get('/', async (req, res) => {
  try {
    const visits = await client.get('visits');
    const updatedVisits = parseInt(visits) + 1;
    await client.set('visits', updatedVisits);
    res.send(`This page has been visited ${updatedVisits} times.`);
  } catch (err) {
    console.error("Error interacting with Redis:", err);
    res.status(500).send("Internal Server Error");
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the Application

To run your application, execute the following command in your terminal:

node app.js
Enter fullscreen mode Exit fullscreen mode

You should see output confirming that the server is running and connected to Redis:

Connected to Redis
Server is running on http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

Conclusion

And there you have it! 🎉 Today, we built a simple visitor counter using Node.js and Redis. This project is a great starting point for understanding how to connect a Node.js application to a database and manage dynamic content.

I hope you enjoyed this hands-on experience as much as I did! Feel free to check out my projects and follow my journey on GitHub:https://github.com/Arbythecoder.

Stay tuned for more beginner-friendly projects that make learning tech fun and accessible!

Top comments (4)

Collapse
 
nevodavid profile image
Nevo David

Nice! This project seems like a fun way to learn.

Collapse
 
ansellmaximilian profile image
Ansell Maximilian

Looks good! thanks

Collapse
 
arbythecoder profile image
Arbythecoder

Thank you for stopping by, I am glad you found the article helpful

Collapse
 
moibra profile image
Mohamed Ibrahim

Nice .. may I add it to my portfolio ... thanks :)

But I have a question .. If I visit it more than once it still increments? If so .. you should get IP of every user to prevent that.