Checkpoint Docs
Server Integrations

Next.js Integration

Edge-optimized AI agent detection for Next.js applications

Overview

The Checkpoint Next.js integration provides AI agent detection and enforcement for Next.js applications. With edge runtime optimization and full App Router support, it delivers protection with minimal performance impact.

Features

  • Edge Runtime Compatible — Runs at the edge for ultra-low latency
  • < 2ms overhead — Minimal impact on response times
  • Detect or Enforce modes — Log-only or active enforcement
  • Route Matching — Fine-grained control over protected paths
  • Policy Engine — Local policy evaluation with configurable rules
  • TypeScript — Full type definitions included

Installation

npm install @kya-os/agentshield-nextjs

Quick Setup

1. Create Middleware

Create middleware.ts in your 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).*)',
  ],
};

2. Add Environment Variables

# .env.local
AGENTSHIELD_API_KEY=your_api_key_here

3. Server Component Usage

// app/page.tsx
import { headers } from 'next/headers';

export default function Page() {
  const headersList = headers();
  const detection = headersList.get('x-checkpoint-detection');

  if (detection) {
    const result = JSON.parse(detection);
    if (result.detectionClass === 'ai_agent') {
      return <div>Access Restricted</div>;
    }
  }

  return <div>Welcome!</div>;
}

1. Create Middleware

Create middleware.ts in your project root:

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

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

export const config = {
  matcher: '/:path*',
};

2. API Route Protection

// pages/api/protected.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const detection = req.headers['x-checkpoint-detection'];

  if (detection) {
    const result = JSON.parse(detection as string);
    if (result.detectionClass === 'ai_agent') {
      return res.status(403).json({ error: 'Access denied' });
    }
  }

  res.status(200).json({ data: 'Protected data' });
}

Enhanced Middleware

For production deployments with enforcement, use the enhanced middleware:

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

export default createEnhancedAgentShieldMiddleware({
  projectId: process.env.CHECKPOINT_PROJECT_ID!,
  apiKey: process.env.CHECKPOINT_API_KEY!,
  mode: 'enforce', // 'detect' or 'enforce'
});

The enhanced middleware adds:

  • Enforcement mode — Block or redirect detected agents
  • Session tracking — Track agents across requests
  • Policy evaluation — Local policy engine for fast decisions
  • Storage adapters — Configurable session storage

See Middleware Enforcement for complete enhanced middleware documentation.

Detect vs Enforce Mode

ModeBehavior
detectClassifies requests and adds detection headers. All traffic passes through.
enforceClassifies requests and applies policy actions (block, redirect, rate-limit).

Start with detect mode to understand your traffic, then switch to enforce when ready.

Configuration

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

export default withAgentShield({
  // Required
  apiKey: string,               // Your AgentShield API key

  // Optional
  onBlock?: 'block',            // Enable enforcement (default: detect-only)
  skipPaths?: string[],         // Paths to skip detection
});

Enhanced Configuration

createEnhancedAgentShieldMiddleware({
  // Required
  projectId: string,
  apiKey: string,

  // Mode
  mode?: 'detect' | 'enforce',   // Default: 'detect'

  // Policy
  policy?: PolicyConfig,          // Custom policy rules

  // Performance
  cacheDetection?: boolean,       // Cache detection results
  cacheDuration?: number,         // Cache TTL in seconds

  // Advanced
  skipPaths?: string[],           // Paths to skip
  debug?: boolean,                // Debug logging
});

Environment Variables

# .env.local
AGENTSHIELD_API_KEY=your_api_key_here

React Hooks

Hooks are not exported from the main package entry. Import them from the /hooks subpath: typescript import {useAgentDetection} from '@kya-os/agentshield-nextjs/hooks';

useAgentDetection

Monitor detection status in client components:

'use client';

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

export function ProtectedContent() {
  const { isAgent, confidence, isLoading } = useAgentDetection();

  if (isLoading) return <div>Checking...</div>;
  if (isAgent) return <div>Content not available</div>;

  return <div>Premium content here</div>;
}

Edge Runtime

Checkpoint middleware is fully optimized for the Next.js Edge Runtime:

// app/api/protected/route.ts
import { NextRequest } from 'next/server';

export const runtime = 'edge';

export async function GET(request: NextRequest) {
  const detection = request.headers.get('x-checkpoint-detection');

  if (detection) {
    const result = JSON.parse(detection);
    if (result.detectionClass === 'ai_agent') {
      return new Response('Forbidden', { status: 403 });
    }
  }

  return new Response('Protected data');
}

Content Security Policy

If your site uses CSP headers and you're also using the Pixel, add the Checkpoint domain:

// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: 'Content-Security-Policy',
            value: [
              "default-src 'self'",
              "script-src 'self' 'unsafe-inline' https://kya.vouched.id",
              "connect-src 'self' https://kya.vouched.id",
            ].join('; '),
          },
        ],
      },
    ];
  },
};

Troubleshooting

Middleware not running

  • Ensure middleware.ts is in the project root (not inside app/ or src/)
  • Check the matcher configuration
  • Verify the file exports a default function

Detection not working

  • Verify Project ID is correct
  • Check network tab for API calls to kya.vouched.id
  • Enable debug: true for detailed logs

Performance issues

  • Enable caching with cacheDetection: true
  • Use skipPaths for non-critical routes (health checks, static assets)
  • The edge runtime provides the best performance

Next Steps