Checkpoint Docs
Server IntegrationsExpress

Enhanced Express Middleware

Production-grade Express middleware with session tracking and Redis storage

Overview

The createEnhancedAgentShieldMiddleware for Express adds persistent session state, storage adapters (Redis or memory), and detection callbacks on top of the basic middleware. Use it when your production app needs session-level tracking, event persistence, or custom detection handlers.

For a comparison of enhanced vs basic middleware and the full configuration reference covering both Next.js and Express, see Enhanced Middleware.

Setup

import express from 'express';
import { createEnhancedAgentShieldMiddleware } from '@kya-os/agentshield-express';

const app = express();

app.use(
  createEnhancedAgentShieldMiddleware({
    onAgentDetected: 'block',
    confidenceThreshold: 70,
    storage: {
      type: 'redis',
      redis: {
        url: process.env.REDIS_URL!,
        token: process.env.REDIS_TOKEN!,
      },
    },
  })
);

app.listen(3000);

Express uses a 0–100 confidence scale (default threshold: 70), while Next.js uses 0–1 (default: 0.7). Both represent the same 70% threshold.

Storage Adapters

MemoryStorageAdapter

For development and single-instance deployments. Data is lost on restart.

import { MemoryStorageAdapter } from '@kya-os/agentshield-express';

createEnhancedAgentShieldMiddleware({
  storage: { type: 'memory' },
});

RedisStorageAdapter

For production. Persists detection events and sessions across restarts and instances.

import { RedisStorageAdapter } from '@kya-os/agentshield-express';

createEnhancedAgentShieldMiddleware({
  storage: {
    type: 'redis',
    redis: {
      url: process.env.REDIS_URL!,
      token: process.env.REDIS_TOKEN!,
    },
    ttl: 86400, // 24 hours (default)
  },
});

Redis storage uses Upstash Redis with sorted sets for timeline ordering and automatic key expiry.

Detection Callbacks

onAgentDetected

Controls what happens when an agent is detected above the confidence threshold:

ValueBehavior
'block'Return HTTP 403 JSON response
'log'Log the detection, allow request through
'allow'Allow silently (events still stored if configured)

onDetection

Custom callback that fires before the onAgentDetected action. Use for alerts, analytics, or custom logic.

createEnhancedAgentShieldMiddleware({
  onDetection: async (result, req) => {
    await alertingService.notify({
      agent: result.detectedAgent,
      confidence: result.confidence,
      path: req.path,
      ip: req.ip,
    });
  },
  onAgentDetected: 'block',
});

Express vs Next.js callback difference: Express passes (result, req) where req is the standard Express request. Next.js passes (result, context) where context is a DetectionInput object with userAgent, ipAddress, headers, url, method, and timestamp.

Request Metadata

The enhanced middleware attaches detection results directly to the Express request object, making them available in downstream route 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(`Verification: ${req.agentShield.verificationMethod}`);
  }

  res.json({ data: 'your response' });
});

This is Express-specific — the Next.js enhanced middleware does not attach data to the request.

Configuration Reference

OptionTypeDefaultDescription
storageStorageConfigStorage backend (memory, redis, custom)
sessionTracking{ enabled?: boolean; ttl?: number }{ enabled: true }Session tracking config
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

Next Steps