Creating a website that records user mouse paths, stores them in a database, and provides an admin dashboard to view different sessions involves several components:
- Frontend: Captures mouse movements and sends them to the backend.
- Backend: Receives and stores the data.
- Database: Stores user sessions and mouse coordinates.
- Admin Dashboard: Displays the collected data for analysis.
We'll use the following technologies:
- Frontend: HTML, CSS, JavaScript
- Backend: Node.js with Express.js
- Database: MongoDB
- Templating Engine: EJS for the admin dashboard
Prerequisites
- Node.js and npm installed on your machine.
- MongoDB installed locally or use a cloud service like MongoDB Atlas.
- Basic knowledge of JavaScript, Node.js, and MongoDB.
Step 1: Set Up the Project
-
Initialize the project:
mkdir mouse-tracker
cd mouse-tracker
npm init -y
-
Install dependencies:
npm install express mongoose ejs body-parser express-session
-
Project Structure:
mouse-tracker/
├── public/
│ ├── css/
│ │ └── styles.css
│ └── js/
│ └── tracker.js
├── views/
│ ├── index.ejs
│ └── admin.ejs
├── models/
│ └── Session.js
├── app.js
└── package.json
Step 2: Backend Setup (app.js)
// app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Session = require('./models/Session');
const path = require('path');
const session = require('express-session');
const app = express();
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mouse_tracker', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
// Session middleware to track user sessions
app.use(session({
secret: 'mouse tracker secret',
resave: false,
saveUninitialized: true
}));
// Routes
// Home route
app.get('/', (req, res) => {
// Initialize a session if not present
if (!req.session.sessionId) {
req.session.sessionId = new mongoose.Types.ObjectId();
// Save the initial session in DB
const newSession = new Session({
_id: req.session.sessionId,
createdAt: new Date(),
events: []
});
newSession.save();
}
res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
// Endpoint to receive mouse data
app.post('/mouse-data', async (req, res) => {
const { x, y, timestamp } = req.body;
const sessionId = req.session.sessionId;
try {
await Session.findByIdAndUpdate(sessionId, {
$push: { events: { x, y, timestamp } }
});
res.status(200).send('Data received');
} catch (err) {
console.error(err);
res.status(500).send('Error saving data');
}
});
// Admin dashboard
app.get('/admin', async (req, res) => {
try {
const sessions = await Session.find().sort({ createdAt: -1 });
res.render('admin', { sessions });
} catch (err) {
console.error(err);
res.status(500).send('Error fetching sessions');
}
});
// View specific session
app.get('/admin/session/:id', async (req, res) => {
const sessionId = req.params.id;
try {
const sessionData = await Session.findById(sessionId);
res.render('session', { session: sessionData });
} catch (err) {
console.error(err);
res.status(500).send('Error fetching session data');
}
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 3: Define the MongoDB Schema (models/Session.js)
// models/Session.js
const mongoose = require('mongoose');
const EventSchema = new mongoose.Schema({
x: Number,
y: Number,
timestamp: Date
}, { _id: false });
const SessionSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
createdAt: {
type: Date,
default: Date.now
},
events: [EventSchema]
});
module.exports = mongoose.model('Session', SessionSchema);
Step 4: Frontend Setup
-
HTML for Tracking (views/index.ejs or views/index.html):
<!-- views/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mouse Tracker</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<h1>Welcome to the Mouse Tracker Page</h1>
<p>Move your mouse around and your movements will be tracked.</p>
<script src="/js/tracker.js"></script>
</body>
</html>
-
JavaScript to Capture Mouse Movements (public/js/tracker.js):
// public/js/tracker.js
(function() {
const sendInterval = 1000; // Send data every 1 second
let events = [];
// Capture mousemove events
document.addEventListener('mousemove', function(e) {
const event = {
x: e.clientX,
y: e.clientY,
timestamp: new Date()
};
events.push(event);
});
// Send data to server at intervals
setInterval(() => {
if (events.length > 0) {
fetch('/mouse-data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ events })
})
.then(response => response.text())
.then(data => {
console.log(data);
events = []; // Clear after sending
})
.catch(err => console.error('Error:', err));
}
}, sendInterval);
})();
Note: In the above script, it's more efficient to batch send multiple events instead of sending one at a time. Adjust sendInterval as needed.
-
Basic CSS (public/css/styles.css):
/* public/css/styles.css */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f0f0f0;
}
h1 {
color: #333;
}
Step 5: Admin Dashboard
-
Admin View (views/admin.ejs):
<!-- views/admin.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<h1>Admin Dashboard</h1>
<h2>Sessions</h2>
<table border="1" cellpadding="10">
<thead>
<tr>
<th>Session ID</th>
<th>Created At</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<% sessions.forEach(session => { %>
<tr>
<td><%= session._id %></td>
<td><%= session.createdAt.toLocaleString() %></td>
<td><a href="/admin/session/<%= session._id %>">View</a></td>
</tr>
<% }) %>
</tbody>
</table>
</body>
</html>
-
Individual Session View (views/session.ejs):
<!-- views/session.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session <%= session._id %></title>
<link rel="stylesheet" href="/css/styles.css">
<style>
#canvas {
border: 1px solid #000;
background-color: #fff;
}
</style>
</head>
<body>
<h1>Session ID: <%= session._id %></h1>
<p>Created At: <%= session.createdAt.toLocaleString() %></p>
<h2>Mouse Path</h2>
<canvas id="canvas" width="800" height="600"></canvas>
<script>
const events = <%- JSON.stringify(session.events) %>;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.beginPath();
for (let i = 0; i < events.length; i++) {
const point = events[i];
if (i === 0) {
ctx.moveTo(point.x, point.y);
} else {
ctx.lineTo(point.x, point.y);
}
}
ctx.stroke();
</script>
</body>
</html>
Explanation: This page retrieves all mouse events for a specific session and draws the path on an HTML5 canvas.
Step 6: Testing the Application
-
Start the server:
node app.js
-
Access the Tracking Page:
Open your browser and navigate to http://localhost:3000/. Move your mouse around the page; the movements will be recorded.
-
Access the Admin Dashboard:
Navigate to http://localhost:3000/admin to view all sessions. Click on "View" to see the mouse path for a specific session.
Step 7: Enhancements and Considerations
-
Authentication for Admin Dashboard:
- Implement authentication to restrict access to the admin dashboard.
- Libraries like
passport.js can be useful.
-
Data Optimization:
- Instead of sending every mouse event, consider throttling or debouncing to reduce the number of requests.
- Use
socket.io for real-time data transmission if needed.
-
Data Visualization:
- Enhance the admin dashboard with better visualizations using libraries like Chart.js or D3.js.
- Allow filtering sessions by date, user, etc.
-
Security:
- Sanitize all inputs to prevent injection attacks.
- Use HTTPS to secure data transmission.
-
Scalability:
- For high-traffic websites, consider optimizing database operations.
- Use indexing in MongoDB for faster queries.
-
Privacy Compliance:
- Ensure compliance with privacy laws like GDPR.
- Inform users about data collection and obtain necessary consents.
Complete Example Repository
For a complete example, consider creating a GitHub repository with the above structure and code. This allows for version control and easier collaboration.
By following the steps above, you can set up a basic mouse tracking system with an admin dashboard. Depending on your specific requirements, you can further enhance and optimize the system.