Express / Node.js
This guide adds Inception Agents as middleware to your Express application. The middleware intercepts incoming requests, detects AI agent traffic, and serves optimized content. Human visitors pass through to your normal route handlers with zero overhead.
What to Expect
After deployment, the middleware detects agent traffic on every request that passes through it. Content optimization and llms.txt generation run automatically. Dashboard data populates as agent traffic arrives, typically within 24-48 hours.
| Timeframe | What Happens |
|---|---|
| Immediate | Middleware is active. Agent detection starts. llms.txt and agent.json are served. |
| 1-6 hours | Your pages are analyzed for agent readability and structured data coverage. |
| 6-24 hours | Content variants are generated. JSON-LD enrichment begins. |
| 24-48 hours | Agent referral attribution activates in the dashboard. |
| 1 week+ | Learning engine adapts content per platform and intent. |
Prerequisites
- Express 4.18 or later
- Node.js 18 or later
- An Inception Agents API key (sign up, then find it in Settings > API Keys)
Step 1: Install the Package
npm install @inception-agents/express
Step 2: Set Your API Key
Add your API key to your environment variables. Use a .env file with dotenv or your deployment platform’s secret management.
# .env
INCEPTION_API_KEY=ia_live_xxxxxxxxxxxxxxxxxxxx
Never commit
.envto version control. Add it to.gitignore.
Step 3: Add the Middleware
Add the Inception Agents middleware before your route handlers. It must run early in the middleware chain to intercept agent traffic before other middleware processes the request.
import express from 'express';
import { inceptionMiddleware } from '@inception-agents/express';
const app = express();
// Inception Agents middleware — add before route handlers
app.use(
inceptionMiddleware({
apiKey: process.env.INCEPTION_API_KEY!,
})
);
// Your existing routes
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.get('/products/:id', (req, res) => {
// Your product page logic
res.json({ id: req.params.id, name: 'Widget' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
For production deployments, wrap the middleware in error handling to ensure agent detection failures never break your application:
import express from 'express';
import { inceptionMiddleware } from '@inception-agents/express';
const app = express();
// Production-safe middleware with error boundary
try {
app.use(
inceptionMiddleware({
apiKey: process.env.INCEPTION_API_KEY!,
debug: process.env.NODE_ENV !== 'production',
})
);
} catch (error) {
console.error('Failed to initialize Inception Agents middleware:', error);
// Application continues without agent detection
}
// Error handler for middleware runtime errors
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error('Middleware error:', err.message);
next(); // Pass through to normal route handling
});
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000);
Step 4: Deploy
Deploy your Express application as you normally would (e.g., npm start, Docker, PM2, or your hosting platform).
# Standard deployment
NODE_ENV=production node dist/index.js
# Or with a process manager
pm2 start dist/index.js --name my-app
Ensure the INCEPTION_API_KEY environment variable is set in your production environment.
Step 5: Verify
Run these checks against your running server:
Check Agent Detection
curl -s -D - \
-H "User-Agent: Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; GPTBot/1.0" \
http://localhost:3000/ | head -20
Expected: response headers include X-Inception-Agent: detected and X-Inception-Agent-Platform: openai.
Check Human Passthrough
curl -s -D - \
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120.0.0.0 Safari/537.36" \
http://localhost:3000/ | head -20
Expected: your normal response, unmodified. No X-Inception-Agent header.
Check llms.txt
curl -s http://localhost:3000/llms.txt
Expected: a markdown document describing your site.
Check Agent Card
curl -s http://localhost:3000/.well-known/agent.json
Expected: a JSON object declaring your site’s agent capabilities.
Detection-Only Mode
If you want to detect and log agent traffic without modifying responses, use detection-only mode. This is useful for auditing traffic before enabling full optimization.
app.use(
inceptionMiddleware({
apiKey: process.env.INCEPTION_API_KEY!,
mode: 'detect-only',
})
);
In this mode, the middleware detects agents and logs events to the dashboard but calls next() for all requests, passing both human and agent traffic to your route handlers without modification.
Accessing Detection Metadata
The middleware attaches detection data to the request object. Access it in your route handlers for custom logic:
app.get('/products/:id', (req, res) => {
if (req.inceptionAgent) {
console.log('Agent detected:', {
platform: req.inceptionAgent.platform, // 'openai', 'anthropic', 'google', etc.
confidence: req.inceptionAgent.confidence, // 0.0 - 1.0
type: req.inceptionAgent.type, // 'crawler', 'browsing', 'search'
userAgent: req.inceptionAgent.userAgent,
});
}
if (req.inceptionIntent) {
console.log('Inferred intent:', {
category: req.inceptionIntent.category, // 'product_evaluation', 'comparison', 'pricing'
competitors: req.inceptionIntent.competitors, // ['competitor-a', 'competitor-b']
signals: req.inceptionIntent.signals, // raw detection signals
});
}
// Your normal route logic
res.json({ id: req.params.id });
});
TypeScript Types
If you use TypeScript, extend the Express Request type for autocomplete:
import type { InceptionAgent, InceptionIntent } from '@inception-agents/express';
declare global {
namespace Express {
interface Request {
inceptionAgent?: InceptionAgent;
inceptionIntent?: InceptionIntent;
}
}
}
Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
apiKey | string | required | Your Inception Agents API key |
mode | 'full' | 'detect-only' | 'full' | full serves optimized content; detect-only logs without modifying responses |
debug | boolean | false | Log detection decisions to stdout |
excludePaths | string[] | [] | URL path prefixes to skip entirely |
detectionThreshold | number | 0.7 | Minimum confidence score to classify a visitor as an AI agent |
cacheMaxAge | number | 3600 | Cache TTL in seconds for optimized content |
enableLlmsTxt | boolean | true | Serve auto-generated /llms.txt |
enableJsonLd | boolean | true | Inject enriched JSON-LD into agent responses |
enableAgentCard | boolean | true | Serve /.well-known/agent.json |
trustProxy | boolean | false | Trust X-Forwarded-For headers for client IP detection (enable if behind a reverse proxy) |
Troubleshooting
Middleware Not Running
- Confirm
app.use(inceptionMiddleware(...))is called before your route handlers. Express middleware executes in the order it is registered. - Verify the middleware is not wrapped in a conditional that evaluates to
false(e.g., checking an undefined environment variable). - Enable
debug: trueand check stdout for log output.
No Agent Traffic in Dashboard
- Agent traffic depends on AI platforms crawling your site. This typically begins within 24-48 hours.
- Verify detection with the
curlcommands in Step 5. - Confirm
INCEPTION_API_KEYis set and valid:echo $INCEPTION_API_KEY.
req.inceptionAgent is Undefined
- This property is only set when an AI agent is detected. For human visitors, it is
undefinedby design. - Check that the middleware is registered before the route handler that reads this property.
- If using detection-only mode,
req.inceptionAgentis still populated.
Latency Concerns
- Agent detection adds less than 5ms for Tier 0/1 detection (pattern matching, no external calls).
- If running behind a reverse proxy (nginx, HAProxy, ALB), set
trustProxy: trueso the middleware reads the correct client IP fromX-Forwarded-For. - Add API routes and health check paths to
excludePathsto skip detection entirely.
Express 5 Compatibility
- The middleware is compatible with Express 5. No changes to the API are required.
Cluster Mode (PM2 / Node Cluster)
- Each worker process runs its own instance of the middleware. No shared state is required between workers.
- The middleware reports events to the Inception Agents backend asynchronously. Duplicate detection across workers does not occur because each request is handled by a single worker.
Uninstall
Step 1: Remove the Middleware
Delete the app.use(inceptionMiddleware(...)) call from your application code. Also remove any TypeScript type extensions and references to req.inceptionAgent or req.inceptionIntent.
Step 2: Remove the Package
npm uninstall @inception-agents/express
Step 3: Remove the Environment Variable
Remove INCEPTION_API_KEY from your .env file and from your deployment platform’s environment variable configuration.
Your application reverts to its default behavior on the next deployment. No residual middleware runs.
Inception Agents