1. Introduction
As APIs become more central to modern web apps, securing them is critical. One common and powerful method is JWT (JSON Web Token) authentication. It allows secure, stateless communication between client and server.
In this guide, we’ll walk through the core concepts, the authentication flow, and how to implement JWT in a Node.js + Express API.
2. What is JWT?
JWT (JSON Web Token) is a compact, URL-safe way of representing claims between two parties. It’s widely used for authentication.
A JWT has three parts:
HEADER.PAYLOAD.SIGNATURE
Example Token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImlhdCI6MTY3Nzg0NTM1Nn0.vPObNvSaNfrqzuhRRYtNnmlbRrFYP7oowC_NWkpiW1k
Part | purpose |
---|---|
Header | Algorithm + Token type |
Payload | Claims (user ID, role, etc.) |
Signature | Verifies token integrity (signed) |
3. JWT Authentication Flow
4. Example Project Structure (Node.js + Express)
project/
├── controllers/
│ └── auth.js
├── middleware/
│ └── authMiddleware.js
├── routes/
│ └── authRoutes.js
├── app.js
├── .env
└── package.json
5. Code Breakdown
5.1 Install Required Packages
npm install express jsonwebtoken dotenv
5.2 Generate Token (Login Route)
const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET;
function login(req, res) {
const user = { id: 1, username: 'ilyas' }; // dummy user
const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '1h' });
res.json({ token });
}
5.3 Protect Routes with Middleware
function verifyToken(req, res, next) {
const token = req.headers['authorization']?.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) return res.sendStatus(403);
req.userId = decoded.userId;
next();
});
}
5.4 Secure Endpoint Example
app.get('/profile', verifyToken, (req, res) => {
res.send(`This is a protected route for user ${req.userId}`);
});
6. Best Practices for JWT
Tip | Why It Matters |
---|---|
Use short expiration times | Limits damage from stolen tokens |
Store tokens securely | Avoid localStorage for sensitive data |
Rotate tokens periodically | Increase security |
Never store JWT secret in code | Use environment variables |
7. Conclusion
JWT is a powerful way to secure RESTful APIs in a stateless and scalable manner. You now understand the structure, flow, and implementation of JWT authentication in a Node.js Express app.
Top comments (0)