Most APIs use token authentication: after login, the server gives the client a token, and the client sends it with every request.
JSON Web Token (JWT)
A JWT has three parts: header.payload.signature. The payload holds data such as the user id. The signature, made with a secret key, proves the token was not changed. The payload is only encoded, not encrypted — never put passwords in it.
Packages
npm install bcrypt jsonwebtoken
The flow
- Register: hash the password with
bcrypt.hash(password, 10)and save the user - Login: find the user, check with
bcrypt.compare(), thenjwt.sign({ sub: user.id }, SECRET, { expiresIn: '1h' }) - The client sends
Authorization: Bearer <token> - Middleware verifies with
jwt.verify()and setsreq.user
Security tips
- Keep
JWT_SECRETlong and in.env - Use short expiry times; refresh tokens for long sessions
- Always use HTTPS
- Rate-limit the login route
For browser apps, storing the token in an httpOnly cookie protects it from JavaScript (XSS).
Example
import express from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
const app = express();
app.use(express.json());
const users = []; // use a real database in your app
const SECRET = process.env.JWT_SECRET;
app.post('/api/register', async (req, res) => {
const { email, password } = req.body;
if (users.some((u) => u.email === email)) return res.status(409).json({ error: 'Email already registered' });
users.push({ id: users.length + 1, email, password: await bcrypt.hash(password, 10) });
res.status(201).json({ message: 'Registered' });
});
app.post('/api/login', async (req, res) => {
const user = users.find((u) => u.email === req.body.email);
if (!user || !(await bcrypt.compare(req.body.password, user.password))) {
return res.status(401).json({ error: 'Invalid email or password' });
}
const token = jwt.sign({ sub: user.id, email: user.email }, SECRET, { expiresIn: '1h' });
res.json({ token });
});
function auth(req, res, next) {
const token = req.get('authorization')?.replace('Bearer ', '');
try {
req.user = jwt.verify(token, SECRET);
next();
} catch {
res.status(401).json({ error: 'Please log in' });
}
}
app.get('/api/me', auth, (req, res) => res.json({ id: req.user.sub, email: req.user.email }));
app.listen(3000);
Register, then log in to receive {"token":"eyJ..."}. GET /api/me with the header Authorization: Bearer eyJ... returns your id and email; without a valid token it returns 401.