Checkpoint Docs
Enforce

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-nextjs
npm install @kya-os/agentshield-express

Basic 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:

ValueBehavior
'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:

HeaderValueWhen
KYA-Detectedtrue / falseAll responses
KYA-Confidence0–100When agent detected
KYA-AgentAgent name (e.g. ChatGPT)When agent detected
KYA-Verificationpattern / signatureWhen agent detected
KYA-AI-VisitortrueHigh 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

OptionTypeDefaultDescription
storageStorageConfigStorage backend (memory, redis, or custom)
sessionTracking{ enabled?: boolean; ttl?: number }{ enabled: true }Session tracking configuration
skipPathsstring[]Path prefixes to skip detection
onAgentDetected'block' | 'log' | 'allow'Action when agent detected
onDetection(result, context) => void | PromiseCustom detection callback
confidenceThresholdnumber0.7Confidence threshold (0–1 scale)
blockedResponse{ status?: number; message?: string }{ status: 403, message: 'Access denied: AI agent detected' }Custom block response

Express

OptionTypeDefaultDescription
storageStorageConfigStorage backend (memory, redis, or custom)
sessionTracking{ enabled?: boolean; ttl?: number }{ enabled: true }Session tracking configuration
skipPathsstring[]Path prefixes to skip detection
onAgentDetected'block' | 'log' | 'allow'Action when agent detected
onDetection(result, req) => void | PromiseCustom detection callback
confidenceThresholdnumber70Confidence threshold (0–100 scale)
blockedResponse{ status?: number; message?: string }{ status: 403, message: 'Access denied: AI agent detected' }Custom block response

Enhanced vs Basic Middleware

FeatureBasic (withAgentShield)Enhanced (createEnhancedAgentShieldMiddleware)
StorageNo built-in storageMemory, Redis, or custom adapter
Session trackingCookie-basedStorage-backed with event persistence
Detection callbackEvent emitters (Next.js)Simple onDetection callback
Request metadatareq.agentShield object (Express)
Response headersBasicFull detection metadata
Use caseSimple detect/blockProduction apps needing session state

Next Steps