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.13.0

Published

Checkpoint Next.js middleware: AI agent detection and verification through kya-os-engine

Readme

@kya-os/checkpoint-nextjs

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

Features

  • 🚀 Next.js Middleware: Node.js (proxy.ts) and Edge runtime middleware
  • 🧩 Two Deployment Shapes: In-process WebAssembly engine or SaaS gateway
  • 🎯 Flexible Actions: Block, redirect, or challenge detected agents
  • 🛡️ Edge Runtime: Optimized for Vercel Edge Functions
  • 📊 Dashboard Reporting: Detections land in your Checkpoint dashboard

Two deployment shapes

This package ships two middleware factories. Both return a Next.js middleware function with the same request and response contract, and you can use both in one app on different routes.

| Shape | Factory | Where verification runs | Use when | | ---------------- | ------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Local engine | withCheckpoint | In-process, through WebAssembly (kya-os-engine) | You want the lowest latency, verdicts from the engine itself, and no network round trip per request. On Next.js, run it as Edge middleware; see Runtimes and bundlers. | | SaaS gateway | withCheckpointApi | Cloudflare DNS gateway (https://detect.checkpoint-gateway.ai) | You run somewhere WebAssembly can't load, or want one HTTPS hop with centralized policy. It adds about 30 to 50 ms per request and sends request metadata to the gateway. |

// middleware.ts (Edge runtime): local engine
import engineWasmModule from '@kya-os/checkpoint-nextjs/engine-wasm';
import { withCheckpoint } from '@kya-os/checkpoint-nextjs';

export default withCheckpoint({
  // Honor platform headers only inside Vercel's managed runtime.
  clientIpPolicy: { platform: 'vercel' },
  engineWasmModule,
});
// middleware.ts: SaaS gateway
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';

export default withCheckpointApi({
  // Honor platform headers only inside Vercel's managed runtime.
  clientIpPolicy: { platform: 'vercel' },
  apiKey: process.env.CHECKPOINT_API_KEY!,
  onBlock: 'redirect',
  redirectUrl: '/blocked',
});

Runtimes and bundlers

withCheckpoint loads the engine's WebAssembly inside your middleware, so what works depends on the runtime and the bundler. On Next.js, run it as Edge middleware: that works with Turbopack and webpack.

| Middleware file | Import | Turbopack (Next.js 16 default) | webpack (Next.js 15 default) | | ------------------------------------------------------- | --------------------------------------------------- | ------------------------------ | -------------------------------------------------- | | middleware.ts on the Edge runtime (recommended) | @kya-os/checkpoint-nextjs with engineWasmModule | Supported | Supported with unstable_allowDynamic | | proxy.ts, or middleware.ts with runtime: 'nodejs' | @kya-os/checkpoint-nextjs | Supported | Not supported yet |

withCheckpointApi needs no WebAssembly and works with either bundler and either runtime; on webpack's Edge runtime it needs the unstable_allowDynamic config too.

Edge runtime

The Edge runtime does not let code compile WebAssembly from bytes, so the engine has to arrive as a compiled WebAssembly.Module. Import it from @kya-os/checkpoint-nextjs/engine-wasm and pass it as engineWasmModule:

// middleware.ts (Edge runtime)
import engineWasmModule from '@kya-os/checkpoint-nextjs/engine-wasm';
import { withCheckpoint } from '@kya-os/checkpoint-nextjs';

export default withCheckpoint({
  clientIpPolicy: { platform: 'vercel' },
  engineWasmModule,
});

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

/engine-wasm imports the binary from this package's own @kya-os/checkpoint-wasm-runtime dependency, so it always matches the engine code that loads it, and your app needs no direct dependency on that package. On the Edge runtime, @kya-os/checkpoint-nextjs resolves to the Edge build (export conditions edge-light, edge-runtime, workerd and worker, the same as /edge), and without engineWasmModule every request is answered 503 and the missing module is logged.

Cedar policies on the Edge runtime

To evaluate the project's Cedar policy on the Edge runtime, pass the Cedar build as engineWasmModule, in place of the engine-only build. The Cedar build is the engine plus the Cedar policy evaluator, so one module runs detection and the policy:

import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
import { withCheckpoint } from '@kya-os/checkpoint-nextjs';

export default withCheckpoint({
  projectId: process.env.CHECKPOINT_PROJECT_ID,
  engineWasmModule,
});

It is opt-in because it is larger than the engine-only build. Configs that pass it as cedarWasmModule keep working: on its own it serves both roles, and next to the engine-only build it runs as a second instance, so the bundle carries the engine twice (with debug, a hint is logged).

Without a Cedar module the project's policy is still fetched and never skipped. A project with no Cedar policy is unaffected, and a policy in shadow mode keeps the structured decision. A project whose Cedar policy is enforcing has every request answered 503, and the missing module is logged once.

The Edge middleware bundle, gzipped, measured in a Next.js 16 app (Turbopack) whose middleware is withCheckpoint alone:

| Modules | Edge bundle | Vercel Edge limit | | ------------------------------------------------------ | ------------- | -------------------------- | | /engine-wasm as engineWasmModule | about 0.94 MB | fits Hobby (1 MB) | | /cedar-wasm as engineWasmModule | about 1.38 MB | fits Pro (2 MB), not Hobby | | /engine-wasm plus /cedar-wasm as cedarWasmModule | about 2.13 MB | exceeds Pro |

Your own middleware code adds to these. If the bundle does not fit your plan, use withCheckpointApi, which carries no WebAssembly.

webpack

On the Edge runtime, webpack rejects any module that contains code able to evaluate code at runtime, even when that code never runs. Two dependencies trip the check, so allow them in the middleware config:

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
  unstable_allowDynamic: [
    // The Zod schema library bundled into checkpoint-shared probes for `new Function`
    // support inside a try/catch (its allowsEval check).
    '**/@kya-os/checkpoint-shared/dist/**',
    // The engine's wasm-bindgen glue can compile WebAssembly from bytes; passing
    // engineWasmModule means that path never runs.
    '**/@kya-os/checkpoint-wasm-runtime/wasm/**',
  ],
};

withCheckpointApi needs both entries when you import it from @kya-os/checkpoint-nextjs, because on the Edge runtime that is the Edge build, which includes the engine glue. Import it from @kya-os/checkpoint-nextjs/api-middleware and only the checkpoint-shared entry is needed.

Node.js runtime

On the Node.js runtime, @kya-os/checkpoint-nextjs runs the engine's Node build, which loads its .wasm through new URL(..., import.meta.url). Next.js always bundles proxy.ts and middleware.ts, and Turbopack follows that URL and copies the file into the build output, so the same build works bundled and unbundled. @kya-os/checkpoint-nextjs/node is the same build.

In a minimal Next.js 16 app, proxy.ts with withCheckpoint traces 117 files (5.6 MiB), against 111 files for a proxy.ts without it. If the engine cannot load (a missing or unreadable .wasm), every request is answered 503, the cause is logged, and the next request tries again.

On webpack, the Node.js runtime is not supported yet: the build succeeds, but webpack rewrites the .wasm URL into a value Node's file read rejects, so the engine fails to load and every request is answered 503.

Background work

A request can start work that outlives its response: a refresh of the engine's vendor keys, and the detection report when apiKey is set. withCheckpoint registers that work with the waitUntil of the event Next.js passes to middleware, so Vercel does not cancel it once the response is sent. If you wrap withCheckpoint in your own middleware, pass the event through:

const checkpoint = withCheckpoint({});

export default function middleware(request: NextRequest, event: NextFetchEvent) {
  return checkpoint(request, event);
}

Without an event, it falls back to waitUntil from @vercel/functions, which only has an effect on Vercel.

Installation

npm install @kya-os/checkpoint-nextjs

Quick Start

Client-IP trust policy

Set clientIpPolicy to resolve an observed client address only where the runtime can authenticate its source. Next.js 15 removed request.ip; the default direct policy therefore returns no address on current NextRequest objects.

| Deployment | Configuration and result | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | Vercel managed runtime | { platform: 'vercel' } accepts Vercel's overwritten singleton address header when VERCEL=1 | | Legacy Next runtime with a platform-provided request.ip | { platform: 'direct' } uses that framework address | | Self-hosted Next behind a proxy or Cloudflare | No authenticated address is available through NextRequest; trusted-proxy and cloudflare return no address |

The Next adapter adopts the strict resolveObservedClientAddress contract. Selecting a profile does not authenticate a forwarding header. NextRequest exposes no socket peer for the SDK to verify. Supplying isTrustedPeer cannot provide the missing transport address. The SDK withholds the address from both verification and reporting when that boundary is unavailable.

For Vercel, keep clientIpPolicy: { platform: 'vercel' } and use the runtime-provided VERCEL=1 signal. Do not set that variable manually on a self-hosted application to enable header trust. Outside Vercel, the Next adapter resolves this profile like direct.

Migrate self-hosted proxy configurations

Earlier versions accepted Cloudflare or X-Forwarded-For values when a profile was selected. Those configurations now return no address through NextRequest. Configure a transport-aware ingress, such as @kya-os/checkpoint-express, to verify the actual proxy peer and exact forwarding chain. Keep the Next application on direct until it has an authenticated address source. Do not copy a header into request.ip or invent a peer value to restore the old behavior.

Unavailable address evidence does not establish a clean network result. The strict resolver returns status: 'unavailable', a reason, and a null observedClientAddress; the Next adapter returns undefined for its compatibility API. See the client-IP resolution runbook for the supported boundaries and migration checks.

Middleware Setup

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

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

export default withCheckpointApi({
  // Honor platform headers only inside Vercel's managed runtime.
  clientIpPolicy: { platform: 'vercel' },
  apiKey: process.env.CHECKPOINT_API_KEY,
});

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

Enforcement happens in the middleware, before your pages and route handlers run: blocked or challenged requests never reach your code. Tune what gets blocked in your Checkpoint dashboard policy.

Client-Side Detection

This package is server-side middleware; it does not ship client-side React hooks. (The legacy useAgentDetection hook was removed along with the AgentDetector class it wrapped.) For client-side detection, such as conditionally rendering content or tracking agent visits from the browser, use the JavaScript Beacon or the Marketing Pixel alongside the middleware.

Middleware Configuration

The SaaS-gateway shape (withCheckpointApi) accepts:

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

export default withCheckpointApi({
  // API key (or set the CHECKPOINT_API_KEY env var)
  apiKey: process.env.CHECKPOINT_API_KEY,

  // Action when an agent should be blocked: 'block' | 'redirect' | 'challenge'
  // Default: uses the policy from your dashboard
  onBlock: 'block',

  // Target when onBlock is 'redirect'
  redirectUrl: '/blocked',

  // Skip enforcement for paths (glob patterns)
  skipPaths: ['/api/webhooks', '/health'],

  // Custom blocked response
  blockedResponse: {
    status: 403,
    message: 'Access denied',
  },

  // Edge detection: lower latency, catches non-JS clients. Default: true
  useEdge: true,

  // Request timeout in ms. Default: 5000
  timeout: 5000,

  // Fail open (allow) on API errors. Default: false (503 + Retry-After).
  // Requests that present a credential are answered 503 even when true.
  failOpen: false,

  // Observability callback when an agent is detected
  onAgentDetected: async (request, decision) => {
    console.log('Agent detected:', decision.reason);
  },

  // Enable debug logging
  debug: false,
});

The local-engine shape (withCheckpoint) takes a CheckpointConfig instead, every field optional: enforcementMode ('enforce' | 'observe'), apiKey (enables dashboard reporting), projectId (enforces your deployed dashboard policy in-process), and more. tenantHost is deprecated: it is no longer used and will be removed. See the middleware docs for the full option tables for both shapes.

Failure behavior

withCheckpoint answers 503 (Retry-After: 3, Cache-Control: no-store) when the verification pipeline errors; it never passes the request through or returns a 500. If the policy API is unreachable, the last successfully fetched policy (at most 24h old) is served; with none, the request is answered 503 and the default policy is never substituted. The last-good copy lives in process memory and, when a PolicyCacheAdapter is configured, in that adapter (so a cold process or isolate can still serve it). A policy-origin 401/403/404 or a body that is not a policy-API response is treated like an outage: last-good is served for up to 24h.

DID documents and status lists

The engine names every DID document and status list a request needs, after its own trust checks, and withCheckpoint fetches only what it names, before the request is decided. A status list that cannot be fetched or verified is answered 503 with Retry-After: 1 (kyaos/status-pending); a request signer's DID document that cannot be fetched is refused (401 kyaos/did-unresolvable).

On the Node.js runtime each fetch connects only to a public address its own DNS lookup checked, refuses redirects, caps the body and has a deadline. The Edge runtime has no connect hook, so there the same rules apply except the address check, and the platform's egress rules are what keep a fetch off private addresses. adapters.fetch replaces the transport, and the connect-time address check becomes your job: a custom fetch must connect only to a vetted public address (check every address DNS returns, and never re-resolve), refuse redirects, cap the body and enforce a deadline. safeGet, makeSafeLookup and isBlockedIpAddress from @kya-os/checkpoint-wasm-runtime/adapters are the pieces the default uses.

withCheckpoint itself never throws, because a Next.js middleware module that fails to load can let requests through unchecked. An invalid configuration (for example a missing engineWasmModule on the Edge runtime) and an engine that fails to load (for example an unreadable .wasm) are logged with a [checkpoint] prefix and every request is answered 503.

Actions

Block Agents

export default withCheckpointApi({
  apiKey: process.env.CHECKPOINT_API_KEY,
  onBlock: 'block',
  blockedResponse: {
    status: 403,
    message: 'Automated access not allowed',
    headers: {
      'Content-Type': 'application/json',
      'X-Robots-Tag': 'noindex',
    },
  },
});

Redirect Agents

export default withCheckpointApi({
  apiKey: process.env.CHECKPOINT_API_KEY,
  onBlock: 'redirect',
  redirectUrl: '/blocked',
});

By default a redirect verdict is delivered as an HTTP 401 "instruct" envelope with a link header pointing the agent at the redirect URL, which LLM fetchers surface as a clickable link. Set redirectMode: 'http' for a legacy 302 response (only useful when your traffic is real browsers).

Custom Logic

customBlockedResponse runs when the verdict is a block; whatever it returns becomes the response:

import { NextResponse } from 'next/server';

export default withCheckpointApi({
  apiKey: process.env.CHECKPOINT_API_KEY,
  customBlockedResponse: async (request, decision) => {
    if (decision.confidence > 0.9) {
      // High confidence: hard block
      return NextResponse.json({ error: 'Blocked' }, { status: 403 });
    }
    // Lower confidence: send to a verification page instead
    return NextResponse.redirect(new URL('/verify', request.url));
  },
});

API Routes Integration

API routes matched by the matcher are protected by the middleware itself: a request that your policy blocks is answered with the verdict (403, redirect, or challenge) before your route handlers execute. Handlers need no detection code of their own:

// app/api/protected/route.js
import { NextResponse } from 'next/server';

export async function GET() {
  // Only requests your policy allows ever reach this point.
  return NextResponse.json({ data: 'Protected content' });
}

Advanced Usage

Path-Specific Configuration

Use includePaths and skipPaths (glob patterns) to scope enforcement without touching the matcher:

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

export default withCheckpointApi({
  apiKey: process.env.CHECKPOINT_API_KEY,

  // Only enforce on these paths (overrides dashboard policy)
  includePaths: ['/api/*', '/admin/*'],

  // Never enforce on webhooks or health checks
  skipPaths: ['/api/webhooks', '/health'],
});

TypeScript Support

Full TypeScript support with proper types:

import type { NextRequest } from 'next/server';
import {
  withCheckpointApi,
  type CheckpointApiMiddlewareConfig,
  type EnforcementDecision,
} from '@kya-os/checkpoint-nextjs';

const config: CheckpointApiMiddlewareConfig = {
  onBlock: 'block',
  onAgentDetected: async (request: NextRequest, decision: EnforcementDecision) => {
    // Fully typed parameters
    console.log(decision.confidence);
  },
};

export default withCheckpointApi(config);

Examples

E-commerce Protection

// Protect product pages from scrapers
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';

export default withCheckpointApi({
  apiKey: process.env.CHECKPOINT_API_KEY,
  onBlock: 'redirect',
  redirectUrl: '/captcha',
  skipPaths: ['/api/webhooks', '/health'],
});

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

Content Publishing

// Allow search engines through, block other agents
import { NextResponse } from 'next/server';
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';

export default withCheckpointApi({
  apiKey: process.env.CHECKPOINT_API_KEY,
  customBlockedResponse: async (request, decision) => {
    const userAgent = request.headers.get('user-agent') || '';

    // Let known search engines continue even when the policy blocks
    if (/googlebot|bingbot|slurp/i.test(userAgent)) {
      return NextResponse.next();
    }

    return NextResponse.json(
      { error: 'Bot access restricted', reason: decision.reason },
      { status: 403 }
    );
  },
});

License

MIT OR Apache-2.0

Browser integrity

For opt-in classification, signed posture and scoped consent step-up, see the browser integrity rollout runbook.

Reading the browser posture outcome

With browserPosture configured, read the posture outcome for a request in a route handler or page. The accessor verifies the posture token from the request's KYA-Posture headers or cookies with the same verifier and the same posture config the middleware uses, so nothing is forwarded and there is no extra secret:

import { getCheckpointPostureOutcome } from '@kya-os/checkpoint-nextjs';
import { browserPosture, projectId } from '@/checkpoint-config';

export async function POST(request: Request) {
  const outcome = await getCheckpointPostureOutcome(request, { browserPosture, projectId });
  return Response.json({ posture: outcome.status, verdict: outcome.posture?.verdict });
}

The result is { status: 'verified' | 'absent' | 'rejected', reason?, posture? }, with posture (the verified claims, as a frozen copy) only when verified. The accessor always checks: it returns verified, absent or rejected for the request it is given, and does not depend on the middleware having run or on the route matching it. status: 'verified' means the token signature and claims are valid, so check posture.verdict before treating the visitor as human. Given a bare Headers (for example await headers() in a server component), pass those instead of a request. Verification is a single ES256 check, so calling it in a handler as well as in the middleware costs little. A verified token that carries the beacon's agent or bot verdict (posture.detection), or discloses automation, also reclassifies a request the engine called human or incomplete data. The accessor validates browserPosture and projectId with the same check withCheckpoint runs at startup: projectId must be the lowercase project UUID, not the friendly id, and any invalid config throws. Pass the same config object the middleware takes. Treat absent and rejected alike (neither is usable posture evidence), and log reason on the server rather than returning it to the client.