Checkpoint Docs
Enforce

Middleware Enforcement

Code-based enforcement for Next.js and Express applications

What is Middleware Enforcement?

Checkpoint Middleware adds AI agent detection and enforcement directly in your application code. It runs before your route handlers, classifying every request and applying your configured policies.

Middleware is available for Next.js and Express applications.

Installation

npm install @kya-os/agentshield-nextjs
npm install @kya-os/agentshield-express

Basic Setup

Create or update your middleware.ts file in the project root:

import { withAgentShield } from '@kya-os/agentshield-nextjs/api-middleware';

export default withAgentShield({
  apiKey: process.env.AGENTSHIELD_API_KEY,
});

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({
    projectId: process.env.CHECKPOINT_PROJECT_ID!,
  })
);

app.get('/', (req, res) => {
  res.json({ message: 'Protected by Checkpoint' });
});

app.listen(3000);

Enhanced Middleware

Both packages offer an enhanced middleware with built-in session tracking, storage adapters, and event handling.

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

export default createEnhancedAgentShieldMiddleware({
  projectId: process.env.CHECKPOINT_PROJECT_ID!,
  storage: {
    type: 'redis',
    url: process.env.REDIS_URL,
  },
  onDetection: (event) => {
    console.log(`Detected ${event.detectionClass} with confidence ${event.confidence}`);
  },
});
import {
  createEnhancedAgentShieldMiddleware,
  RedisStorageAdapter,
} from '@kya-os/agentshield-express';

app.use(
  createEnhancedAgentShieldMiddleware({
    projectId: process.env.CHECKPOINT_PROJECT_ID!,
    storage: {
      type: 'redis',
      url: process.env.REDIS_URL,
    },
    onDetection: (event) => {
      console.log(`Detected ${event.detectionClass} with confidence ${event.confidence}`);
    },
  })
);

Storage Adapters

The enhanced middleware supports multiple storage backends for session tracking:

AdapterPackageUse Case
MemoryBuilt-inDevelopment and testing
Redis@kya-os/agentshield-expressProduction (recommended)
// Default — no configuration needed
createEnhancedAgentShieldMiddleware({
  projectId: process.env.CHECKPOINT_PROJECT_ID!,
  // Memory storage is used by default
});
createEnhancedAgentShieldMiddleware({
  projectId: process.env.CHECKPOINT_PROJECT_ID!,
  storage: {
    type: 'redis',
    url: process.env.REDIS_URL,
  },
});

Memory storage is not suitable for production — data is lost on restart and not shared across instances. Use Redis for production deployments.

Configuration Options

OptionTypeDefaultDescription
projectIdstringRequiredYour Checkpoint project ID
mode'detect' | 'enforce''enforce'Detection only or detection + enforcement
storageStorageConfigMemorySession storage backend
onDetectionfunctionCallback for each detection event

Detect vs Enforce Mode

With withAgentShield, the default behavior is detect-only (logging detections to the dashboard without blocking). To enforce, set the onBlock option:

import { withAgentShield } from '@kya-os/agentshield-nextjs/api-middleware';

// Detect only — logs detections but never blocks (default)
export default withAgentShield({
  apiKey: process.env.AGENTSHIELD_API_KEY,
});

// Enforce — detection + blocking
export default withAgentShield({
  apiKey: process.env.AGENTSHIELD_API_KEY,
  onBlock: 'block',
});

In detect mode, all requests pass through regardless of classification. Detections are still logged to the dashboard.

In enforce mode, the middleware applies your configured policies and may block, redirect, or challenge requests.

Advanced Usage

Policy Evaluation

Evaluate policies locally for faster response times:

import { evaluatePolicy, createEvaluationContext } from '@kya-os/agentshield-nextjs';

const context = createEvaluationContext(detection);
const result = evaluatePolicy(policy, context);

API Route Protection

Protect individual API routes:

import { withAgentShield } from '@kya-os/agentshield-nextjs';

export const GET = withAgentShield(async (req) => {
  return Response.json({ data: 'protected' });
});

Client-Side Hooks

For React applications, import hooks from a separate entry point:

import { useAgentDetection } from '@kya-os/agentshield-nextjs/hooks';
Hooks are client-only. Use middleware for server-side detection.

Route Matching (Next.js)

Control which routes the middleware applies to using Next.js matcher configuration:

export const config = {
  matcher: [
    // Match all paths except static assets
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
};

To protect only specific routes:

export const config = {
  matcher: ['/api/:path*', '/dashboard/:path*'],
};

Next Steps