Adding a login page to your HTML website prevents unauthorized visitors from accessing protected content. Users can only enter the page after providing a valid email address and password. The example code below also allows multiple users, different access durations, and automatic expiration using JavaScript and localStorage.
This approach is suitable for private blogs, premium tutorials, member-only resources, internal company pages, and downloadable content. Each user can be assigned a different validity period, such as 7, 14, or 30 days, before access automatically expires.
Key Takeaways
- Restricts access using email and password authentication.
- Supports multiple user accounts.
- Allows custom access duration for each user.
- Stores login sessions in localStorage.
- Automatically expires access after a specified number of days.
- Includes logout functionality.
- Works with pure HTML, CSS, and JavaScript.
What Is an HTML Login Page?
An HTML login page is a user authentication interface that requires visitors to enter credentials before accessing protected content. In this example, the username is an email address and authentication is handled through JavaScript.
The system verifies the entered email and password against predefined user records. If a match is found, the protected content becomes visible; otherwise, an error message is displayed.
How Does This Login System Work?
The JavaScript code contains a validUsers array that stores user information including email, password, and access duration. Each user can have a different validity period.
When a user logs in successfully, JavaScript calculates an expiration timestamp and saves it in localStorage. Every time the page loads, the script checks whether the stored session is still valid.
If the expiration date has passed, the session is automatically removed and the user must log in again. This creates a simple membership-style access system without requiring a database.
Here is whole code
CSS
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
}
.login-container {
background: #fff;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
width: 100%;
}
.login-form h2,
.content h2 {
margin-bottom: 1.5rem;
color: #333;
}
.content h6 {
text-align: center;
}
.input-group {
margin-bottom: 1rem;
}
.input-group label {
display: block;
margin-bottom: 0.5rem;
color: #555;
text-align: left;
}
.input-group input {
width: 100%;
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
}
.input-group input:focus {
border-color: #007bff;
outline: none;
}
.btn {
width: 100%;
padding: 0.75rem;
background-color: #444;;
color: #fff;
border: none;
border-radius: 4px;
font-size: 1rem;
cursor: pointer;
}
.btn:hover {
background-color: #0056b3;
}
.error-message {
color: red;
text-align: center;
margin-top: 1rem;
display: none;
}
.content {
margin-top: 1rem;
}
@media (max-width: 600px) {
.login-container {
padding: 1.5rem;
}
}
JS
document.addEventListener('DOMContentLoaded', function () {
const loginForm = document.getElementById('loginForm');
const content = document.getElementById('content');
const logoutBtn = document.getElementById('logoutBtn');
const errorMessage = document.getElementById('error-message');
const expiryDateElement = document.getElementById('expiryDate');
// Define valid email-password pairs with validity periods (in days)
const validUsers = [
{ email: 'bandarlaundry@gmail.com', password: 'password123', validityPeriod: 7 }, // 7 days
{ email: 'bandardeterjen@gmail.com', password: 'password456', validityPeriod: 14 }, // 14 days
{ email: 'bezimeni.id@gmail.com', password: 'mypassword', validityPeriod: 30 } // 30 days
];
// Check if the user is already logged in
const storedData = localStorage.getItem('loginData');
if (storedData) {
const { email, expiry } = JSON.parse(storedData);
const now = new Date().getTime();
if (now < expiry) {
// User is still logged in
showContent(email, expiry);
} else {
// Login expired
localStorage.removeItem('loginData');
}
}
// Handle login form submission
loginForm.addEventListener('submit', function (event) {
event.preventDefault();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value.trim();
// Validate email and password against the validUsers array
const user = validUsers.find(user => user.email === email && user.password === password);
if (user) {
errorMessage.style.display = 'none';
// Calculate expiration date based on the user's validity period
const now = new Date().getTime();
const validityInMilliseconds = user.validityPeriod * 24 * 60 * 60 * 1000; // Convert days to milliseconds
const expiry = now + validityInMilliseconds;
// Store login data in localStorage
const loginData = { email, expiry };
localStorage.setItem('loginData', JSON.stringify(loginData));
// Show content
showContent(email, expiry);
} else {
errorMessage.textContent = 'Invalid email or password';
errorMessage.style.display = 'block';
}
});
// Handle logout button click
logoutBtn.addEventListener('click', function () {
localStorage.removeItem('loginData'); // Remove login data
hideContent(); // Hide content and show login form
});
// Function to show content and set the expiry date
function showContent(email, expiry) {
loginForm.style.display = 'none';
content.style.display = 'block';
expiryDateElement.textContent = new Date(expiry).toLocaleString();
}
// Function to hide content and show login form
function hideContent() {
loginForm.reset();
loginForm.style.display = 'block';
content.style.display = 'none';
errorMessage.style.display = 'none';
}
});
var myElement = document.getElementById("myElement");
myElement.addEventListener("contextmenu", function(event) {
event.preventDefault(); // Prevent the default right-click menu behavior
});
Posts/Index
<div class="login-container">
<!-- Login Form -->
<form id="loginForm" class="login-form">
<h2>Login</h2>
<div class="input-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Enter your email" required>
</div>
<div class="input-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password" required>
</div>
<button type="submit" class="btn">Login</button>
<p id="error-message" class="error-message"></p>
</form>
<div id="content" class="content" style="display: none;">
<div class="container">
<div id="header"></div>
<div class="content">
<h2>Latest Posts</h2>
<div class="post-list">
<div class="post-item">
<h3><a href="posts/post1.html">My First Blog Post</a></h3>
<p>Posted on March 5, 2025</p>
<p>This is a short excerpt from the blog post...</p>
</div>
<div class="post-item">
<h3><a href="posts/post2.html">My Second Blog Post</a></h3>
<p>Posted on March 5, 2025</p>
<p>This is a short excerpt from the blog post...</p>
</div>
</div>
</div>
<button id="logoutBtn" class="btn"><span id="expiryDate"></span> Logout</button>
<div id="footer"></div>
</div>
</div>
What Are the Advantages of This Login Page?
- Easy to implement on static websites.
- No server configuration required.
- Supports multiple email accounts.
- Different users can receive different access durations.
- Automatic session expiration.
- Simple logout mechanism.
- Suitable for personal projects and private content.
What Are the Limitations?
The login credentials are stored directly inside the JavaScript file. Anyone with browser developer tools can potentially inspect the code and discover user information.
Because authentication occurs entirely on the client side, this method should not be used for sensitive business data, financial information, or customer records. For higher security, server-side authentication using technologies such as Node.js, PHP, Python, or Firebase is recommended.
How Does This Compare with Server-Side Authentication?
| Feature | Client-Side Login | Server-Side Login |
|---|---|---|
| Setup Complexity | Easy | Moderate to Advanced |
| Database Required | No | Usually Yes |
| Security Level | Low | High |
| Session Control | localStorage | Server Sessions |
| Suitable for Sensitive Data | No | Yes |
What Technologies Are Used in This Example?
The login page combines HTML for structure, CSS for styling, and JavaScript for authentication logic. The browser's localStorage API stores login sessions and expiration data.
Popular companies such as Google, Microsoft, and Meta use far more advanced authentication systems involving encrypted passwords, databases, OAuth, and multi-factor authentication. However, the basic concept of verifying user credentials remains similar.
What Tips Can Improve Security?
- Avoid storing real passwords in plain text.
- Use hashed passwords whenever possible.
- Move authentication to a backend server.
- Implement HTTPS encryption.
- Add rate limiting for login attempts.
- Use multi-factor authentication for important accounts.
- Regularly review active user access periods.
FAQ
Can I add more email accounts?
Yes. Simply add additional objects inside the validUsers array with a unique email, password, and validity period.
Can each user have a different access duration?
Yes. The validityPeriod property allows different users to receive different expiration periods.
Where is the login session stored?
The session information is stored in the browser using localStorage.
Can users stay logged in after refreshing the page?
Yes. The script automatically checks localStorage and restores access if the session has not expired.
Is this login page secure for commercial websites?
No. Since all credentials are stored on the client side, it should only be used for lightweight protection or demonstration purposes.
Can I protect blog posts with this system?
Yes. The protected content section can contain blog posts, downloads, tutorials, member resources, or private pages.
Conclusion
An HTML login page with email authentication, password validation, and expiration dates is a practical way to restrict access to private content. By using JavaScript and localStorage, you can manage multiple users and assign different access periods without needing a database.
While this solution is convenient for personal websites and protected resources, it should not be considered a replacement for professional server-side authentication. For sensitive projects, technologies such as Firebase Authentication, Node.js, PHP, MySQL, or OAuth-based systems provide significantly stronger security.
