User Login in Node.js
Learn how to authenticate registered users using Express.js, bcrypt, and MySQL in a Node.js application.
User login allows registered users to access their accounts. When a user submits an email address and password, the server retrieves the corresponding account and verifies the submitted password against the stored password hash.
In this tutorial, we will build a login API using Node.js, Express.js, bcrypt, and MySQL. We will validate login requests, verify passwords, handle invalid credentials, and understand how a successful login can establish authenticated access.
1. What Is User Login?
User login is the process of verifying the identity of a registered user using credentials such as an email address and password.
The server checks whether the account exists and whether the submitted password matches the stored password hash. If the credentials are valid, the application can establish a session or issue an authentication token.
2. How User Login Works
Enter email and password
Validate the request data
Retrieve the user by email from MySQL
Use bcrypt.compare() against the stored hash
Reject invalid credentials or accept the login
Establish a session or issue a token
3. Required Packages
We will use Express.js to create the login endpoint, bcrypt to verify passwords, and mysql2 to query MySQL.
npm install express bcrypt mysql2 dotenv
If you completed the previous User Registration tutorial, these packages may already be installed.
| Package | Purpose |
|---|---|
express |
Creates the login API endpoint. |
bcrypt |
Verifies the submitted password against the stored hash. |
mysql2 |
Retrieves user account information from MySQL. |
dotenv |
Loads configuration values from environment variables. |
4. Understand the Users Table
The login API uses the users table created in the previous User Registration tutorial.
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The important column for password verification is
password_hash. It stores the bcrypt hash created
during registration, not the original password.
5. Configure the Database Connection
The following example assumes that your project already has
a db.js file exporting a MySQL connection pool.
require("dotenv").config();
const mysql = require("mysql2/promise");
const pool = mysql.createPool({
host: process.env.DB_HOST || "localhost",
user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || "auth_demo",
waitForConnections: true,
connectionLimit: 10
});
module.exports = pool;
Ensure the database name, username, and password match your local MySQL configuration.
6. Create the User Login API
Create or update your server.js file with the
following login endpoint. This example assumes the registration
endpoint has already been implemented and uses the same users table.
require("dotenv").config();
const express = require("express");
const bcrypt = require("bcrypt");
const pool = require("./db");
const app = express();
app.use(express.json());
app.post("/api/auth/login", async (req, res) => {
try {
const { email, password } = req.body;
if (
typeof email !== "string" ||
typeof password !== "string" ||
email.trim() === "" ||
password.length === 0
) {
return res.status(400).json({
message: "Email and password are required."
});
}
const normalizedEmail = email.trim().toLowerCase();
if (normalizedEmail.length > 255) {
return res.status(400).json({
message: "Invalid email or password."
});
}
const [users] = await pool.execute(
`SELECT id, name, email, password_hash
FROM users
WHERE email = ?
LIMIT 1`,
[normalizedEmail]
);
if (users.length === 0) {
return res.status(401).json({
message: "Invalid email or password."
});
}
const user = users[0];
const isPasswordValid = await bcrypt.compare(
password,
user.password_hash
);
if (!isPasswordValid) {
return res.status(401).json({
message: "Invalid email or password."
});
}
return res.status(200).json({
message: "Login successful.",
user: {
id: user.id,
name: user.name,
email: user.email
}
});
} catch (error) {
console.error("Login failed:", error.message);
return res.status(500).json({
message: "Unable to process login."
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
This example verifies credentials and returns the user's non-sensitive account details. It does not yet create a session or issue a JWT; those are separate ways to maintain authenticated access after login.
7. Test the Login API Using Postman
Start the Node.js server and send a POST request to the login endpoint.
node server.js
Request method: POST
http://localhost:3000/api/auth/login
In Postman, select Body → raw → JSON and submit the same credentials used when registering the user.
{
"email": "rahul@example.com",
"password": "MyStrongPassword123!"
}
Example successful response:
{
"message": "Login successful.",
"user": {
"id": 1,
"name": "Rahul Sharma",
"email": "rahul@example.com"
}
}
This is an illustrative response. The actual user ID and account details depend on your database.
8. Handle Invalid Login Credentials
If the submitted email does not exist or the password is incorrect,
the API returns HTTP status 401 Unauthorized.
{
"message": "Invalid email or password."
}
If the email or password field is missing or has the wrong data
type, the API returns 400 Bad Request.
Production applications should also apply rate limiting and consider monitoring repeated failed login attempts to reduce password-guessing attacks.
9. Common Login Response Codes
| Status Code | Meaning | Example |
|---|---|---|
| 200 | OK | Credentials verified successfully. |
| 400 | Bad Request | Required login fields are missing. |
| 401 | Unauthorized | Invalid email or password. |
| 500 | Internal Server Error | Unexpected server or database failure. |
10. What Happens After Login?
Verifying the user's credentials is only one part of the login process. The application also needs a secure way to maintain authenticated access across subsequent requests.
| Approach | How It Works |
|---|---|
| Session-Based Authentication | The server maintains session state, usually identified by a session cookie. |
| JWT Authentication | The server issues a signed token that the client sends with later requests. |
11. User Login Flow
Receive email and password
Retrieve the stored password hash
Use bcrypt.compare()
Reject invalid credentials or accept the login
Use a session or an authentication token
Important Points to Remember
- User login verifies the identity of a registered user.
- Retrieve the stored password hash from the database.
- Use bcrypt.compare() to verify the submitted password.
- Never store or return plaintext passwords.
- Use parameterized queries for database operations.
- Return generic errors for invalid credentials.
- Apply rate limiting to help prevent password-guessing attacks.
- Use HTTPS in production.
- Use a session or token mechanism to maintain authenticated access.
- Protect database credentials and internal error details.
Summary
User login verifies a registered user's credentials. We created an Express.js login API that retrieves a user from MySQL, verifies the submitted password using bcrypt, and returns appropriate responses for successful and failed login attempts.
In the next tutorial, we will learn how JWT authentication works and how to verify tokens when protecting API endpoints.