What is JWT?
- JWT (JSON Web Token) is a compact token used for secure info exchange.
- Contains 3 parts:
- Header: Type & signing algorithm.
- Payload: Claims (user data).
- Signature: Validates integrity.
JWT Example in Node.js
Setup Node.js Project
npm init -y
npm install express jsonwebtoken bcryptjs
Code: Simple Login & Token Creation
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const app = express();
app.use(express.json());
const users = [];
const JWT_SECRET = 'your-secret-key'; // this should be stored inside the env file
app.post('/signup', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ username, password: hashedPassword });
res.status(201).send('User registered');
});
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).send('Invalid credentials');
}
const token = jwt.sign({ username }, JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
});
Code: Protecting Routes with JWT Middleware
const authenticateToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.status(403).send('Token required');
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.status(403).send('Invalid token');
req.user = user;
next();
});
};
app.get('/dashboard', authenticateToken, (req, res) => {
res.send(`Hello ${req.user.username}`);
});
Pros & Cons of JWT
Pros:
- Stateless: No session storage.
- Compact: Easy to transmit.
- Cross-domain: Securely works across systems.
Cons:
- Token size: Large tokens can affect performance.
- Cannot revoke: Once issued, difficult to invalidate some bypass this issue by using refresh tokens.
- Data exposure: Payload is not encrypted (avoid sensitive info).
Conclusion
JWT makes authentication simple and scalable, but be aware of its security implications. Keep tokens secure with short expiration times and HTTPS.
Top comments (1)
Thank you for the info