JWT Authentication in Node.js Explained Simply
What Is Authentication?
Authentication verifies who a user is.
Example:
Login systems
Admin dashboards
Banking apps
Without authentication:
Anyone could access protected data
Why Authentication Is Required
Applications need to:
Identify users
Protect private routes
Restrict access
Maintain login state
What Is JWT?
JWT stands for:
JSON Web Token
It is a token-based authentication system.
After login:
Server creates token
Client stores token
Client sends token with requests
Server verifies token
JWT Is Stateless
Server does not store login session data.
Instead:
Token itself contains user information
This is called:
Stateless authentication
JWT Login Flow
Structure of a JWT
A JWT has 3 parts:
Header.Payload.Signature
Example JWT
xxxxx.yyyyy.zzzzz
1. Header
Contains token metadata.
Example:
{
"alg": "HS256",
"typ": "JWT"
}
2. Payload
Contains user data.
Example:
{
"userId": 15,
"role": "admin"
}
3. Signature
Used to verify token authenticity.
Prevents tampering.
JWT Structure Visualization
Installing JWT Package
npm install jsonwebtoken
Creating a JWT Token
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{
userId: 1
},
"secretkey",
{
expiresIn: "1h"
}
);
console.log(token);
What jwt.sign() Does
Login Example
app.post("/login", (req, res) => {
const user = {
id: 1,
email: "[email protected]"
};
const token = jwt.sign(
{
userId: user.id
},
"secretkey"
);
res.json({ token });
});
Sending Token With Requests
Usually sent in request headers.
Authorization Header
Authorization: Bearer TOKEN_HERE
Example Request Flow
Protecting Routes Using JWT
Use middleware to verify token.
Example Middleware
const jwt = require("jsonwebtoken");
function verifyToken(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send("Token missing");
}
const token = authHeader.split(" ")[1];
try {
const decoded = jwt.verify(token, "secretkey");
req.user = decoded;
next();
} catch (error) {
res.status(401).send("Invalid token");
}
}
Protected Route Example
app.get("/dashboard", verifyToken, (req, res) => {
res.send("Protected Dashboard");
});
Token Validation Lifecycle
Why JWT Is Popular
Common JWT Use Cases
Common Beginner Mistakes
Storing Sensitive Data in Payload
Incorrect:
{
"password": "123456"
}
JWT payload is readable.
Never store passwords.
Forgetting Token Verification
Creating token alone is not enough.
Always verify before allowing access.
Simple JWT Flow Summary
User Logs In ↓ Server Creates JWT ↓ Client Stores Token ↓ Client Sends Token With Requests ↓ Server Verifies Token ↓ Access Granted or Denied
Practice Example
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{
username: "Ali"
},
"mysecret"
);
console.log(token);
const decoded = jwt.verify(token, "mysecret");
console.log(decoded);
Key Takeaways
Final Notes
JWT authentication is heavily used in modern backend systems because it works well with:
APIs
Mobile apps
React frontends
Distributed systems
Understanding JWT basics is important before learning:
Refresh tokens
OAuth
Access control
Role-based authentication
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!