Middleware Reference
Detailed API reference for Gatekeeper middleware
init(getOptions)
Creates middleware that initializes the Mira context with service identification, a unique trace ID, and pre-configured OpenAI client.
init(() => ({ serviceId: 'verify' })) // 'verify' or 'inference'What it does
- Validates required env vars:
CF_ACCOUNT_ID,CF_GATEWAY_ID,CF_AIG_TOKEN,CF_AIG_BYOK_ALIAS,USAGE_QUEUE - Validates
serviceId(must be'verify'or'inference') - Generates a unique
traceId(UUID) for request tracing - Creates an OpenAI client configured for Cloudflare AI Gateway
- Wraps the OpenAI client to automatically report usage via queue
- Sets mira context on the request
Options
| Property | Type | Description |
|---|---|---|
serviceId | 'verify' | 'inference' | Service identifier for this worker |
Mira Context
After init() runs, access the context via c.get('mira'):
interface MiraContext {
traceId: string; // Unique request ID (UUID)
serviceId: string; // Service identifier ('verify' | 'inference')
openai: OpenAI; // Pre-configured OpenAI client with auto usage reporting
}auth()
Creates middleware that validates API keys and checks account balance. Requires init() to be called first.
auth() // No options needed - gets serviceId from mira contextWhat it does
- Gets
serviceIdfrom mira context (set byinit) - Extracts Bearer token from
Authorizationheader - Validates token prefix matches service (e.g.,
mk_verify_...) - Calls Console Service to validate the full key
- Checks if the app has sufficient balance
- Sets auth context on the request
- Auto-enriches mira context with auth metadata for AI Gateway logging
Auth Context
After auth() runs, access the context via c.get('auth'):
interface AuthContext {
keyId: string; // API key identifier
appId: string; // App identifier
userId: string; // User identifier
}AI Gateway Metadata
After auth runs, all OpenAI client requests automatically include metadata for logging and billing:
serviceId- Service identifierappId- App identifierextra- JSON string containingtraceId,requestedModel,keyId,userId
Usage is automatically reported to Console Service via queue after each completion.
Errors Thrown
AuthError- When authentication fails (401)InsufficientBalanceError- When app has insufficient balance (402)
rateLimit(options)
Creates middleware that enforces rate limits per API key.
rateLimit({
rpm: 60, // Requests per minute
rpd: 1000, // Requests per day
})What it does
- Reads rate limit state from KV storage
- Checks against per-minute and per-day limits
- Increments counters and saves state
- Sets rate limit headers on response
Options
| Property | Type | Description |
|---|---|---|
rpm | number | Maximum requests per minute |
rpd | number | Maximum requests per day |
Response Headers
X-RateLimit-Limit-Minute: 60
X-RateLimit-Remaining-Minute: 45
X-RateLimit-Limit-Day: 1000
X-RateLimit-Remaining-Day: 955Errors Thrown
RateLimitError- When rate limit is exceeded (429)
Full Example
import { Hono } from 'hono';
import {
init,
auth,
rateLimit,
AuthError,
RateLimitError,
InsufficientBalanceError,
type AuthContext,
type MiraContext,
} from '@mira.network/gatekeeper';
type Env = {
CF_ACCOUNT_ID: string;
CF_GATEWAY_ID: string;
CF_AIG_TOKEN: string; // AI Gateway auth token (cf-aig-authorization)
CF_AIG_BYOK_ALIAS: string; // alias of the OpenRouter key stored on the gateway
CONSOLE_SERVICE: Service;
RATE_LIMIT_KV: KVNamespace;
USAGE_QUEUE: Queue;
};
const app = new Hono<{
Bindings: Env;
Variables: { auth: AuthContext; mira: MiraContext };
}>();
// Initialize Mira context (reads AI Gateway config from env vars)
app.use('/*', init(() => ({ serviceId: 'verify' })));
// Global error handler
app.onError((err, c) => {
if (err instanceof AuthError) {
return c.json({ error: err.message }, 401);
}
if (err instanceof RateLimitError) {
return c.json({ error: err.message, resetAt: err.resetAt }, 429);
}
if (err instanceof InsufficientBalanceError) {
return c.json({ error: 'Insufficient balance', balance: err.balance }, 402);
}
console.error(err);
return c.json({ error: 'Internal error' }, 500);
});
// Health check (no auth required)
app.get('/health', (c) => c.json({ status: 'ok' }));
// Protected routes - auth + rate limit
app.use('/v1/*', auth());
app.use('/v1/*', rateLimit({ rpm: 60, rpd: 1000 }));
app.post('/v1/chat', async (c) => {
const { openai } = c.get('mira');
// Use pre-configured OpenAI client
// Usage is automatically reported via queue after completion
const completion = await openai.chat.completions.create({
model: 'openai/gpt-4o-mini',
messages: [{ role: 'user', content: 'Hello!' }],
});
return c.json({ result: completion.choices[0].message.content });
});
export default app;