Express.js
Beginner
1 min read
JWT Authentication with jsonwebtoken
Example
// npm install jsonwebtoken bcryptjs
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET || 'change_me';
const JWT_EXPIRES = '15m';
// Fake user store (use a real DB in production)
const users = [
{ id: 1, email: 'alice@example.com',
hash: bcrypt.hashSync('Password1!', 10) },
];
// POST /auth/login
router.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = users.find(u => u.email === email);
if (!user || !bcrypt.compareSync(password, user.hash)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign(
{ sub: user.id, email: user.email },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES, algorithm: 'HS256' }
);
res.json({ token, expiresIn: JWT_EXPIRES });
});
// Auth middleware
function authenticate(req, res, next) {
const auth = req.headers.authorization || '';
const [, token] = auth.split(' ');
try {
req.user = jwt.verify(token, JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid or expired token' });
}
}
// Protected route
router.get('/profile', authenticate, (req, res) => {
res.json({ userId: req.user.sub, email: req.user.email });
});
module.exports = router;
Related Resources
Express.js Reference
Complete tag & property list
Express.js How-To Guides
Step-by-step practical guides
Express.js Exercises
Practice what you've learned
More in Express.js