How JWT Authentication Works
User Signs In
User authenticates via Better Auth (email/password or OAuth). A session is created and stored in the database.
JWT Generation
When the frontend makes an API request, Better Auth generates a signed JWT containing the user’s identity.
Token Injection
The API proxy automatically injects the JWT as a Bearer token in the Authorization header.
JWT Plugin Configuration
The JWT plugin is configured in both server and client configurations:Server Configuration
src/lib/auth.ts
Client Configuration
src/lib/auth-client.ts
Token Generation
JWT tokens are generated server-side using Better Auth’sgetToken API:
src/app/api/[...path]/route.ts
- Validates the current session from the request cookies
- Generates a signed JWT containing user claims
- Returns the token for use in backend requests
Tokens are generated on-demand for each backend request, not stored long-term. This ensures tokens are always fresh and reduces security risks.
JWT Structure
A typical JWT generated by Better Auth contains:Header
Payload
Signature
The signature is created using the private key stored in the database, ensuring the token cannot be forged.JWKS Endpoint
Better Auth automatically provides a JSON Web Key Set (JWKS) endpoint at:Backend Token Validation
Here’s how your backend API should validate JWT tokens:Token Lifecycle
Security Best Practices
Short Expiration
Keep JWT expiration times short (15-30 minutes) to minimize risk if a token is compromised.
JWKS Caching
Cache JWKS responses on your backend to reduce latency and external requests.
HTTPS Only
Always use HTTPS to prevent tokens from being intercepted in transit.
Validate Claims
Verify all claims (exp, iat, sub) in addition to the signature.
Key Storage
JWT signing keys are stored in thejwks table in your database:
- Private Key: Used to sign tokens (never exposed publicly)
- Public Key: Distributed via JWKS endpoint for verification
- Key Rotation: Better Auth can rotate keys for enhanced security
Troubleshooting
401 Unauthorized errors
401 Unauthorized errors
Token expiration issues
Token expiration issues
If tokens expire too quickly:
- Ensure system clocks are synchronized (use NTP)
- Check if token expiration time is appropriate for your use case
- Verify the API proxy is generating fresh tokens for each request
JWKS fetch failures
JWKS fetch failures
If your backend cannot fetch the JWKS:
- Verify the JWKS URL is accessible from your backend
- Check firewall rules and network connectivity
- Ensure HTTPS certificates are valid
- Implement retry logic with exponential backoff
Next Steps
API Proxy
Learn how the API proxy automatically injects JWT tokens
Database Schema
Understand how JWT keys are stored in the database