Kind: Function
Source: src/middleware/jwt/jwt.ts
Part of: Middleware
JWT Auth Middleware for Hono.
jwt creates Hono middleware that reads a JWT from the request, verifies it with the configured options, and stores the decoded payload in the request context. Routes protected by this middleware can read the payload from c.get('jwtPayload').
Signature
tsfunction jwt(options: { secret: SignatureKey cookie?: | string | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions } alg: SignatureAlgorithm headerName?: string realm?: string verification?: VerifyOptions }): MiddlewareHandler
Parameters
| Name | Type |
|---|---|
options | `{ secret: SignatureKey cookie?: |
Returns: MiddlewareHandler
Diagram
mermaidgraph LR Request[Incoming request] --> Middleware[jwt middleware] Middleware --> Token[Read JWT] Token --> Verify[Verify signature and claims] Verify -->|Valid| Context[Store jwtPayload in context] Context --> Handler[Route handler] Verify -->|Invalid or missing| Unauthorized[Unauthorized response]
Usage
tsimport { Hono } from 'hono'
import { jwt } from 'hono/jwt'
const app = new Hono()
app.use(
'/api/*',
jwt({
secret: 'my-secret-key',
})
)
app.get('/api/profile', (c) => {
const payload = c.get('jwtPayload')
return c.json({
userId: payload.sub,
})
})
export default app
AI Coding Instructions
- Register
jwtbefore route handlers that readc.get('jwtPayload'). - Pass the same secret or public-key configuration used when signing tokens.
- Scope the middleware to protected route paths instead of applying it to public endpoints.
- Read claims from
jwtPayloadin handlers and validate application-specific fields before granting access. - Return tokens through the expected authorization header format when calling protected routes.
Was this page helpful?