Login using html and css with javascript validation – for full project – visit here
🔐 Login Flow (Step-by-Step)
1. User Enters Username & Password
2. JavaScript Validates & Sends Login Request
JavaScript grabs the input on login form submission.
🔹 Sends login request:
async function validateLogin(event) {
event.preventDefault();
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const response = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (response.ok) {
localStorage.setItem("token", data.token); // Save session token
localStorage.setItem("user_id", data.userId); // Save user ID
window.location.href = "storylisting";
} else {
alert(data.message || "Login failed.");
}
}
3. Server Checks Credentials
🖥️ Server Receives Login:
What happens:
- Find user in DB by
username - Compare
req.passwordwith hashed password in DB usingbcrypt.compare - If match:
- Create a JWT token
app.post("/api/login", async (req, res) => {
const { username, password } = req.body;
const user = await executeQuery("SELECT * FROM users WHERE username = ?", [username]);
const match = await bcrypt.compare(password, user.password); // Compare with hashed password
if (match) {
const token = jwt.sign({ id: user.id, username: user.username }, process.env.JWT_SECRET, {
expiresIn: "1h",
});
res.json({ token });
} else {
res.status(401).json({ message: "Invalid credentials" });
}
});
4. JS on frontend:
- Stores
tokenanduser_idinlocalStorage - The
tokenanduser_idare stored inlocalStorageafter a successful login, specifically after the server returns a successful response with a token. Here’s the exact point in your login JavaScript code:
if (response.ok) {
// Login successful, store the token and user ID
localStorage.setItem("token", data.token);
localStorage.setItem("user_id", data.userId); // Store user ID
window.location.href = "storylisting"; // Redirect to story listing page
}
🛡️ JWT (Token) = a special badge the user wears so they don’t have to log in again soon.