JSON Web Tokens (JWT) provide a secure way to transmit information between parties as a JSON object. In web applications, JWTs are commonly used for authentication - allowing servers to verify user identity without maintaining session state.
A JWT consists of three parts separated by dots: header.payload.signature. The header specifies the algorithm used, the payload contains claims (user data), and the signature ensures the token hasn't been tampered with. When a user logs in with valid credentials, the server creates a JWT containing user information and signs it with a secret key.
The key advantage of JWTs is that they're stateless - all necessary information is contained within the token itself. This makes them perfect for distributed systems and APIs where you don't want to maintain server-side sessions.
In Express applications, JWT authentication typically follows this pattern:
The standard practice is to send JWTs in the Authorization header using the Bearer scheme: Authorization: Bearer <token>. Your middleware extracts this token, verifies it using the same secret key used for signing, and either grants access or returns an authentication error.
1import jwt from 'jsonwebtoken';
2
3// Creating a JWT when user logs in
4const createToken = (userData: any) => {
5 return jwt.sign(
6 { id: userData.id, email: userData.email },
7 'secret-key',
8 { expiresIn: '24h' }
9 );
10};
11
12// Middleware to verify JWT tokens
13const verifyToken = (req: any, res: any, next: any) => {
14 const token = req.headers.authorization?.split(' ')[1];
15
16 if (!token) {
17 return res.status(401).json({ error: 'No token provided' });
18 }
19
20 try {
21 const decoded = jwt.verify(token, 'secret-key');
22 req.user = decoded;
23 next();
24 } catch (error) {
25 res.status(401).json({ error: 'Invalid token' });
26 }
27};