Vercel / Next.js

Add Inception Agents middleware to your Vercel-deployed Next.js project — agent detection, Edge Config Tier-1, and the catalog route-through for headless commerce.

Vercel / Next.js

This guide walks through adding Inception Agents as Edge Middleware to your Vercel-deployed application. The middleware intercepts requests at the edge, detects AI agent traffic, and serves optimized content — all before your application code runs. Human visitors pass through unmodified with zero latency impact.

For headless storefronts, the middleware also enables the catalog route-through: when an AI shopping agent hits your dynamic agent surfaces (/agent/query, /agent/products, and the ACP/UCP endpoints), the request is signed and forwarded to the Inception engine, which resolves your store by hostname and serves your real, normalized catalog — at your own domain. See Catalog Route-Through below.

What to Expect

After deployment, the middleware begins intercepting and analyzing traffic immediately. The first AI agent visits typically appear in your dashboard within 24-48 hours, depending on how actively AI platforms crawl your domain. Content optimization runs automatically — no manual configuration of individual pages is required.

TimeframeWhat Happens
ImmediateMiddleware is active. llms.txt and agent.json are served. Agent detection begins.
1-6 hoursInitial content analysis completes. Structured data gaps are identified.
6-24 hoursContent variants are generated for detected agent intents. JSON-LD enrichment is applied.
24-48 hoursAgent referral attribution activates in the dashboard.
1 week+Learning engine refines content variants per platform. Recommendation rates improve.

Prerequisites

  • Node.js 18 or later
  • Next.js 14 or later (App Router or Pages Router)
  • A project deployed on Vercel
  • An Inception Agents API key (sign up, then find it in Settings > API Keys)

SvelteKit and other frameworks that support Vercel Edge Middleware also work. The middleware API is the same.

Step 1: Install the Package

npm install @inception-agents/vercel

Step 2: Set Your Environment Variables

The fastest path is the one-click installer, which provisions these for you (plus a Vercel Edge Config store) and opens a GitHub PR with the middleware pre-configured. To set them by hand, use the Vercel CLI or dashboard:

vercel env add INCEPTION_API_KEY      # per-tenant API key (also your signing key)
vercel env add INCEPTION_TENANT_ID    # tenant UUID — required for the catalog route-through + MCP proxy
vercel env add EDGE_CONFIG            # provisioned Edge Config connection string (installer sets this)

Select all environments (Production, Preview, Development) or just Production when prompted.

For local development, add them to .env.local:

# .env.local
INCEPTION_API_KEY=ia_live_xxxxxxxxxxxxxxxxxxxx
INCEPTION_TENANT_ID=your_tenant_uuid_here
EDGE_CONFIG=https://edge-config.vercel.com/...

Never commit .env.local to version control. Add it to .gitignore.

Step 3: Create the Middleware

If You Do Not Have an Existing middleware.ts

Create middleware.ts in your project root (next to package.json):

// middleware.ts
import { withInception } from '@inception-agents/vercel';

export const middleware = withInception({
  apiKey: process.env.INCEPTION_API_KEY!,
  tenantId: process.env.INCEPTION_TENANT_ID!,
  enableRouteThrough: true, // serve your catalog at /agent/* + ACP/UCP (the installer sets this)
});

export const config = {
  matcher: [
    /*
     * Match all paths except:
     * - _next/static (static files)
     * - _next/image (image optimization)
     * - favicon.ico
     * - public folder assets
     */
    '/((?!_next/static|_next/image|favicon\\.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)$).*)',
  ],
};

If You Already Have a middleware.ts

Compose Inception Agents with your existing middleware using createInceptionMiddleware. It returns null for human traffic, letting your existing logic run unchanged:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createInceptionMiddleware } from '@inception-agents/vercel';

const inception = createInceptionMiddleware({
  apiKey: process.env.INCEPTION_API_KEY!,
});

function myMiddleware(request: NextRequest) {
  // Your existing middleware logic
  const response = NextResponse.next();
  response.headers.set('x-custom-header', 'my-value');
  return response;
}

export async function middleware(request: NextRequest) {
  // Inception runs first. If it detects an AI agent, it returns the
  // optimized response and we short-circuit. Otherwise, fall through.
  const inceptionResponse = await inception(request);
  if (inceptionResponse) return inceptionResponse;

  return myMiddleware(request);
}

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon\\.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)$).*)',
  ],
};

createInceptionMiddleware runs agent detection first. If the visitor is an AI agent, it serves optimized content and short-circuits. If the visitor is human, it returns null and your myMiddleware function runs normally.

Catalog Route-Through

For headless storefronts, the middleware can serve your real catalog — not just discovery files — from your dynamic agent surfaces. When enableRouteThrough is set (the one-click installer enables it by default; it requires tenantId), requests to /agent/query, /agent/products, /agent/*, and the ACP/UCP endpoints (/.well-known/acp/*, /.well-known/ucp/*) are:

  1. Signed — HMAC-SHA256 over the path, query, and body with your per-tenant key.
  2. Forwarded to the Inception engine, which verifies the signature and binds the request to your tenant by host (no cross-tenant access).
  3. Resolved to your normalized catalog and served back with a short shared-CDN cache.

On any engine error or timeout, the request degrades to your origin — it never blocks. Your catalog is normalized from whichever backend connector you run (Shopify, WooCommerce, BigCommerce, Adobe Commerce, or Salesforce Commerce Cloud); Vercel is the delivery layer.

export const middleware = withInception({
  apiKey: process.env.INCEPTION_API_KEY!,
  tenantId: process.env.INCEPTION_TENANT_ID!,
  enableRouteThrough: true,
});

Tier-1 discovery surfaces (/llms.txt, /.well-known/agent.json) continue to short-circuit from Edge Config, and /mcp and human traffic are unaffected whether or not the route-through is enabled.

Step 4: Deploy

vercel --prod

Or push to your connected Git repository. Vercel will deploy the middleware automatically.

Step 5: Verify

Run these three checks against your production URL:

Check Agent Detection

curl -s -o /dev/null -w "%{http_code}" \
  -H "User-Agent: Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; GPTBot/1.0" \
  https://your-site.com/

Expected: 200. The response will include enriched content and the header X-Inception-Agent: detected.

Check Human Passthrough

curl -s -o /dev/null -w "%{http_code}" \
  -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120.0.0.0 Safari/537.36" \
  https://your-site.com/

Expected: 200. The response is your normal page, unmodified. No X-Inception-Agent header present.

Check llms.txt

curl -s https://your-site.com/llms.txt

Expected: a markdown document describing your site, its content structure, and key topics.

Check the Catalog Route-Through

# Your real catalog, not a brochure -- requires enableRouteThrough + tenantId
curl -s -H "User-Agent: GPTBot/1.0" https://your-site.com/.well-known/acp/products | head -40
curl -s -H "User-Agent: GPTBot/1.0" "https://your-site.com/agent/query?q=trail+running+shoes" | head -40

Expected: your normalized catalog as JSON — products with variants, GTINs, price, and availability. If the route-through is disabled or the engine is unreachable, the request degrades to your origin instead.

Configuration Options

Pass these options to withInception (or createInceptionMiddleware):

withInception({
  apiKey: process.env.INCEPTION_API_KEY!,
  tenantId: process.env.INCEPTION_TENANT_ID!,
  enableRouteThrough: true,
  excludePaths: ['/api/internal/', '/admin/'],
  detectionThreshold: 0.7,
  cacheMaxAge: 3600,
  enableLlmsTxt: true,
  enableJsonLd: true,
  enableAgentCard: true,
});
OptionTypeDefaultDescription
apiKeystringrequiredYour Inception Agents API key (also the per-tenant signing key)
tenantIdstring(recommended)Tenant UUID. Required for the catalog route-through, MCP auto-proxy, and trace beacon.
enableRouteThroughbooleanfalseRoute the dynamic agent surfaces (/agent/query, /agent/products, /agent/*, ACP/UCP) through the engine to serve your normalized catalog. Requires tenantId. The one-click installer enables it.
routeThroughOriginUrlstring(hosted engine)Override the route-through engine origin URL.
routeThroughTimeoutMsnumber2500Timeout for the route-through fetch before degrading to origin passthrough.
enableMcpProxybooleantrueAuto-proxy /mcp requests to the hosted MCP backend. Requires tenantId.
excludePathsstring[]['/api/', '/_next/']URL path prefixes to skip detection (trace cookies are still written).
detectionThresholdnumber0.7Minimum confidence score (0-1) to classify a visitor as an AI agent. Below this threshold, requests pass through as human.
cacheMaxAgenumber300Cache TTL in seconds for Tier-1 / optimized content served to agents.
enableLlmsTxtbooleantrueServe auto-generated /llms.txt.
enableJsonLdbooleantrueInject enriched JSON-LD structured data into agent responses.
enableAgentCardbooleantrueServe /.well-known/agent.json agent capability card.

What Happens After Deployment

Once the middleware is live, the platform operates automatically:

  1. Dashboard populates. Agent visits, detection events, and platform breakdowns appear in real-time under Analytics.
  2. Content analysis runs. Your pages are crawled and analyzed for agent readability, structured data coverage, and content gaps.
  3. Learning engine activates. After sufficient agent interactions (typically 1-2 weeks), the system begins adapting content variants per platform and intent.
  4. Optimization tab unlocks. The dashboard surfaces actionable recommendations — structured data improvements, content gaps, and A/B test opportunities.

Troubleshooting

Middleware Not Running

  • Confirm middleware.ts is in the project root (same directory as package.json), not inside src/ or app/.
  • Check that the matcher pattern in export const config is not accidentally excluding your routes.
  • Verify the middleware is deployed by checking Vercel’s Functions tab — you should see a middleware entry.
  • Run vercel logs --follow to check for errors at the edge.

No Agent Traffic in Dashboard

  • Agent traffic depends on AI platforms crawling your site. This typically begins within 24-48 hours.
  • Verify detection is working with the curl commands in the Verify section.
  • Check that your INCEPTION_API_KEY environment variable is set correctly in Vercel: Settings > Environment Variables.
  • Enable debug: true in the middleware config and check Vercel function logs for detection decisions.

Latency Concerns

  • The middleware adds less than 5ms to request processing for human visitors. Agent detection uses pattern matching and header analysis — no external API calls are made for Tier 0/1 detection.
  • If you observe higher latency, confirm that excludePaths is set for high-traffic API routes that do not need agent detection (e.g., /api/internal/).
  • The cacheMaxAge setting controls how long optimized agent content is cached at the edge. Higher values reduce origin calls.

ISR / Incremental Static Regeneration

  • The middleware runs before ISR cache lookup. Agent-specific content is served from the Inception Agents edge cache, not from your ISR cache.
  • Human visitors continue to use ISR normally. No configuration changes are needed for ISR compatibility.

App Router vs Pages Router

  • The middleware file works identically for both App Router and Pages Router projects. Place middleware.ts in the project root regardless of which router you use.

Uninstall

Step 1: Remove the Middleware

Delete middleware.ts if Inception Agents was the only middleware. If you composed Inception with your own middleware, remove the createInceptionMiddleware import and the inceptionResponse short-circuit block, leaving only your original middleware function.

Step 2: Remove the Package

npm uninstall @inception-agents/vercel

Step 3: Remove the Environment Variables

vercel env rm INCEPTION_API_KEY
vercel env rm INCEPTION_TENANT_ID
vercel env rm EDGE_CONFIG

Or remove them from the Vercel dashboard under Settings > Environment Variables.

Your site reverts to its default behavior on the next deployment. No residual code runs at the edge.