What Is JWT?
JSON Web Token
A JWT is a compact, self-contained token used for authentication and information exchange. It contains encoded JSON data (claims) that's cryptographically signed so the server can verify it wasn't tampered with — without hitting a database.
How JWT Works
A JWT has three parts separated by dots: header.payload.signature. The header specifies the algorithm (usually HS256 or RS256). The payload contains claims like user ID, role, and expiration time. The signature proves the token hasn't been modified.
JWTs are stateless — the server doesn't need to store sessions. It just verifies the signature and reads the claims. This makes JWTs perfect for microservices where multiple servers need to authenticate requests without sharing a session store.
Why Developers Use JWT
JWTs are the standard for API authentication. Your frontend stores the JWT (usually in memory, not localStorage) and sends it in the Authorization header with every request. The backend verifies the signature and extracts user info without a database lookup.
Key Concepts
- Header — Specifies the token type (JWT) and signing algorithm (HS256, RS256)
- Payload — Contains claims — user ID, email, role, expiration time, and any custom data
- Signature — Cryptographic hash of header + payload + secret key — proves the token is authentic
- Access vs Refresh Tokens — Short-lived access tokens (15 min) for API calls, long-lived refresh tokens (7 days) to get new access tokens
Creating and Verifying JWTs
const jwt = require('jsonwebtoken');
// Create a token
const token = jwt.sign(
{ userId: 42, role: 'admin' },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
);
// Verify a token
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log(decoded.userId); // 42
} catch (err) {
console.log('Invalid token');
} Frequently Asked Questions
Should I store JWTs in localStorage?
No. localStorage is vulnerable to XSS attacks. Store access tokens in memory (a variable) and refresh tokens in httpOnly cookies. This is the most secure approach.
What happens when a JWT expires?
The server rejects it with a 401 status. The client uses a refresh token to get a new access token without requiring the user to log in again.