What is JWT Encoding? Secure Token-Based Authentication
Last updated: July 18, 2025 • 7 min read
🔐 Definition
JWT (JSON Web Token) is a compact, URL-safe means of representing claims between two parties. A JWT consists of three parts: a header, a payload, and a signature — each Base64Url encoded and concatenated with dots.
⚙️ How JWT Encoding Works
- Header: Specifies the algorithm (e.g., HS256) and token type (
JWT
). - Payload: Contains claims (registered, public, and custom) such as
iss
,sub
,exp
, and application-specific data. - Signature: Calculated by hashing the encoded header and payload with a secret or private key.
// Example JWT structure: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkRl bW8gVXNlciIsImlhdCI6MTYyNzI0MjU2OX0 . TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
🚀 Practical Applications
- Authentication: JWTs are issued after login and sent in HTTP headers to secure routes.
- Authorization: Embed user roles and permissions in the token for resource access control.
- Single Sign-On (SSO): Transfer user identity across domains without storing session state.
- Information Exchange: Share trusted data between microservices or external partners.
🛠️ Implementing JWTs in Next.js
In Next.js, you can use libraries like jsonwebtoken
ornext-auth
to sign and verify tokens:
import jwt from 'jsonwebtoken'; // Signing a token const token = jwt.sign( { sub: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' } ); // Verifying a token const decoded = jwt.verify(token, process.env.JWT_SECRET); console.log(decoded); // { sub: '123', role: 'admin', iat: ..., exp: ... }
💡 Best Practices
- Use strong, secret keys and rotate them periodically.
- Set appropriate
exp
(expiration) andnbf
(not before) claims to limit token lifespan. - Store JWTs securely on the client (e.g., HttpOnly cookies).
- Avoid storing sensitive data in the payload; it's simply encoded, not encrypted.
- Implement token revocation or blacklisting for compromised tokens.