Middleware Enforcement
Code-based enforcement for Next.js, Express, ASP.NET Core, and Java applications
What is Middleware Enforcement?
Vouched KYA Middleware adds AI agent detection and enforcement directly in your application code. It runs before your route handlers, classifying every request and applying the verdict from Vouched KYA's detection engine (plus any composed Cedar policy you deploy).
Middleware is available for Next.js, Express, ASP.NET Core, and Java applications.
Next.js has two shapes. withCheckpoint runs the detection engine in-process (WASM, no
per-request network hop). withCheckpointApi dispatches to the Vouched KYA SaaS gateway over
HTTPS (no local WASM). Express, .NET, and Java run the engine in-process. Pick the shape that fits
your runtime. See Basic Setup below.
Prerequisites
- A Vouched KYA project. Create one in the dashboard if you don't have one yet.
- Your project's API key (and, for the .NET and Java adapters, its Project ID). See Credentials for where to find both in the dashboard.
Installation
npm install @kya-os/checkpoint-nextjsBasic Setup
For current NextRequest objects (Next.js 15+), client-address evidence requires Vercel's managed runtime; self-hosted proxy and Cloudflare profiles return no address. Express behind a proxy requires an explicit proxy profile and a peer allowlist. Its default policy withholds a socket that Express regards as a proxy. See client-IP deployment guidance.
Create or update middleware.ts in your project root. Choose the deployment shape for your runtime:
Next.js 16: middleware.ts → proxy.ts
proxy.ts and export a proxy function (a default export also works); middleware.ts exporting middleware still works but is deprecated. The Vouched KYA setup below is the same either way, except that withCheckpoint on the Edge runtime also takes engineWasmModule. One caveat: proxy.ts runs on the Node.js runtime only, so if you want Vouched KYA on the Edge runtime (lowest latency), keep the file as middleware.ts. On Next.js 15 and earlier, use middleware.ts.Local engine (withCheckpoint): runs the WASM engine in-process. Lowest latency, deterministic verdicts, no per-request network hop.
// middleware.ts
import engineWasmModule from '@kya-os/checkpoint-nextjs/engine-wasm';
import { withCheckpoint } from '@kya-os/checkpoint-nextjs';
export default withCheckpoint({
// Managed Vercel only; current self-hosted Next has no authenticated client-IP source.
clientIpPolicy: { platform: 'vercel' },
engineWasmModule, // the engine's compiled WebAssembly, required on the Edge runtime
apiKey: process.env.CHECKPOINT_API_KEY, // optional: enables dashboard reporting
});
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
};SaaS gateway (withCheckpointApi): dispatches detection + enforcement to the Vouched KYA gateway over HTTPS. No local WASM; centralized dashboard policy applies.
// middleware.ts
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';
export default withCheckpointApi({
// Managed Vercel only; current self-hosted Next has no authenticated client-IP source.
clientIpPolicy: { platform: 'vercel' },
apiKey: process.env.CHECKPOINT_API_KEY,
});
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
};See the full Next.js integration guide for App Router / Pages Router specifics, API-route protection, and troubleshooting.
Next.js runtimes and bundlers
withCheckpoint runs the engine's WebAssembly inside your middleware, so what works depends on the runtime and the bundler.
withCheckpointApi needs no WebAssembly.
On the Edge runtime, pass engineWasmModule from @kya-os/checkpoint-nextjs/engine-wasm, as in the example above.
The Edge runtime cannot compile WebAssembly from bytes, so withCheckpoint needs the compiled module; without it every request is answered 503 and the missing module is logged.
To evaluate the project's Cedar policy on the Edge runtime, pass engineWasmModule from @kya-os/checkpoint-nextjs/cedar-wasm instead: the Cedar build is the engine plus the Cedar evaluator, so one module runs both. It is larger, so it is opt-in. A config that passes it as cedarWasmModule keeps working; next to the engine-only build it runs as a second instance and the bundle carries the engine twice.
Without it the policy is never skipped: a project whose Cedar policy is enforcing has every request answered 503, and a policy in shadow mode keeps the structured decision.
On the Node.js runtime, leave it out.
With webpack on the Edge runtime, allow the two dependencies that contain code able to evaluate code at runtime: Zod's guarded new Function probe, bundled into checkpoint-shared, and the engine glue's byte-compiling path, which engineWasmModule makes unreachable.
withCheckpointApi imported from @kya-os/checkpoint-nextjs/api-middleware needs only the first entry.
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
unstable_allowDynamic: [
'**/@kya-os/checkpoint-shared/dist/**',
'**/@kya-os/checkpoint-wasm-runtime/wasm/**',
],
};Bundle size on Vercel
The Edge middleware bundle is about 0.94 MB gzipped with /engine-wasm, which fits Vercel's Edge
limit on the Hobby plan (1 MB), and about 1.38 MB with /cedar-wasm, which fits the Pro plan (2
MB). Passing both builds is about 2.13 MB and exceeds Pro. Your own middleware code adds to these.
On the Node.js runtime, a proxy.ts with withCheckpoint traces about 5.6 MiB, well inside
Vercel's 250 MB function limit. Where the Edge bundle does not fit your plan, run it on the
Node.js runtime or use withCheckpointApi.
Calling withCheckpoint outside middleware
In a Server Component or a Server Function, Next.js bundles the engine and rewrites the URL it reads its .wasm from, so the engine cannot load: every call is answered 503, and the logged EngineLoadError names this fix.
Load the engine from node_modules instead:
- Install
@kya-os/checkpoint-wasm-runtimeas a direct dependency of your app, at the version@kya-os/checkpoint-nextjsalready uses (npm ls @kya-os/checkpoint-wasm-runtimeshows it). - Add it to
serverExternalPackages:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
serverExternalPackages: ['@kya-os/checkpoint-wasm-runtime'],
};
export default nextConfig;Next.js keeps a package out of the bundle only when your app resolves it to the same copy the SDK imports.
Without the direct dependency, a package manager that does not hoist dependencies of dependencies (pnpm, by default) leaves the setting with no effect under webpack.
serverExternalPackages and next.config.ts need Next.js 15 or later. On Next.js 13 and 14, list the package in experimental.serverComponentsExternalPackages in next.config.js instead.
Under Turbopack, proxy.ts and route handlers load the engine without either step.
Configuration Options
The Next.js local-engine (withCheckpoint) and Express middleware share the same CheckpointConfig shape (Next.js adds a couple of runtime-specific fields). The SaaS-gateway middleware (withCheckpointApi) uses a different config. See SaaS gateway config below.
Next.js withCheckpoint additionally accepts engineWasmModule and cedarWasmModule for the Edge runtime, and composedPolicyEnforcer for injecting a pre-built enforcer: both advanced-injection escapes rather than everyday configuration.
There is no mode: 'strict' | 'balanced' | 'lenient' knob, no onAgentDetected / onBlock
callback, and no top-level storage or allowList config on withCheckpoint. Detection
sensitivity is set by the engine, not by config; enforcement rules come from your
policies / composed Cedar; agent allowances come from the deployed
policy, not a config array.
Detect-only (observe) mode
To run detection without blocking, set enforcementMode: 'observe'. Every request passes through; the engine still classifies each one and stamps X-Checkpoint-Would-Have-Been headers so you can see what enforcement would have done, and detections still report to the dashboard (when apiKey is set).
withCheckpoint({
enforcementMode: 'observe', // classify + report, never block
apiKey: process.env.CHECKPOINT_API_KEY,
});SaaS gateway config (Next.js)
withCheckpointApi is a distinct middleware with its own configuration; it POSTs to the gateway rather than running the engine locally, so its knobs differ from CheckpointConfig:
onBlock and onAgentDetected belong to withCheckpointApi (the SaaS-gateway path) only. The
in-process withCheckpoint engine does not have them: read its verdict via the onResult
callback instead (see below).
Reading the Verdict
Plain withCheckpoint attaches nothing to req. Read the engine's verdict through the onResult(result, req) callback, which fires after every verification with the full VerifyResult:
withCheckpoint({
onResult: (result, req) => {
// result.decision.kind is the verdict: 'Permit' | 'Block' | 'Challenge' | 'Redirect' | 'Instruct'
console.log(`[${req.method} ${req.url}] verdict=${result.decision.kind}`);
},
});Errors thrown inside onResult are swallowed so an observability failure can never break the verdict path.
In an Express route handler
onResult runs before the verdict is applied, so it can keep the verdict on res.locals, Express's per-request store, for your route handlers:
app.use(
withCheckpoint({
onResult: (result, req) => {
if (req.res) req.res.locals.checkpoint = result;
},
})
);
app.get('/data', (req, res) => {
const agent = res.locals.checkpoint?.detectionDetail.detectedAgent?.name;
res.json({ agent: agent ?? null });
});To keep verdicts in your own logs or database, write them from onResult: see Express Observability.
withSessionTracking, ExpressSessionTracker, req.checkpoint and the storage adapters
(createStorageAdapter, MemoryStorageAdapter, RedisStorageAdapter) were removed from
@kya-os/checkpoint-express. Use onResult as shown above.
Response Headers
The engine path (withCheckpoint, Express and Next.js) sets X-Checkpoint-* headers on the response and writes a __checkpoint_verdict cookie that is byte-identical across both runtimes (shared encodeVerdictCookie primitive). In observe mode it adds X-Checkpoint-Would-Have-Been so you can see the verdict enforcement would have applied.
The X-Checkpoint-Engine header carries the engine name. Exact header keys are produced by the engine's renderDecisionAsResponse; the SDK propagates them verbatim.
Earlier docs listed KYA-Detected / KYA-Confidence / KYA-Agent / KYA-Verification /
KYA-AI-Visitor headers for the engine path. Those were stale. The in-process engine emits
X-Checkpoint-*. The KYA-* detection headers belong to the SaaS-gateway path
(withCheckpointApi), which sets KYA-Detected / KYA-Confidence / KYA-Agent on pass-through
responses.
Response shape (Express)
The middleware adapts the engine's Decision to one of four response shapes. Express and the Next.js local engine (withCheckpoint) share the same transport-agnostic adapter (renderDecisionAsResponse → RenderedResponse), so the shape is identical across both runtimes except for the HTML-block transport, where Next.js's Edge/Node runtime offers a rewrite primitive Express doesn't:
Nothing is attached to req / NextRequest on this path in either runtime: read the verdict from onResult (as shown above), or from the response's verdict cookie / X-Checkpoint-* headers.
withCheckpointApi (Next.js SaaS gateway) does not use this adapter. It never runs
renderDecisionAsResponse; its response shapes come from the gateway's
EnforcementDecision.action (block / redirect / instruct / challenge / log / allow),
not the engine's Decision.kind. See below.
Response shape (Next.js SaaS gateway)
withCheckpointApi attaches nothing to req either. Read the verdict from the response, from the
onAgentDetected(request, decision) callback (fires only when decision.isAgent), or from the
decision object passed into customBlockedResponse:
.NET Configuration
Configure the ASP.NET Core adapter through CheckpointOptions in AddCheckpoint(options => …). Selected options (see the .NET integration guide for the full list):
OnAgentDetected = DetectedAction.Block and EnableSessionTracking are real members of CheckpointOptions: verified against Checkpoint.Core. The .NET API deliberately keeps OnAgentDetected (an enum action) where the TS engine SDK uses composed policy + onResult; the two SDKs are configured differently by design.
Advanced Usage (Next.js)
API route protection (SaaS gateway)
withCheckpointApi(config) takes a config object and returns Next.js middleware. It is not a route-handler wrapper. To protect only your API routes, scope the middleware with the matcher config:
// middleware.ts
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';
export default withCheckpointApi({
// Managed Vercel only; current self-hosted Next has no authenticated client-IP source.
clientIpPolicy: { platform: 'vercel' },
apiKey: process.env.CHECKPOINT_API_KEY,
});
export const config = {
matcher: ['/api/:path*'],
};Alternatively, keep a site-wide matcher and set includePaths: ['/api/*'] in the middleware config so only API paths are enforced.
Client-side detection
The middleware packages are server-side only. They do not ship client-side detection hooks. (The legacy useAgentDetection hook was removed along with the AgentDetector class it wrapped.) For client-side detection (conditionally rendering content, tracking agent visits from the browser), use the JavaScript Beacon or the Marketing Pixel alongside the middleware.
Route Matching (Next.js)
Control which routes the middleware applies to with the Next.js matcher config:
export const config = {
matcher: [
// Match all paths except static assets
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};Next.js's built-in matcher skip list covers _next (its own static/image-optimization paths) and favicon.ico, but not arbitrary image extensions: a /logo.png or /hero.jpg served straight out of public/ isn't under _next/ and isn't covered by that skip list, so without the trailing .*\.(?:svg|png|jpg|jpeg|gif|webp)$ alternation, requests for it flow through the middleware and get classified like any other page. Add the extension exclusion whenever your app serves images outside of next/image.
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