By ApiNest Team • Last updated Aug 24, 2025
Tokens are the front door to your API. This guide shows how to issue, validate, rotate, and scope tokens the right way.
Token types
- API keys: simple opaque tokens for server-to-server access.
- JWTs: signed claims with expiry; great for user identity and short-lived sessions.
Generation
// Node: random opaque token
import { randomBytes } from 'crypto'
const key = randomBytes(32).toString('base64url')Validation
- Check presence, signature (for JWT), expiry, and revocation status.
- Log token prefix only; never full tokens.
JWT verification example
import jwt from 'jsonwebtoken'
function verifyJWT(token){
try {
return jwt.verify(token, process.env.JWT_SECRET)
} catch (e){
return null
}
}Scopes & least privilege
Attach scopes like read:jokes or write:images and enforce at the endpoint.
Rotation
Issue a new token while the old remains valid; revoke the old after rollout.
Threats & mitigations
| Threat | Mitigation |
|---|---|
| Leak in logs | Never log full tokens; rotate immediately if detected |
| Replay | Short expiries, nonce for sensitive actions |
| Phishing | Out-of-band key delivery and dashboard warnings |
FAQ
Where do I store tokens?
Server-side secrets manager or environment variables. Never ship tokens to the browser.
How short should JWT expiry be?
15 minutes for session tokens, refresh with a rotating refresh token.
