Skip to main content
Node.js & Express·Lesson 5 of 5

Authentication

Authentication verifies who a user is. In this lesson, you will build a complete authentication system with registration, login, password hashing, JSON Web Tokens (JWT), and protected routes.

Authentication Flow

A typical token-based authentication flow:

  1. User registers with email and password
  2. Server hashes the password and stores the user
  3. User logs in with credentials
  4. Server verifies credentials and returns a JWT
  5. Client sends the JWT with every subsequent request
  6. Server verifies the JWT and grants access

Setting Up

Install the required packages:

npm install bcrypt jsonwebtoken
  • bcrypt — hashes passwords securely
  • jsonwebtoken — creates and verifies JWTs

Password Hashing

Never store plain-text passwords. Use bcrypt to hash them:

Ctrl+Enter
HTML
CSS
JS
Preview

Higher salt rounds mean slower hashing (more secure but slower). 12 is a good default.

JSON Web Tokens

A JWT contains a header, payload, and signature. The server signs the token with a secret key, and can later verify it without a database lookup.

Ctrl+Enter
HTML
CSS
JS
Preview

JWT Structure

A JWT looks like xxxxx.yyyyy.zzzzz — three base64-encoded parts separated by dots:

PartContains
HeaderAlgorithm and token type
PayloadUser data (claims) and expiration
SignatureVerification hash (header + payload + secret)

User Registration

Ctrl+Enter
HTML
CSS
JS
Preview

User Login

Ctrl+Enter
HTML
CSS
JS
Preview

Notice we return the same error message for both "user not found" and "wrong password." This prevents attackers from discovering which emails are registered.

Auth Middleware

Protect routes by verifying the JWT on every request:

Ctrl+Enter
HTML
CSS
JS
Preview

Protecting Routes

Ctrl+Enter
HTML
CSS
JS
Preview

Security Best Practices

Rate Limit Login Attempts

Ctrl+Enter
HTML
CSS
JS
Preview

Security Checklist

PracticeWhy
Hash passwords with bcryptProtects against database leaks
Use HTTPS in productionPrevents token interception
Set short JWT expirationLimits damage from stolen tokens
Use httpOnly cookies (optional)Prevents XSS from accessing tokens
Rate limit login attemptsPrevents brute-force attacks
Return generic error messagesPrevents user enumeration
Validate input lengthPrevents DoS via long passwords

Practical Exercise

Wire everything together into a complete auth system:

Ctrl+Enter
HTML
CSS
JS
Preview

Key Takeaways

  • Never store plain-text passwords — always hash with bcrypt.
  • JWTs let you verify identity without a database lookup on every request.
  • Use middleware to protect routes and separate auth logic from business logic.
  • Return the same error for "user not found" and "wrong password" to prevent user enumeration.
  • Rate limit login attempts and use HTTPS in production.