What is a JWT (JSON Web Token)?
A JWT lets any service check who a user is without calling your database. Here's what's inside one, how signing works, when to use JWTs instead of sessions, and the mistakes that get apps breached.
JWT vs session cookie at a glance
|
JWT |
Session cookie | |
|---|---|---|
|
Where the state lives |
Inside the token (stateless) |
In a session store on the server |
|
What the client holds |
A signed token with readable claims |
A random, meaningless session ID |
|
How the server checks it |
Verifies the signature locally, no lookup |
Looks up the session ID on every request |
|
Logging a user out |
Hard before expiry; needs a denylist or short lifetimes |
Delete the session and it's gone instantly |
|
Size per request |
Hundreds of bytes to a few KB |
A few dozen bytes |
|
Across services and domains |
Any service with the key can verify it |
Needs a shared store and same-site cookies |
|
Typical use |
APIs, microservices, single sign-on, mobile apps |
Traditional web apps with one backend |
What a JWT is used for
JWTs are defined in RFC 7519. Their job is to carry trusted facts, called claims, from the system that issues them to the systems that need them. Common uses:
API access tokens. After sign-in, the auth server issues a JWT that the client sends with each API call.
Single sign-on. OpenID Connect ID tokens are always JWTs, which is how one login works across many apps.
Service-to-service calls. One backend proves its identity to another without sharing a database.
Short-lived links, such as email verification or password reset, where the token itself carries the user ID and expiry.
The appeal is that verification is local. An API that receives a JWT checks the signature with a key it already has, instead of asking a session store "is this user logged in?" on every request.
How a JWT works
A JWT looks like a long string with two dots in it: header.payload.signature. Each part is JSON encoded with base64url, a URL-safe form of base64.
Header
Says which algorithm signed the token, for example {"alg": "HS256", "typ": "JWT"}.
Payload
Holds the claims. RFC 7519 registers a few standard ones:
sub: the subject, usually the user IDiss: who issued the tokenaud: who the token is meant forexp: when it expires, in seconds since 1970iat: when it was issuedjti: a unique ID for the token, handy for revocation lists
You can add your own claims, such as a role or tenant ID. Keep them small, because the token travels with every request.
Signature
The issuer signs the encoded header and payload with a key. If anyone changes a single character of the payload, the signature no longer matches and verification fails.
HS256 vs RS256
HS256 uses one shared secret (HMAC with SHA-256) to both sign and verify. It's simple, but every service that verifies tokens can also mint them. RS256 uses an RSA private key to sign and a public key to verify, so only the issuer can create tokens and any service can check them. Auth providers usually publish their public keys at a JWKS endpoint. ES256 works like RS256 with smaller elliptic-curve keys.
Example: signing and verifying a JWT in Node.js
This uses the widely used jsonwebtoken library. Note that verify pins the allowed algorithm and checks the issuer and audience, not just the signature.
import jwt from "jsonwebtoken";
const secret = process.env.JWT_SECRET; // never hard-code it
// Issue a token after the user signs in
const token = jwt.sign({ sub: "user-42", role: "member" }, secret, {
algorithm: "HS256",
expiresIn: "15m",
issuer: "auth.example.com",
audience: "api.example.com",
});
// Verify it on each API request
try {
const claims = jwt.verify(token, secret, {
algorithms: ["HS256"],
issuer: "auth.example.com",
audience: "api.example.com",
});
console.log(claims.sub); // "user-42"
} catch (err) {
// TokenExpiredError, JsonWebTokenError, etc.: reject with 401
}
JWT security best practices
Pin the algorithm when verifying. Never let the token's own header decide how it's checked.
Always validate
exp,issandaud, not only the signature. A valid token for another app is still the wrong token.Keep access tokens short-lived, around 5 to 15 minutes, and use a refresh token to get new ones.
Use asymmetric keys (RS256 or ES256) when several services verify tokens, so only the issuer can sign.
Rotate signing keys and publish them with a key ID (
kid) so verifiers know which key to use.Store tokens safely in the browser. An HttpOnly, Secure, SameSite cookie or in-memory storage beats
localStorage, which any injected script can read.Send JWTs over HTTPS only, in the
Authorization: Bearerheader.
Rule of thumb: treat a JWT like cash. Whoever holds it can spend it until it expires, so keep it short-lived, send it only over HTTPS, and never put anything in it you wouldn't show the user.
Limits and pitfalls
You can't easily revoke a JWT. Once issued, it's valid until
exp. If a user logs out or is banned, you need short lifetimes, a denylist keyed onjti, or a key rotation to cut access.The payload is not secret. Base64url is encoding, not encryption. Anyone holding the token can decode it, so never put passwords, API keys or personal data in it. If you need encryption, that's JWE, a separate standard.
The
alg: nonetrap. Some old libraries accepted unsigned tokens marked"alg": "none", or let an attacker switch RS256 to HS256 and sign with the public key. Pinning the algorithm closes both holes.Tokens grow. Every claim adds bytes to every request. Put an ID in the token and look up the rest when you need it.
Stale claims. If a user's role changes, existing tokens still carry the old role until they expire.
JWTs aren't always the right tool. For a single web app with one backend, a plain session cookie is simpler and easier to revoke.
Using JWTs with CometChat
Most apps that add chat already have their own login, often JWT-based. You don't need a second login for chat.
One login for your app and its chat
Keep your JWTs for your own API. When a signed-in user opens chat, your server verifies their JWT, then requests a CometChat auth token for that user with the Create Auth Token endpoint (
POST /v3/users/{uid}/auth_tokens), authenticated with your REST API key. Your app passes it toCometChat.login(authToken)and the SDK manages the session. Your secret keys never leave the server, and users never see a second sign-in.
Frequently asked questions
Is a JWT encrypted?
No. A standard JWT is signed, not encrypted. The signature stops anyone changing it, but anyone holding the token can read the payload. Encrypted tokens use a separate standard called JWE.
Where should I store a JWT in the browser?
An HttpOnly, Secure, SameSite cookie or in-memory storage is safest. localStorage is convenient, but any script injected through an XSS bug can read it.
How do you invalidate a JWT?
You can't change an issued JWT, so keep lifetimes short and use refresh tokens. To cut access early, keep a denylist of token IDs (the jti claim) or rotate the signing key.
What is the difference between HS256 and RS256?
HS256 signs and verifies with one shared secret. RS256 signs with a private key and verifies with a public key, so services that check tokens can't create them.
What is the difference between JWT and OAuth?
OAuth 2.0 is a framework for granting an app access to an API. JWT is a token format. OAuth access tokens are often JWTs, and OpenID Connect ID tokens always are.