Chanfana integrates with the middleware capabilities of your underlying router (Hono or itty-router).
Router Middleware
You can apply middleware for authentication, logging, or request modification. When using Hono, you can pass middleware directly into the Chanfana route registration method:
openapi.get('/path', middleware, EndpointClass);
Endpoint Interceptors
Chanfana's auto endpoints (e.g., CreateEndpoint, ReadEndpoint, UpdateEndpoint, DeleteEndpoint, ListEndpoint) provide lifecycle methods that act as interceptors. You can override these to perform actions before or after the core logic:
before: Executes before the core logic (useful for authorization or data validation).after: Executes after the core logic (useful for post-processing or logging).
Refer to the specific documentation for each auto-endpoint type to see the full list of available lifecycle methods.
import { Hono } from 'hono';
import { fromHono, OpenAPIRoute } from 'chanfana';
const authMiddleware = async (c, next) => {
const apiKey = c.req.header('X-API-Key');
if (apiKey !== 'valid-api-key') {
return c.json({ success: false, message: 'Unauthorized' }, 401);
}
await next();
};
class ProtectedEndpoint extends OpenAPIRoute {
schema = { responses: { "200": { description: 'Protected resource' } } };
async handle(c: any) { return { message: 'Protected data' }; }
}
const app = new Hono();
const openapi = fromHono(app);
// Apply middleware to a specific route
openapi.get('/protected', authMiddleware, ProtectedEndpoint);
export default app;