Enhanced Middleware
Production-grade middleware with session tracking, storage adapters, and per-session control
What is Enhanced Middleware?
The Enhanced Middleware (createEnhancedAgentShieldMiddleware) adds persistent session state, storage adapters, and granular per-session control on top of the basic withAgentShield middleware. Use it when you need:
- Session persistence — track agent sessions across multiple requests
- Storage backends — persist detection events to Redis for production or memory for development
- Detection callbacks — run custom logic (alerts, logging, analytics) when agents are detected
- Request-level metadata — access detection results downstream via request headers
If you only need stateless detect/block behavior, the basic middleware is simpler and sufficient.
Using .NET? The ASP.NET Core middleware includes session
tracking, signature verification, and policy evaluation in the base package — there is no separate
"enhanced" middleware. Enable these features via CheckpointOptions (e.g., EnableSessionTracking = true). This page covers the Node.js packages only.
Installation
The enhanced middleware ships in the same packages — no additional installation needed:
npm install @kya-os/agentshield-nextjsnpm install @kya-os/agentshield-expressBasic Setup
Create or update your middleware.ts:
import { createEnhancedAgentShieldMiddleware } from '@kya-os/agentshield-nextjs';
export default createEnhancedAgentShieldMiddleware({
onAgentDetected: 'block',
confidenceThreshold: 0.7,
});
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};import express from 'express';
import { createEnhancedAgentShieldMiddleware } from '@kya-os/agentshield-express';
const app = express();
app.use(
createEnhancedAgentShieldMiddleware({
onAgentDetected: 'block',
confidenceThreshold: 70,
})
);
app.get('/', (req, res) => {
res.json({ message: 'Protected by Checkpoint' });
});
app.listen(3000);Confidence scale differs between packages. Next.js uses a 0–1 scale (default 0.7). Express
uses a 0–100 scale (default 70). Both represent the same 70% threshold.
Storage Adapters
The enhanced middleware supports pluggable storage backends for persisting detection events and session data.
Memory (Development)
In-memory storage is the default — no configuration needed. Data is lost on restart and not shared across instances.
createEnhancedAgentShieldMiddleware({
// Memory storage is used by default when no storage config is provided
});createEnhancedAgentShieldMiddleware({
storage: {
type: 'memory',
},
});Redis (Production)
Use Redis for persistent, cross-instance storage. Both packages use Upstash Redis.
createEnhancedAgentShieldMiddleware({
storage: {
type: 'redis',
redis: {
url: process.env.REDIS_URL!,
token: process.env.REDIS_TOKEN!,
},
ttl: 86400, // 24 hours (default)
},
});createEnhancedAgentShieldMiddleware({
storage: {
type: 'redis',
redis: {
url: process.env.REDIS_URL!,
token: process.env.REDIS_TOKEN!,
},
ttl: 86400, // 24 hours (default)
},
});Memory storage is not suitable for production — data is lost on restart and not shared across instances. Use Redis for production deployments.
Custom Adapter
Implement the StorageAdapter interface to use your own backend:
import type { StorageAdapter } from '@kya-os/agentshield-nextjs';
const myAdapter: StorageAdapter = {
storeEvent: async (event) => {
/* ... */
},
getRecentEvents: async (limit) => {
/* ... */
},
getSessionEvents: async (sessionId) => {
/* ... */
},
storeSession: async (session) => {
/* ... */
},
getSession: async (sessionId) => {
/* ... */
},
getRecentSessions: async (limit) => {
/* ... */
},
cleanup: async (olderThan) => {
/* optional */
},
};
createEnhancedAgentShieldMiddleware({
storage: { type: 'custom', custom: myAdapter },
});Detection Callbacks
onAgentDetected — Action on Detection
Controls what happens when an agent is detected above the confidence threshold:
| Value | Behavior |
|---|---|
'block' | Return HTTP 403 with JSON error response |
'log' | Log the detection and allow the request through |
'allow' | Allow the request through silently (detections still stored if configured) |
onDetection — Custom Callback
Run custom logic when an agent is detected. This fires before the onAgentDetected action.
createEnhancedAgentShieldMiddleware({
onDetection: async (result, context) => {
console.log(`Agent detected: ${result.detectedAgent} (${result.confidence})`);
console.log(`Path: ${context.url}, IP: ${context.ipAddress}`);
// Send to your alerting system, analytics, etc.
},
onAgentDetected: 'block',
});The Next.js callback receives (result: DetectionResult, context: DetectionInput) where context includes userAgent, ipAddress, headers, url, method, and timestamp.
createEnhancedAgentShieldMiddleware({
onDetection: async (result, req) => {
console.log(`Agent detected: ${result.detectedAgent} (${result.confidence})`);
console.log(`Path: ${req.path}, IP: ${req.ip}`);
// Send to your alerting system, analytics, etc.
},
onAgentDetected: 'block',
});The Express callback receives (result: DetectionResult, req: Request) — the standard Express request object.
onDetection does not control blocking — it runs alongside the onAgentDetected action. Use it
for side effects like logging, alerting, or analytics.
Session Tracking
Session tracking is enabled by default. The enhanced middleware groups requests into sessions based on IP address, user agent, and time window.
createEnhancedAgentShieldMiddleware({
sessionTracking: {
enabled: true, // default
ttl: 3600, // session TTL in seconds (optional)
},
});When storage is configured, each session stores:
- First and last seen timestamps
- Total event count
- All unique paths accessed
- Average confidence across detections
- Verification methods used
Response Headers
The enhanced middleware adds detection metadata to response headers:
| Header | Value | When |
|---|---|---|
KYA-Detected | true / false | All responses |
KYA-Confidence | 0–100 | When agent detected |
KYA-Agent | Agent name (e.g. ChatGPT) | When agent detected |
KYA-Verification | pattern / signature | When agent detected |
KYA-AI-Visitor | true | High confidence (>90%) only |
Request Metadata (Express)
In Express, the enhanced middleware attaches detection results to the request object for use in downstream handlers:
app.get('/api/data', (req, res) => {
if (req.agentShield?.detected) {
console.log(`Agent: ${req.agentShield.agent?.name}`);
console.log(`Confidence: ${req.agentShield.confidence}`);
console.log(`Method: ${req.agentShield.verificationMethod}`);
}
res.json({ data: 'your response' });
});Configuration Reference
Next.js
| Option | Type | Default | Description |
|---|---|---|---|
storage | StorageConfig | — | Storage backend (memory, redis, or custom) |
sessionTracking | { enabled?: boolean; ttl?: number } | { enabled: true } | Session tracking configuration |
skipPaths | string[] | — | Path prefixes to skip detection |
onAgentDetected | 'block' | 'log' | 'allow' | — | Action when agent detected |
onDetection | (result, context) => void | Promise | — | Custom detection callback |
confidenceThreshold | number | 0.7 | Confidence threshold (0–1 scale) |
blockedResponse | { status?: number; message?: string } | { status: 403, message: 'Access denied: AI agent detected' } | Custom block response |
Express
| Option | Type | Default | Description |
|---|---|---|---|
storage | StorageConfig | — | Storage backend (memory, redis, or custom) |
sessionTracking | { enabled?: boolean; ttl?: number } | { enabled: true } | Session tracking configuration |
skipPaths | string[] | — | Path prefixes to skip detection |
onAgentDetected | 'block' | 'log' | 'allow' | — | Action when agent detected |
onDetection | (result, req) => void | Promise | — | Custom detection callback |
confidenceThreshold | number | 70 | Confidence threshold (0–100 scale) |
blockedResponse | { status?: number; message?: string } | { status: 403, message: 'Access denied: AI agent detected' } | Custom block response |
Enhanced vs Basic Middleware
| Feature | Basic (withAgentShield) | Enhanced (createEnhancedAgentShieldMiddleware) |
|---|---|---|
| Storage | No built-in storage | Memory, Redis, or custom adapter |
| Session tracking | Cookie-based | Storage-backed with event persistence |
| Detection callback | Event emitters (Next.js) | Simple onDetection callback |
| Request metadata | — | req.agentShield object (Express) |
| Response headers | Basic | Full detection metadata |
| Use case | Simple detect/block | Production apps needing session state |
Next Steps
- Basic Middleware — Simpler stateless middleware
- Policies — Configure enforcement rules
- Detection — How detection works