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