Node.js API Authentication Guide
π Node.js API Authentication Guide (Complete Guide)
Authentication is a critical part of any APIβit ensures that only authorized users can access protected resources.
This guide covers:
β
Password hashing
β
JWT Authentication
β
Login & Register
β
Protected routes
β
Middleware
β
Best practices
We will use:
Node.js
Express.js
bcryptjs (Password hashing)
jsonwebtoken (JWT)
π¦ 1. Setup Project
Install required packages:
π§± 2. Basic Server Setup
server.js
π 3. Password Hashing with bcryptjs
Before saving passwords β always hash them!
Verify password:
π§© 4. User Data (Demo)
In real apps, use MongoDB/MySQL.
Here, we use an array:
π 5. Register Route
π 6. Login Route (JWT Token Generation)
Install JWT if not installed:
Create JWT secret key:
Login API:
π‘οΈ 7. JWT Authentication Middleware (Protect Routes)
Create middleware:
π 8. Protected Route
Only logged-in users can access this route:
Test with:
π 9. Logout (Client-Side)
JWT is stateless β logout is handled by frontend:
Delete token from localStorage / cookies
Server doesnβt need to store sessions
(Optional) Block tokens via blacklist for advanced systems.
π§° 10. Full Example Code (server.js)
π 11. Authentication Best Practices (Highly Recommended)
β Never store passwords β always hash
β Use dotenv for secrets
β Set token expiry (1h recommended)
β Use HTTPS in production
β Validate email/password inputs
β Use refresh tokens for long sessions
β Use role-based access control (RBAC) for admin access
