Skip to documentation

Jump to a guide

Crawler ProtectionOverview · See and simulate crawler traffic, then enforce it at your edge and protect website and database capacity.Agent AccessOverview · Decide which AI agents can use your API, before they cost you money.Traffic insightsCrawler Protection · Connect request logs and see which bots reach your website, without changing any traffic.Edge rulesCrawler Protection · Test edge rules on your recent traffic, then enforce them at Cloudflare or AWS WAF.Self-hosted quickstartCrawler Protection · Run the gateway or SDK in your own infrastructure and roll it out safely.Gateway & SDK integrationCrawler Protection · Describe your routes, measure a baseline and wrap expensive work.Runtime policy & capacityCrawler Protection · Choose which crawlers the self-hosted runtime allows, set shared budgets and keep room for customers.Self-hosted controlsCrawler Protection · Change crawler access, budgets, decision logs and alerts for a running runtime.Runtime analyticsCrawler Protection · Report runtime telemetry and read what the self-hosted runtime decided.Troubleshooting & recoveryCrawler Protection · Handle limits, outages, held capacity and recovery.Bot verificationCrawler Protection · How crawler claims are checked against provider evidence and signatures.Plans & usageCrawler Protection · What each plan includes, monthly allowances and additional requests.ConceptsAgent Access · Decisions, the sandbox, supported chains and plan limits.Trust signalsAgent Access · The checks behind each decision, and how to choose them for each route.MiddlewareAgent Access · Gate routes in Express, Fastify, Next.js and other frameworks.SDK referenceAgent Access · Every SDK method, response type, telemetry option and error.InstallationAgent Access · Agent identity, access policies, and SDK integration.Identity and trustAgent Access · Agent identity, access policies, and SDK integration.API referenceAgent Access · Agent identity, access policies, and SDK integration.Errors and retriesAgent Access · Agent identity, access policies, and SDK integration.
Docs/Agent Access/Middleware
Browse documentation

Agent Access

Middleware

Gate routes in Express, Fastify, Next.js and other frameworks.

Set up your framework

Before you upgrade. These examples describe the hardened source contract. Import verifyAgentRequest from your application-owned signature verifier; it is not an SDK export. It must bind identity, method, full URL and body and atomically reject replayed nonces. Missing or invalid verification returns AGENT_OWNERSHIP_REQUIRED (401). Confirm your installed package supports this contract before upgrading. Read the request-proof upgrade guide.

Drop-in middleware for every major Node.js framework. All middleware variants auto-detect on-chain (x-agent-id) and key-based (x-agent-address) agents automatically.

Express / Connect

import { ValironSDK, createValironGate } from '@valiron/sdk';

const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });

// Basic — checks x-agent-id first, then x-agent-address, minScore 65
// Includes a 30s client-side cache for payment retries and cold starts
// Safe with Express 4 (async errors handled via Promise.catch(next))
app.use('/api/paid', createValironGate({ verifyRequest: verifyAgentRequest, sdk: valiron }));

// Custom threshold + longer cache
app.use('/api/premium', createValironGate({
  verifyRequest: verifyAgentRequest,
  sdk: valiron,
  minScore: 85,
  cacheTtlMs: 60_000, // 60s
}));

// Custom agent ID extraction + hooks
app.use('/api/custom', createValironGate({
  verifyRequest: verifyAgentRequest,
  sdk: valiron,
  extractAgentId: (req) => req.query.agent_id as string,
  onAllow: (req, result) => {
    console.log(`Allowed agent ${result.agentId} (score: ${result.score})`);
  },
  onDeny: (req, res, result) => {
    res.status(403).json({
      error: 'Insufficient trust score',
      requiredTier: 'A',
      currentTier: result.tier,
    });
  },
}));

Fastify

import Fastify from 'fastify';
import { ValironSDK, valironFastifyPlugin } from '@valiron/sdk';

const app = Fastify();
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });

// Gate all routes
app.register(valironFastifyPlugin, { verifyRequest: verifyAgentRequest, sdk: valiron });

// Or gate a specific prefix
app.register(valironFastifyPlugin, {
  verifyRequest: verifyAgentRequest,
  sdk: valiron,
  prefix: '/api',
  minScore: 85,
});

app.get('/api/data', async (req) => {
  // req.valiron is populated with GateResult
  return { data: 'protected', tier: req.valiron.tier };
});

Next.js

Use createValironNextMiddleware() in your project's middleware.ts to gate API routes.

// middleware.ts (Next.js project root)
import { ValironSDK, createValironNextMiddleware } from '@valiron/sdk';

const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });

const valironMiddleware = createValironNextMiddleware({
  verifyRequest: verifyAgentRequest,
  sdk: valiron,
  paths: ['/api/paid', '/api/premium'],  // only gate these paths
  minScore: 65,
});

export async function middleware(request: Request) {
  return valironMiddleware(request);
}

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

Returns undefined (pass through) when the agent is allowed, or a JSON Response (401/403/503) when blocked. Paths not in the paths array are passed through without checking.

Generic (Hono, Koa, Bun…)

Use valironGateCheck() for any framework. Returns a structured result you can map to any HTTP response type.

import { ValironSDK, valironGateCheck } from '@valiron/sdk';

const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });

// Hono
app.use('/api/*', async (c, next) => {
  const gate = await valironGateCheck(valiron, {
    verifyRequest: (identifier) => verifyAgentRequest(c.req.raw, identifier),
    agentId: c.req.header('x-agent-id') ?? null,
    agentAddress: c.req.header('x-agent-address') ?? null,
    minScore: 65,
  });
  if (!gate.allow) return c.json(gate.body, gate.status);
  c.set('valiron', gate.result);
  await next();
});

// Koa
app.use(async (ctx, next) => {
  const gate = await valironGateCheck(valiron, {
    verifyRequest: (identifier) => verifyAgentRequest(ctx.req, identifier),
    agentId: ctx.get('x-agent-id') || null,
    agentAddress: ctx.get('x-agent-address') || null,
  });
  if (!gate.allow) {
    ctx.status = gate.status;
    ctx.body = gate.body;
    return;
  }
  ctx.state.valiron = gate.result;
  await next();
});

Middleware Error Responses

All middleware variants use identical, actionable error responses. Use code for program logic; message, action, and docsUrl explain recovery.

StatusCodeWhenNext step
401MISSING_AGENT_IDENTITYNo supported identity headerSend x-agent-id or x-agent-address
401AGENT_OWNERSHIP_REQUIREDMissing verifier, invalid proof or replayConfigure verification and sign the actual request with a fresh nonce
403TRUST_GATE_DENIEDAgent did not meet policyInspect score, tier, route, and reasons
403AGENT_EVALUATION_PENDINGNew agent evaluation is runningKeep the same identity and retry after retryAfterMs
503TRUST_GATE_UNAVAILABLEGate could not evaluateFail closed, retry shortly, and inspect the logged cause
Fail-closed: If the Valiron API is unreachable, all middleware returns 503 and denies the request. Valiron never fails open — an unknown agent is never allowed through.