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, Express, and ASP.NET Core applications.
Installation
npm install @kya-os/agentshield-nextjsnpm install @kya-os/agentshield-expressdotnet add package Checkpoint.AspNetCore
dotnet add package Checkpoint.CoreBasic 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);// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCheckpoint(options =>
{
options.ProjectId = builder.Configuration["Checkpoint:ProjectId"]!;
options.ApiKey = builder.Configuration["Checkpoint:ApiKey"]!;
options.OnAgentDetected = DetectedAction.Block;
});
var app = builder.Build();
app.UseCheckpoint(); // Add early — before UseRouting()
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();See the full .NET integration guide for configuration options, signature verification, and MCP-I instruct mode.
Enhanced Middleware
The Next.js and Express packages offer an enhanced middleware with built-in session tracking, storage adapters, and event handling.
Using .NET? The ASP.NET Core middleware includes session tracking
and signature verification in the base package — just set EnableSessionTracking = true. No
separate enhanced middleware is needed.
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:
| Adapter | Package | Use Case |
|---|---|---|
| Memory | Built-in | Development and testing |
| Redis | @kya-os/agentshield-express | Production (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
| Option | Type | Default | Description |
|---|---|---|---|
projectId | string | Required | Your Checkpoint project ID |
mode | 'strict' | 'balanced' | 'lenient' | 'balanced' | Detection sensitivity — how aggressively traffic is classified as an AI agent |
onAgentDetected | 'block' | 'redirect' | 'rewrite' | 'allow' | 'log' | 'block' | What to do when an AI agent is detected |
storage | StorageConfig | Memory | Session storage backend |
onDetection | function | — | Callback for each detection event |
Detect-Only vs Active Enforcement
With withAgentShield, you control enforcement behavior using the onAgentDetected option. To run in detect-only mode (observe without blocking), set onAgentDetected: 'log':
import { withAgentShield } from '@kya-os/agentshield-nextjs/api-middleware';
// Detect only — logs detections but takes no blocking action
export default withAgentShield({
apiKey: process.env.AGENTSHIELD_API_KEY,
onAgentDetected: 'log',
});
// Active enforcement — detection + blocking (default)
export default withAgentShield({
apiKey: process.env.AGENTSHIELD_API_KEY,
onAgentDetected: 'block',
});With onAgentDetected: 'log', all requests pass through regardless of classification. Detections are still logged to the dashboard.
With onAgentDetected: 'block' (or 'redirect', 'rewrite'), the middleware applies your configured policies and may block or redirect requests based on the detected agent and your rules.
The instruct action (MCP-I cryptographic challenge) is not supported by in-app middleware
and will silently fall back to redirect behavior. MCP-I enforcement requires traffic to flow
through the Checkpoint Gateway so the gateway can construct the 401
challenge response and verify the agent's signature on retry. If you need MCP-I on an endpoint
your middleware is protecting, add the gateway in front of your origin. See MCP-I Enforcement →
Deployment architecture for the full
picture.
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';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
- Policies — Configure enforcement rules
- Detection in Enforce Mode — How middleware detects agents
- Gateway Enforcement — Alternative: DNS-based enforcement