Authentication in Node.js

📘 Node.js 👁 45 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Authentication is the process of verifying who a user is before granting access to protected resources.
In Node.js applications, authentication is commonly implemented using sessions, tokens, or third-party providers.


1. Why Authentication Is Important

  • Protects user data

  • Prevents unauthorized access

  • Enables personalized experiences

  • Required for secure APIs


2. Common Authentication Methods

2.1 Session-Based Authentication

  • Server stores session data

  • Client stores session ID (cookie)

Flow:

LoginSession created → Session ID stored → Verified on requests

✔ Suitable for traditional web apps


2.2 Token-Based Authentication (JWT)

  • Server issues a token

  • Client sends token with each request

  • No server-side session storage

✔ Ideal for APIs and mobile apps


2.3 OAuth / Third-Party Authentication

  • Login using Google, GitHub, etc.

  • Delegates authentication to trusted providers

✔ Reduces password handling


3. Password-Based Authentication

3.1 Hashing Passwords

Never store plain passwords.
Use bcrypt for hashing.

npm install bcrypt
const bcrypt = require('bcrypt'); const hashedPassword = await bcrypt.hash(password, 10);

3.2 Verifying Passwords

const isMatch = await bcrypt.compare(password, user.password);

4. Authentication Using JWT (JSON Web Token)

Install JWT Package

npm install jsonwebtoken

Generate Token on Login

const jwt = require('jsonwebtoken'); const token = jwt.sign( { userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' } );

Send Token to Client

res.json({ token });

Verify Token Middleware

function auth(req, res, next) { const token = req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).send('Access denied'); try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; next(); } catch { res.status(403).send('Invalid token'); } }

5. Protecting Routes

app.get('/profile', auth, (req, res) => { res.send(`User ID: ${req.user.userId}`); });

6. Authentication with Sessions (Express)

npm install express-session
app.use(session({ secret: 'secret-key', resave: false, saveUninitialized: false }));

7. Authentication vs Authorization

AuthenticationAuthorization
Who you areWhat you can do
Login processAccess control
Identity checkPermission check

8. Security Best Practices

  • Use HTTPS

  • Hash passwords

  • Set token expiration

  • Store secrets in environment variables

  • Implement logout and token revocation


9. Common Mistakes

❌ Storing passwords in plain text
❌ Hardcoding secret keys
❌ Not expiring tokens
❌ Exposing sensitive data


10. Real-World Authentication Flow

User Login ↓ Credentials Verified ↓ Token/Session Created ↓ Protected Resource Access

11. Summary

  • Authentication verifies user identity

  • Node.js supports sessions, JWT, and OAuth

  • JWT is most common for APIs

  • Security best practices are essential


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes