You have two solid choices for auth: JWT or Sessions. Both work. Both are secure when done right. The difference? Sessions are like a hotel key card, JWT is like a driver's license.
Here's a quick framework to help you choose the right one for your next project.
The 3-Question Framework
-
What are you building?
- Traditional web app with server-rendered pages? → Use Sessions.
- An API for a React/Vue/Mobile app? → Use JWT.
-
How many users will you have?
- Under 1K concurrent users? → Either works fine.
- 1K+ concurrent users? → JWT scales easier because it's stateless.
-
How sensitive is the data?
- Banking or medical app where you need to log a user out instantly? → Sessions are safer because you can kill the session on the server immediately.
- Standard app? → JWT is fine.
My Go-To JWT Middleware
For most of my API projects, I end up using JWTs. Here’s the simple and clean Express.js middleware I use to protect my routes. It's stateless and works perfectly with microservices.
// JWT middleware - clean and stateless
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ error: 'Invalid or expired token' });
}
req.user = user; // Now you have user info in all protected routes
next();
});
};
This is a condensed version of a more detailed guide I wrote on my personal blog, which includes a full comparison table and more code examples.
Originally published on my personal blog: https://www.kripanshu.me/blog/posts/jwt-vs-sessions/index.html
Top comments (0)