npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kya-os/checkpoint-nextjs

v1.2.0

Published

Checkpoint Next.js middleware for AI agent detection (formerly @kya-os/agentshield-nextjs)

Downloads

619

Readme

@kya-os/checkpoint-nextjs

Next.js middleware and React hooks for Checkpoint AI agent detection and enforcement.

Features

  • 🚀 Next.js Middleware: Edge-compatible middleware for all routes
  • ⚛️ React Hooks: Client-side detection and monitoring
  • 🎯 Flexible Actions: Block, redirect, rewrite, or log detected agents
  • 🛡️ Edge Runtime: Optimized for Vercel Edge Functions
  • 📊 Built-in Analytics: Track detection patterns and statistics

Two deployment shapes

This package ships two complementary middleware factories. Pick the one that fits your runtime; both are first-class and supported.

| Shape | Factory | Where verification runs | Use when | | ---------------- | ------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Local engine | withCheckpoint | In-process, via WASM (kya-os-engine) | You want the lowest possible latency, deterministic verdicts, no network round-trip per request, and your runtime can load the WASM artifact (Vercel Node, Vercel Edge with the bundled artifact, Cloudflare Workers with nodejs_compat). This is the canonical Phase D output. | | SaaS gateway | withCheckpointApi | Cloudflare DNS gateway (https://detect.checkpoint-gateway.ai) | You want centralized policy + dashboard rules without a redeploy, you're on a runtime where the WASM artifact won't load (bare-Edge, browser embedding), or you want a single HTTPS hop with cached verdicts. Trades ~30–50ms of edge latency for zero local engine state. |

Both factories return a Next.js middleware function — the request/response contract is identical. You can run both side-by-side in the same app on different routes if your policy demands it.

// middleware.ts — local engine
import { withCheckpoint } from '@kya-os/checkpoint-nextjs';
export default withCheckpoint({ tenantHost: 'demo.example' });

// middleware.ts — SaaS gateway
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';
export default withCheckpointApi({
  apiKey: process.env.CHECKPOINT_API_KEY!,
  onBlock: 'redirect',
  redirectUrl: '/blocked',
});

Pre-Phase-D the SaaS-gateway factory shipped as withAgentShield; the name is preserved as a @deprecated alias for one release. Same for AgentShieldClient / AgentShieldClientConfigCheckpointApiClient / CheckpointApiClientConfig. New code should import the Checkpoint* names.

Installation

npm install @kya-os/checkpoint-nextjs

Quick Start

Middleware Setup

Create middleware.js (or middleware.ts) in your project root:

import { agentShield } from '@kya-os/checkpoint-nextjs';

export default agentShield({
  onAgentDetected: 'block',
  confidenceThreshold: 0.8,

  // NEW: Session tracking (v0.1.27+)
  sessionTracking: {
    enabled: true, // Track continued sessions from AI agents
  },
});

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

React Hooks

⚠️ useAgentDetection is deprecated as of AgentDetector-Deletion-1 and slated for removal in the next minor. It wraps the legacy TS AgentDetector class; Stage 1 detection now lives in the Rust kya-os-engine (PDM-1 #2560). Migrate to server-side detection via withCheckpoint from @kya-os/checkpoint-nextjs, or consume KNOWN_AGENT_PATTERNS directly from @kya-os/checkpoint-shared if you genuinely need client-side pattern matching. useDetectionMonitor stays — it doesn't depend on AgentDetector.

'use client';

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

export default function SecurityMonitor() {
  const { detect, isDetecting, lastResult } = useAgentDetection({
    confidenceThreshold: 0.7,
  });

  const handleCheck = async () => {
    const result = await detect();
    if (result.isAgent) {
      alert('Agent detected!');
    }
  };

  return (
    <div>
      <button onClick={handleCheck} disabled={isDetecting}>
        {isDetecting ? 'Checking...' : 'Check for Agents'}
      </button>

      {lastResult && (
        <div>
          <p>Is Agent: {lastResult.isAgent ? 'Yes' : 'No'}</p>
          <p>Confidence: {(lastResult.confidence * 100).toFixed(1)}%</p>
        </div>
      )}
    </div>
  );
}

Middleware Configuration

import { agentShield } from '@kya-os/checkpoint-nextjs';

export default agentShield({
  // Core detection options
  confidenceThreshold: 0.7,
  enablePatternMatching: true,
  enableBehaviorAnalysis: true,

  // Action when agent is detected
  onAgentDetected: 'block', // 'block' | 'redirect' | 'rewrite' | 'allow' | 'log'

  // Skip detection for paths
  skipPaths: ['/api/webhooks', /^\/admin/],

  // Custom responses
  blockedResponse: {
    status: 403,
    message: 'Access denied',
  },
  redirectUrl: '/blocked',
  rewriteUrl: '/blocked',

  // Custom handler
  onDetection: async (request, result) => {
    console.log('Agent detected:', result);
    // Return custom NextResponse or void
  },
});

Actions

Block Agents

export default agentShield({
  onAgentDetected: 'block',
  blockedResponse: {
    status: 403,
    message: 'Automated access not allowed',
    headers: {
      'Content-Type': 'application/json',
      'X-Robots-Tag': 'noindex',
    },
  },
});

Redirect Agents

export default agentShield({
  onAgentDetected: 'redirect',
  redirectUrl: '/blocked',
  confidenceThreshold: 0.8,
});

Rewrite Requests

export default agentShield({
  onAgentDetected: 'rewrite',
  rewriteUrl: '/bot-content',
  confidenceThreshold: 0.6,
});

Custom Logic

export default agentShield({
  onDetection: async (request, result) => {
    if (result.confidence > 0.9) {
      // High confidence - block
      return NextResponse.json({ error: 'Blocked' }, { status: 403 });
    } else if (result.confidence > 0.5) {
      // Medium confidence - redirect to captcha
      return NextResponse.redirect(new URL('/verify', request.url));
    }
    // Low confidence - continue
  },
});

React Hooks

useAgentDetection

⚠️ Deprecated — see banner above. Will be removed in the next minor. Migrate to withCheckpoint (server-side) or direct KNOWN_AGENT_PATTERNS consumption (client-side pattern matching).

Client-side agent detection:

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

function SecurityComponent() {
  const { detect, isDetecting, lastResult, detector } = useAgentDetection({
    confidenceThreshold: 0.7,
  });

  useEffect(() => {
    // Auto-detect on component mount
    detect();
  }, [detect]);

  return (
    <div>
      {lastResult?.isAgent && (
        <div className="alert">Agent detected with {lastResult.confidence} confidence</div>
      )}
    </div>
  );
}

useDetectionMonitor

Monitor and track detection events:

import { useDetectionMonitor } from '@kya-os/checkpoint-nextjs';

function AnalyticsDashboard() {
  const { detectionHistory, getStats, clearHistory } = useDetectionMonitor((context) => {
    // Handle each detection
    console.log('Detection event:', context);
  });

  const stats = getStats();

  return (
    <div>
      <h2>Detection Statistics</h2>
      <p>Total Requests: {stats.total}</p>
      <p>Agents Detected: {stats.detected}</p>
      <p>Detection Rate: {(stats.detectionRate * 100).toFixed(1)}%</p>
      <p>Average Confidence: {(stats.avgConfidence * 100).toFixed(1)}%</p>

      <button onClick={clearHistory}>Clear History</button>
    </div>
  );
}

API Routes Integration

Protect API routes with server-side detection:

// pages/api/protected.js or app/api/protected/route.js
import { AgentDetector } from '@kya-os/checkpoint';

const detector = new AgentDetector();

export async function GET(request) {
  const context = {
    userAgent: request.headers.get('user-agent'),
    ip: request.ip,
    headers: Object.fromEntries(request.headers.entries()),
  };

  const result = await detector.analyze(context);

  if (result.isAgent && result.confidence > 0.7) {
    return NextResponse.json({ error: 'Automated access detected' }, { status: 403 });
  }

  return NextResponse.json({ data: 'Protected content' });
}

Advanced Usage

Path-Specific Configuration

import { NextRequest, NextResponse } from 'next/server';
import { AgentDetector } from '@kya-os/checkpoint';

const detector = new AgentDetector();

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Different thresholds for different paths
  let threshold = 0.7;
  if (pathname.startsWith('/api/')) {
    threshold = 0.5; // More sensitive for API
  } else if (pathname.startsWith('/admin/')) {
    threshold = 0.9; // Less sensitive for admin (humans expected)
  }

  const context = {
    userAgent: request.headers.get('user-agent') ?? undefined,
    ip: request.ip,
    headers: Object.fromEntries(request.headers.entries()),
    url: request.url,
  };

  const result = await detector.analyze(context);

  if (result.isAgent && result.confidence >= threshold) {
    return NextResponse.json(
      { error: 'Access denied' },
      { status: 403 }
    );
  }

  return NextResponse.next();
}

Server Components

Use detection results in Server Components:

// app/dashboard/page.tsx
import { headers } from 'next/headers';
import { AgentDetector } from '@kya-os/checkpoint';

export default async function Dashboard() {
  const headersList = headers();
  const detector = new AgentDetector();

  const result = await detector.analyze({
    userAgent: headersList.get('user-agent') ?? undefined,
    headers: Object.fromEntries(headersList.entries()),
  });

  if (result.isAgent) {
    return <div>Automated access detected</div>;
  }

  return <div>Welcome to the dashboard!</div>;
}

TypeScript Support

Full TypeScript support with proper types:

import { NextRequest } from 'next/server';
import { agentShield, NextJSMiddlewareConfig } from '@kya-os/checkpoint-nextjs';

const config: NextJSMiddlewareConfig = {
  onAgentDetected: 'block',
  confidenceThreshold: 0.8,
  onDetection: async (request: NextRequest, result) => {
    // Fully typed parameters
    console.log(result.confidence);
  },
};

export default agentShield(config);

Examples

E-commerce Protection

// Protect product pages from scrapers
export default agentShield({
  onAgentDetected: 'redirect',
  redirectUrl: '/captcha',
  confidenceThreshold: 0.6,
  skipPaths: ['/api/webhooks', '/health'],
});

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

Content Publishing

// Allow search engines, block other bots
export default agentShield({
  onDetection: async (request, result) => {
    const userAgent = request.headers.get('user-agent') || '';

    // Allow known search engines
    if (/googlebot|bingbot|slurp/i.test(userAgent)) {
      return; // Continue
    }

    // Block other agents
    if (result.isAgent && result.confidence > 0.5) {
      return NextResponse.json({ error: 'Bot access restricted' }, { status: 403 });
    }
  },
});

License

MIT OR Apache-2.0