Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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.

Example: A student registers on a learning website. Later, the student enters the registered email address and password on the login page to access the student dashboard.

2. How User Login Works

1. User Login Form

Enter email and password

↓
2. Express.js API

Validate the request data

↓
3. Find User Account

Retrieve the user by email from MySQL

↓
4. Verify Password

Use bcrypt.compare() against the stored hash

↓
5. Authentication Result

Reject invalid credentials or accept the login

↓
6. Authenticated Access

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.

Terminal
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.

SQL
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.

If you already created the table in the previous tutorial, do not create it again. Use the existing table and its records.

5. Configure the Database Connection

The following example assumes that your project already has a db.js file exporting a MySQL connection pool.

JavaScript — db.js
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.

JavaScript
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.

Why the same error message? Returning “Invalid email or password” for both unknown email addresses and incorrect passwords avoids directly revealing which accounts exist.

7. Test the Login API Using Postman

Start the Node.js server and send a POST request to the login endpoint.

Terminal
node server.js

Request method: POST

URL
http://localhost:3000/api/auth/login

In Postman, select Body → raw → JSON and submit the same credentials used when registering the user.

JSON
{
    "email": "rahul@example.com",
    "password": "MyStrongPassword123!"
}

Example successful response:

JSON
{
    "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.

JSON
{
    "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.
Next step: In the next tutorial, we will study JWT authentication and how signed tokens can be verified when accessing protected API routes.

11. User Login Flow

Login Request

Receive email and password

↓
Find Account

Retrieve the stored password hash

↓
Verify Password

Use bcrypt.compare()

↓
Authentication Result

Reject invalid credentials or accept the login

↓
Establish Authenticated Access

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.