JWT Authentication in Hono
Use stateless JWT auth with route-level middleware.
Token Service
- Validate credentials against environment vars.
- Issue 7-day JWT (
HS256). - Verify on protected API routes.
const payload = { username, iat: now, exp: now + 7 * 24 * 60 * 60 };
const token = await sign(payload, env.JWT_SECRET);
Middleware Pattern
Apply auth to /api/*, but skip only public auth endpoints.
const publicAuthRoutes = ['/api/auth/login', '/api/auth/logout'];
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return c.json({ error: 'Unauthorized', message: 'Missing authentication token' }, 401);
}
Endpoint Contract
POST /api/auth/login: returns{ token, expiresIn }.GET /api/auth/me: validates token and returns remaining TTL.POST /api/auth/logout: client-side token removal (stateless server).
Security Notes
- Keep
JWT_SECRETin Workers secrets. - Keep admin credentials in vars/secrets, never frontend.
- Log auth attempts and failures with request IDs.