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

mkdir node-auth-api
cd node-auth-api
npm init -y

Install required packages:

npm install express bcryptjs jsonwebtoken cors
npm install --save-dev nodemon

🧱 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:

npm install jsonwebtoken

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:

GET /api/profile
Authorization: token_here

πŸ“˜ 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

You may also like...