Step 1 - Download and Install Node.js
To download and install Node.js (the long-term supported version) visit the Node.js download page (https://nodejs.org/), and select your operating system and 64 or 32 bits options.
You will also need to confirm the installation by entering this command in your terminal.
node -v
npm -v
Step 2 - Create a Directory For Your Project & Switch to the New Directory:
mkdir activity-timeout-project
cd activity-timeout-project
Step 3: Initialize the node.js project
Now that you have a project directory, you need to initialize your project.:
npm init -y
Step 4: Install Necessary Dependencies
To begin installing the required packages you will need to run:
npm install express express-session body-parser
Step 5: Structure Your Project
Your project should consist of the following folders and files based on the hierarchical structure illustrated below:
activity-timeout-project/
│
├── server.js
└── views/
├── register.html
├── login.html
└── activity.html
Step 6: Registration Page
A registration page allows users to create a user account with a username and password. This account information is stored on the server temporarily until it is validated by a user through login.
Step 7: Login Page
A login page authenticates registered users. The login page will also create a session for that user by using `express-session`
Step 8: Activity Page
The activity page:
- Tracks user activity
- Sends requests to the server periodically
- Displays 'PAGE EXPIRED' message after 1 second of inactivity.
Step 9: Session Timeout Logic
In your `server.js`:
- Save the timestamp of the last activity by the user.
- Take the current timestamp and compare to the last activity timestamp.
- Destroy the user's session if they have had more than 1 second of inactivity.
- Send a 'PAGE EXPIRED' message back to the client.
Step 10: Running The Server
To run the server locally you can run:
node server.js
Step 11: Launch Your Web Client App
Open your Internet browser and navigate to:
http://localhost:3000
Step 12: Test Your Application Functionality
- Create an account for a new user
- Log into their account successfully
- Do not interact with the application for 1 minute
- See PAGE EXPIRED on your screen
Step 13: Stop Your Application Server
To stop the application server, type:
CTRL + C
Final Thoughts (Blog)
This is a great example of how to use timers and sessions in a Node.js application to keep track of user activity and automatically remove expired Web pages after a period of inactivity.
This project is a good way to learn about session management, security, and tracking users using realtime technology.
server.js Code
const express = require("express");
const session = require("express-session");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const PORT = 3000;
const users = {};
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: "secretkey",
resave: false,
saveUninitialized: true
}));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "views/login.html"));
});
app.get("/register", (req, res) => {
res.sendFile(path.join(__dirname, "views/register.html"));
});
app.post("/register", (req, res) => {
users[req.body.username] = req.body.password;
res.redirect("/");
});
app.post("/login", (req, res) => {
if (users[req.body.username] === req.body.password) {
req.session.user = req.body.username;
req.session.lastActivity = Date.now();
res.redirect("/activity");
} else {
res.send("Invalid Login");
}
});
app.get("/activity", (req, res) => {
if (!req.session.user) {
return res.redirect("/");
}
const now = Date.now();
const timeout = 1 * 1000; // 🔴 1 second
if (now - req.session.lastActivity > timeout) {
req.session.destroy();
return res.send(`
<html>
<body style="text-align:center;margin-top:100px;">
<h1 style="color:red;">PAGE EXPIRED</h1>
<p>Session expired due to inactivity (1 second)</p>
<a href="/">Login Again</a>
</body>
</html>
`);
}
req.session.lastActivity = now;
res.sendFile(path.join(__dirname, "views/activity.html"));
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.send("Logged out successfully");
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
register.html Code
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body style="text-align:center;margin-top:100px;">
<h2>User Registration</h2>
<form action="/register" method="post">
<label>Username:</label>
<input type="text" name="username" required />
<br><br>
<label>Password:</label>
<input type="password" name="password" required />
<br><br>
<button type="submit">Register</button>
</form>
<br>
<a href="/">Already Registered? Login</a>
</body>
</html>
login.html Code
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body style="text-align:center;margin-top:100px;">
<h2>User Login</h2>
<form action="/login" method="post">
<label>Username:</label>
<input type="text" name="username" required />
<br><br>
<label>Password:</label>
<input type="password" name="password" required />
<br><br>
<button type="submit">Login</button>
</form>
<br>
<a href="/register">New User? Register</a>
</body>
</html>
activity.html Page
<!DOCTYPE html>
<html>
<head>
<title>Activity Page</title>
<style>
body {
text-align: center;
margin-top: 100px;
font-family: Arial;
}
.expired {
color: red;
font-size: 32px;
font-weight: bold;
}
</style>
<script>
// Check session every 500 milliseconds
setInterval(() => {
fetch("/activity")
.then(res => res.text())
.then(data => {
if (data.includes("PAGE EXPIRED")) {
document.body.innerHTML = data;
}
})
.catch(() => {
document.body.innerHTML =
"<div class='expired'>PAGE EXPIRED</div>";
});
}, 500);
</script>
</head>
<body>
<h2>Activity Monitoring Page</h2>
<p>
⏱ Session timeout is <b>1 second</b>.
</p>
<p>
If you stay idle for more than 1 second,<br>
the page will expire automatically.
</p>
<br>
<a href="/logout">Logout</a>
</body>
</html>






Useful information about Full-Stack development and the mini project looks cool for beginners and very simple to understand.
ReplyDeleteThanks for the author of the blog Mr. RAVULA KARTHEEK for giving wonderful info for the students
All the best
Thank you for your comment. Follow our blog for quality materials. Thank you.
DeleteThank you for your comment. Follow our blog for quality materials. Thank you.
Deletenice
ReplyDeleteThank you for your comment. Follow our blog for quality materials. Thank you.
Delete