Transform your website into a lead-generating machine with THE8.AI's Visitor Identification API. This comprehensive developer guide covers everything from basic integration to advanced implementation patterns, helping you identify 45-60% of anonymous visitors in real-time.
API Overview and Capabilities
THE8.AI's Visitor Identification API provides real-time visitor intelligence with sub-100ms response times, accessing our 600M+ contact database to reveal the companies and individuals behind your website traffic.
Core API Features
Real-Time Identification:
- 89ms average response time
- 99.9% uptime SLA
- Global infrastructure with 15+ edge locations
- Auto-scaling to handle traffic spikes
Comprehensive Data Coverage:
- 600M+ contact records with verified information
- 47M+ company profiles with detailed intelligence
- 847M+ phone numbers with 99.7% accuracy
- 550M+ email addresses with 99.9% deliverability
Advanced Intelligence:
- Behavioral intent scoring based on visitor actions
- Buying stage classification using ML algorithms
- Technographic data including current tech stack
- Firmographic enrichment with company insights
Getting Started
Authentication
All API requests require authentication using your API key:
# Test your API key
curl -X GET "https://api.the8.ai/v1/auth/verify" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"
Response:
{
"status": "success",
"account": {
"id": "acc_1234567890",
"plan": "growth",
"monthly_quota": 50000,
"used_this_month": 12847,
"remaining": 37153
},
"rate_limits": {
"requests_per_minute": 1000,
"burst_limit": 100
}
}
Base URL and Endpoints
Production Environment:
https://api.the8.ai/v1/
Sandbox Environment:
https://sandbox-api.the8.ai/v1/
Core Endpoints:
POST /visitors/identify
- Identify individual visitorsPOST /visitors/bulk
- Batch visitor identificationGET /visitors/{id}
- Retrieve visitor detailsPOST /enrichment/company
- Enrich company dataPOST /enrichment/contact
- Enrich contact information
Visitor Identification Endpoint
Basic Visitor Identification
Endpoint: POST /v1/visitors/identify
// Basic visitor identification
const response = await fetch('https://api.the8.ai/v1/visitors/identify', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
ip_address: '192.168.1.100',
user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...',
referrer: 'https://google.com/search?q=sales+software',
page_url: 'https://yoursite.com/pricing',
timestamp: Date.now()
})
});
const visitorData = await response.json();
Request Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
ip_address |
string | Yes | Visitor's IP address |
user_agent |
string | Yes | Browser user agent string |
referrer |
string | No | Referring URL |
page_url |
string | No | Current page URL |
timestamp |
number | No | Unix timestamp of visit |
session_id |
string | No | Unique session identifier |
custom_data |
object | No | Custom tracking data |
Advanced Request Example
// Advanced visitor identification with custom data
const identifyVisitor = async (visitorInfo) => {
const payload = {
// Required fields
ip_address: visitorInfo.ip,
user_agent: visitorInfo.userAgent,
// Optional context
referrer: visitorInfo.referrer,
page_url: visitorInfo.currentUrl,
timestamp: Date.now(),
session_id: visitorInfo.sessionId,
// Behavioral context
pages_visited: visitorInfo.pageHistory,
time_on_site: visitorInfo.sessionDuration,
scroll_depth: visitorInfo.scrollPercentage,
// Custom tracking data
custom_data: {
campaign_source: visitorInfo.utmSource,
campaign_medium: visitorInfo.utmMedium,
campaign_name: visitorInfo.utmCampaign,
ab_test_variant: visitorInfo.testVariant,
user_tier: visitorInfo.accountTier
}
};
try {
const response = await fetch('https://api.the8.ai/v1/visitors/identify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
'X-Request-ID': generateRequestId()
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Visitor identification failed:', error);
return null;
}
};
API Response Format
Successful Response Structure
{
"status": "success",
"visitor_id": "vis_abc123def456",
"confidence_score": 0.89,
"processing_time_ms": 73,
"data": {
"company": {
"name": "Acme Corporation",
"domain": "acme.com",
"industry": "Software",
"sub_industry": "Enterprise Software",
"employees": "1001-5000",
"employees_range": {
"min": 1001,
"max": 5000
},
"revenue": "$100M-500M",
"revenue_range": {
"min": 100000000,
"max": 500000000
},
"location": {
"headquarters": "San Francisco, CA",
"country": "United States",
"state": "California",
"city": "San Francisco",
"coordinates": {
"lat": 37.7749,
"lng": -122.4194
}
},
"founded": 2015,
"website": "https://acme.com",
"phone": "+1-415-555-0100",
"social_profiles": {
"linkedin": "https://linkedin.com/company/acme-corp",
"twitter": "https://twitter.com/acmecorp",
"facebook": "https://facebook.com/acmecorp"
},
"technologies": [
"Salesforce",
"HubSpot",
"AWS",
"Slack",
"Zoom"
],
"keywords": [
"enterprise software",
"B2B solutions",
"cloud computing"
]
},
"contact": {
"available": true,
"contacts": [
{
"name": "John Smith",
"title": "VP of Sales",
"department": "Sales",
"email": "[email protected]",
"phone": "+1-415-555-0123",
"mobile": "+1-415-555-9876",
"linkedin": "https://linkedin.com/in/johnsmith-acme",
"confidence": 0.87,
"last_updated": "2025-01-24T10:30:00Z"
},
{
"name": "Sarah Johnson",
"title": "Director of Marketing",
"department": "Marketing",
"email": "[email protected]",
"phone": "+1-415-555-0124",
"confidence": 0.82
}
]
},
"visitor_intelligence": {
"intent_score": 0.73,
"buying_stage": "consideration",
"interest_topics": [
"pricing",
"integrations",
"security"
],
"behavioral_signals": {
"high_value_pages": true,
"multiple_sessions": true,
"deep_engagement": true,
"comparison_research": false
},
"predicted_actions": {
"likely_to_convert": 0.68,
"demo_request_probability": 0.45,
"time_to_conversion_days": 12
}
},
"technographics": {
"categories": {
"CRM": ["Salesforce"],
"Marketing Automation": ["HubSpot"],
"Cloud Infrastructure": ["AWS"],
"Communication": ["Slack", "Zoom"],
"Analytics": ["Google Analytics"]
},
"spending_signals": {
"total_tech_spend": "$500K-1M annually",
"recent_purchases": ["Slack", "Zoom"],
"upcoming_renewals": ["Salesforce"],
"budget_cycle": "Q4"
}
}
},
"meta": {
"api_version": "1.0",
"request_id": "req_xyz789abc123",
"cached": false,
"data_sources": ["proprietary", "public", "partner"],
"compliance": {
"gdpr_compliant": true,
"ccpa_compliant": true,
"data_retention_days": 365
}
}
}
Error Response Format
{
"status": "error",
"error": {
"code": "INVALID_IP_ADDRESS",
"message": "The provided IP address is not valid",
"details": "IP address must be a valid IPv4 or IPv6 address",
"request_id": "req_error123"
},
"meta": {
"api_version": "1.0",
"timestamp": "2025-01-24T15:30:00Z"
}
}
Common Error Codes:
Code | HTTP Status | Description |
---|---|---|
INVALID_API_KEY |
401 | API key is missing or invalid |
RATE_LIMIT_EXCEEDED |
429 | Request rate limit exceeded |
INVALID_IP_ADDRESS |
400 | IP address format is invalid |
DATA_NOT_FOUND |
404 | No data found for the visitor |
INSUFFICIENT_QUOTA |
402 | Monthly API quota exceeded |
INTERNAL_ERROR |
500 | Temporary server error |
Bulk Visitor Identification
For processing multiple visitors simultaneously:
// Bulk visitor identification
const bulkIdentify = async (visitors: VisitorData[]) => {
const response = await fetch('https://api.the8.ai/v1/visitors/bulk', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
visitors: visitors.map(v => ({
ip_address: v.ip,
user_agent: v.userAgent,
referrer: v.referrer,
page_url: v.pageUrl,
timestamp: v.timestamp,
external_id: v.id // Your internal ID for mapping
}))
})
});
return await response.json();
};
// Bulk response format
{
"status": "success",
"total_processed": 1000,
"successful": 987,
"failed": 13,
"results": [
{
"external_id": "visitor_001",
"status": "success",
"visitor_id": "vis_abc123",
"data": { /* visitor data */ }
},
{
"external_id": "visitor_002",
"status": "error",
"error": {
"code": "DATA_NOT_FOUND",
"message": "No data available for this IP"
}
}
// ... more results
],
"meta": {
"processing_time_ms": 234,
"request_id": "req_bulk123"
}
}
Real-Time Implementation Patterns
JavaScript Client-Side Integration
// THE8.AI Visitor Identification SDK
class THE8VisitorIdentification {
constructor(apiKey, options = {}) {
this.apiKey = apiKey;
this.baseURL = options.baseURL || 'https://api.the8.ai/v1';
this.debug = options.debug || false;
this.cache = new Map();
this.sessionId = this.generateSessionId();
}
async identifyCurrentVisitor() {
const visitorData = this.collectVisitorData();
const cacheKey = this.generateCacheKey(visitorData);
// Return cached result if available
if (this.cache.has(cacheKey)) {
return this.cache.get(cacheKey);
}
try {
const result = await this.identifyVisitor(visitorData);
// Cache successful results for 5 minutes
if (result.status === 'success') {
this.cache.set(cacheKey, result);
setTimeout(() => this.cache.delete(cacheKey), 5 * 60 * 1000);
}
return result;
} catch (error) {
this.logError('Visitor identification failed', error);
return null;
}
}
collectVisitorData() {
return {
ip_address: this.getClientIP(), // Note: requires server-side proxy
user_agent: navigator.userAgent,
referrer: document.referrer,
page_url: window.location.href,
timestamp: Date.now(),
session_id: this.sessionId,
pages_visited: this.getPageHistory(),
time_on_site: this.getTimeOnSite(),
screen_resolution: `${screen.width}x${screen.height}`,
language: navigator.language,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
};
}
async identifyVisitor(visitorData) {
const response = await fetch(`${this.baseURL}/visitors/identify`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(visitorData)
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return await response.json();
}
// Event tracking for behavioral analysis
trackEvent(eventType, eventData = {}) {
const event = {
type: eventType,
data: eventData,
timestamp: Date.now(),
page_url: window.location.href,
session_id: this.sessionId
};
// Store events for batch sending
this.queueEvent(event);
}
// Helper methods
generateSessionId() {
return 'session_' + Math.random().toString(36).substr(2, 9);
}
generateCacheKey(visitorData) {
return btoa(visitorData.ip_address + visitorData.user_agent).slice(0, 16);
}
getPageHistory() {
return JSON.parse(sessionStorage.getItem('the8_page_history') || '[]');
}
getTimeOnSite() {
const startTime = sessionStorage.getItem('the8_session_start');
return startTime ? Date.now() - parseInt(startTime) : 0;
}
}
// Usage example
const the8 = new THE8VisitorIdentification('your_api_key', { debug: true });
// Identify visitor on page load
document.addEventListener('DOMContentLoaded', async () => {
const visitor = await the8.identifyCurrentVisitor();
if (visitor && visitor.status === 'success') {
// Personalize experience based on visitor data
personalizeContent(visitor.data);
// Track high-value actions
trackHighValueActions(visitor.data);
// Update CRM or marketing automation
syncToCRM(visitor.data);
}
});
Server-Side Integration Examples
Node.js Express Middleware:
// THE8.AI Express middleware
const the8Middleware = (apiKey) => {
return async (req, res, next) => {
try {
const visitorData = {
ip_address: req.ip || req.connection.remoteAddress,
user_agent: req.get('User-Agent'),
referrer: req.get('Referer'),
page_url: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
timestamp: Date.now()
};
const response = await fetch('https://api.the8.ai/v1/visitors/identify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(visitorData)
});
if (response.ok) {
const visitorIntel = await response.json();
req.the8Visitor = visitorIntel;
}
} catch (error) {
console.error('THE8.AI identification error:', error);
}
next();
};
};
// Use middleware
app.use(the8Middleware('your_api_key'));
// Access visitor data in routes
app.get('/pricing', (req, res) => {
const visitor = req.the8Visitor;
if (visitor && visitor.status === 'success') {
// Customize pricing based on company size
const pricingTier = determinePricingTier(visitor.data.company);
res.render('pricing', { visitor: visitor.data, tier: pricingTier });
} else {
res.render('pricing', { visitor: null, tier: 'standard' });
}
});
Python Flask Integration:
import requests
from flask import Flask, request, g
from functools import wraps
app = Flask(__name__)
THE8_API_KEY = 'your_api_key'
THE8_BASE_URL = 'https://api.the8.ai/v1'
def identify_visitor():
"""Decorator to identify visitors on route access"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
visitor_data = {
'ip_address': request.environ.get('REMOTE_ADDR'),
'user_agent': request.headers.get('User-Agent'),
'referrer': request.headers.get('Referer'),
'page_url': request.url,
'timestamp': int(time.time() * 1000)
}
try:
response = requests.post(
f'{THE8_BASE_URL}/visitors/identify',
headers={
'Authorization': f'Bearer {THE8_API_KEY}',
'Content-Type': 'application/json'
},
json=visitor_data,
timeout=2 # 2 second timeout
)
if response.status_code == 200:
g.visitor = response.json()
else:
g.visitor = None
except requests.RequestException as e:
print(f'THE8.AI API error: {e}')
g.visitor = None
return f(*args, **kwargs)
return decorated_function
return decorator
@app.route('/pricing')
@identify_visitor()
def pricing():
visitor = getattr(g, 'visitor', None)
if visitor and visitor.get('status') == 'success':
company_data = visitor['data']['company']
# Customize pricing based on company size
if company_data['employees_range']['max'] > 1000:
pricing_tier = 'enterprise'
elif company_data['employees_range']['max'] > 100:
pricing_tier = 'business'
else:
pricing_tier = 'starter'
return render_template('pricing.html',
visitor=visitor['data'],
tier=pricing_tier)
return render_template('pricing.html', visitor=None, tier='standard')
Advanced Features and Customization
Custom Intent Scoring
// Custom intent scoring based on visitor behavior
const calculateCustomIntentScore = (visitorData, behaviorEvents) => {
let intentScore = visitorData.visitor_intelligence.intent_score;
// Page-based scoring
const pageScores = {
'/pricing': 0.25,
'/demo': 0.35,
'/case-studies': 0.15,
'/integrations': 0.20,
'/security': 0.18,
'/api-docs': 0.22
};
// Apply page visit bonuses
behaviorEvents.page_visits.forEach(page => {
if (pageScores[page.path]) {
intentScore += pageScores[page.path];
}
});
// Time-based multipliers
const timeOnSite = behaviorEvents.time_on_site;
if (timeOnSite > 300) intentScore *= 1.2; // 5+ minutes
if (timeOnSite > 600) intentScore *= 1.4; // 10+ minutes
// Engagement depth
const pageDepth = behaviorEvents.page_visits.length;
if (pageDepth > 5) intentScore *= 1.15;
if (pageDepth > 10) intentScore *= 1.25;
// Company fit multiplier
const companyFit = calculateCompanyFit(visitorData.data.company);
intentScore *= companyFit;
return Math.min(intentScore, 1.0);
};
const calculateCompanyFit = (company) => {
let fitScore = 0.5; // Base score
// Industry fit
const targetIndustries = ['Software', 'Technology', 'SaaS'];
if (targetIndustries.includes(company.industry)) {
fitScore += 0.2;
}
// Company size fit
const employees = company.employees_range.max;
if (employees >= 100 && employees <= 5000) {
fitScore += 0.2;
}
// Revenue fit
const revenue = company.revenue_range.max;
if (revenue >= 10000000) { // $10M+
fitScore += 0.15;
}
// Technology stack alignment
const techStack = company.technologies;
const targetTechs = ['Salesforce', 'HubSpot', 'AWS'];
const techOverlap = techStack.filter(tech => targetTechs.includes(tech));
fitScore += (techOverlap.length / targetTechs.length) * 0.15;
return Math.min(fitScore, 1.0);
};
Webhook Integration
Set up webhooks to receive real-time visitor notifications:
// Webhook endpoint setup
app.post('/webhooks/the8-visitor', express.json(), (req, res) => {
const signature = req.headers['x-the8-signature'];
const payload = JSON.stringify(req.body);
// Verify webhook signature
if (!verifyWebhookSignature(payload, signature)) {
return res.status(401).json({ error: 'Invalid signature' });
}
const event = req.body;
switch (event.type) {
case 'visitor.identified':
handleVisitorIdentified(event.data);
break;
case 'visitor.high_intent':
handleHighIntentVisitor(event.data);
break;
case 'visitor.return':
handleReturnVisitor(event.data);
break;
default:
console.log(`Unknown event type: ${event.type}`);
}
res.json({ received: true });
});
const handleHighIntentVisitor = async (visitorData) => {
// Send immediate alert to sales team
await sendSlackAlert({
channel: '#sales-alerts',
message: `🔥 High-intent visitor from ${visitorData.company.name}!`,
visitor: visitorData
});
// Create CRM record
await createCRMRecord(visitorData);
// Trigger personalized email campaign
await triggerNurtureSequence(visitorData);
};
Rate Limiting and Optimization
// Implement intelligent rate limiting
class THE8APIClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.requestQueue = [];
this.isProcessingQueue = false;
this.rateLimitRemaining = 1000;
this.rateLimitReset = Date.now() + 60000;
}
async identifyVisitor(visitorData) {
return new Promise((resolve, reject) => {
this.requestQueue.push({ visitorData, resolve, reject });
this.processQueue();
});
}
async processQueue() {
if (this.isProcessingQueue || this.requestQueue.length === 0) {
return;
}
this.isProcessingQueue = true;
while (this.requestQueue.length > 0) {
// Check rate limits
if (this.rateLimitRemaining <= 0) {
const waitTime = this.rateLimitReset - Date.now();
if (waitTime > 0) {
await this.delay(waitTime);
}
}
const request = this.requestQueue.shift();
try {
const response = await this.makeAPIRequest(request.visitorData);
// Update rate limit info from response headers
this.updateRateLimits(response.headers);
request.resolve(response.data);
} catch (error) {
request.reject(error);
}
// Small delay between requests
await this.delay(50);
}
this.isProcessingQueue = false;
}
async makeAPIRequest(visitorData) {
const response = await fetch('https://api.the8.ai/v1/visitors/identify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(visitorData)
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return {
data: await response.json(),
headers: response.headers
};
}
updateRateLimits(headers) {
this.rateLimitRemaining = parseInt(headers.get('X-Rate-Limit-Remaining')) || 1000;
this.rateLimitReset = parseInt(headers.get('X-Rate-Limit-Reset')) || Date.now() + 60000;
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
Data Enrichment APIs
Company Enrichment
// Enrich company data with additional intelligence
const enrichCompany = async (domain) => {
const response = await fetch('https://api.the8.ai/v1/enrichment/company', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
domain: domain,
include_contacts: true,
include_technographics: true,
include_firmographics: true,
include_financial_data: true
})
});
return await response.json();
};
// Response includes comprehensive company intelligence
{
"company": {
"basic": { /* standard company data */ },
"contacts": [
{
"name": "John Smith",
"title": "CEO",
"department": "Executive",
"email": "[email protected]",
"phone": "+1-555-0123",
"social_profiles": { /* LinkedIn, Twitter, etc. */ }
}
],
"technographics": {
"current_stack": ["Salesforce", "AWS", "Slack"],
"tech_spend": "$500K-1M annually",
"upcoming_renewals": ["Microsoft Office"],
"recent_adoptions": ["Zoom", "Notion"]
},
"financial": {
"funding_history": [
{
"round": "Series B",
"amount": "$25M",
"date": "2024-06-15",
"investors": ["Sequoia Capital", "a16z"]
}
],
"credit_rating": "A+",
"growth_rate": "45% YoY"
}
}
}
Contact Enrichment
// Enrich individual contact data
const enrichContact = async (email) => {
const response = await fetch('https://api.the8.ai/v1/enrichment/contact', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
include_social_profiles: true,
include_work_history: true,
include_education: true,
include_skills: true
})
});
return await response.json();
};
Testing and Debugging
API Testing Framework
// Comprehensive API testing suite
describe('THE8.AI Visitor Identification API', () => {
const apiClient = new THE8APIClient(process.env.THE8_API_KEY);
test('should identify visitor with valid IP', async () => {
const visitorData = {
ip_address: '8.8.8.8',
user_agent: 'Mozilla/5.0 (test)',
page_url: 'https://test.com'
};
const result = await apiClient.identifyVisitor(visitorData);
expect(result.status).toBe('success');
expect(result.visitor_id).toBeDefined();
expect(result.data.company).toBeDefined();
});
test('should handle rate limiting gracefully', async () => {
const promises = [];
// Send 100 concurrent requests
for (let i = 0; i < 100; i++) {
promises.push(apiClient.identifyVisitor({
ip_address: `192.168.1.${i}`,
user_agent: 'Mozilla/5.0 (test)'
}));
}
const results = await Promise.allSettled(promises);
const successful = results.filter(r => r.status === 'fulfilled');
expect(successful.length).toBeGreaterThan(0);
});
test('should validate required parameters', async () => {
await expect(apiClient.identifyVisitor({}))
.rejects.toThrow('ip_address is required');
});
});
Debug Mode and Logging
// Debug-enabled API client
class THE8DebugClient extends THE8APIClient {
constructor(apiKey, debug = false) {
super(apiKey);
this.debug = debug;
this.requestLog = [];
}
async identifyVisitor(visitorData) {
if (this.debug) {
console.log('THE8.AI Request:', visitorData);
}
const startTime = performance.now();
try {
const result = await super.identifyVisitor(visitorData);
const endTime = performance.now();
const logEntry = {
timestamp: new Date().toISOString(),
request: visitorData,
response: result,
processing_time: endTime - startTime,
success: true
};
this.requestLog.push(logEntry);
if (this.debug) {
console.log('THE8.AI Response:', result);
console.log(`Processing time: ${logEntry.processing_time}ms`);
}
return result;
} catch (error) {
const endTime = performance.now();
const logEntry = {
timestamp: new Date().toISOString(),
request: visitorData,
error: error.message,
processing_time: endTime - startTime,
success: false
};
this.requestLog.push(logEntry);
if (this.debug) {
console.error('THE8.AI Error:', error);
}
throw error;
}
}
getRequestLog() {
return this.requestLog;
}
exportDebugReport() {
return {
total_requests: this.requestLog.length,
successful_requests: this.requestLog.filter(r => r.success).length,
average_response_time: this.requestLog.reduce((sum, r) => sum + r.processing_time, 0) / this.requestLog.length,
requests: this.requestLog
};
}
}
Performance Optimization
Caching Strategies
// Multi-layer caching system
class THE8CachedClient extends THE8APIClient {
constructor(apiKey, cacheOptions = {}) {
super(apiKey);
this.memoryCache = new Map();
this.redisClient = cacheOptions.redis;
this.cacheTimeout = cacheOptions.timeout || 300000; // 5 minutes
}
async identifyVisitor(visitorData) {
const cacheKey = this.generateCacheKey(visitorData);
// Try memory cache first
const memoryResult = this.memoryCache.get(cacheKey);
if (memoryResult && !this.isExpired(memoryResult)) {
return memoryResult.data;
}
// Try Redis cache
if (this.redisClient) {
const redisResult = await this.redisClient.get(cacheKey);
if (redisResult) {
const parsedResult = JSON.parse(redisResult);
// Store in memory cache for faster access
this.memoryCache.set(cacheKey, {
data: parsedResult,
timestamp: Date.now()
});
return parsedResult;
}
}
// Make API request
const result = await super.identifyVisitor(visitorData);
// Cache the result
if (result.status === 'success') {
const cacheEntry = {
data: result,
timestamp: Date.now()
};
this.memoryCache.set(cacheKey, cacheEntry);
if (this.redisClient) {
await this.redisClient.setex(
cacheKey,
Math.floor(this.cacheTimeout / 1000),
JSON.stringify(result)
);
}
}
return result;
}
generateCacheKey(visitorData) {
const keyData = `${visitorData.ip_address}:${visitorData.user_agent}`;
return 'the8:' + require('crypto').createHash('md5').update(keyData).digest('hex');
}
isExpired(cacheEntry) {
return Date.now() - cacheEntry.timestamp > this.cacheTimeout;
}
}
Security Best Practices
API Key Management
// Secure API key management
class SecureAPIClient {
constructor() {
this.apiKey = this.loadAPIKey();
this.encryptionKey = process.env.THE8_ENCRYPTION_KEY;
}
loadAPIKey() {
// Load encrypted API key from secure storage
const encryptedKey = process.env.THE8_API_KEY_ENCRYPTED;
return this.decrypt(encryptedKey);
}
decrypt(encryptedData) {
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes-256-cbc', this.encryptionKey);
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Rotate API key regularly
async rotateAPIKey() {
const newKey = await this.requestNewAPIKey();
const encryptedNewKey = this.encrypt(newKey);
// Update environment variable or secure storage
await this.updateSecureStorage('THE8_API_KEY_ENCRYPTED', encryptedNewKey);
this.apiKey = newKey;
}
}
Request Validation and Sanitization
// Input validation and sanitization
const validateVisitorData = (data) => {
const schema = {
ip_address: {
required: true,
type: 'string',
pattern: /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$|^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/
},
user_agent: {
required: true,
type: 'string',
maxLength: 1000
},
referrer: {
required: false,
type: 'string',
maxLength: 2000
},
page_url: {
required: false,
type: 'string',
maxLength: 2000,
pattern: /^https?:\/\/.+/
}
};
const errors = [];
for (const [field, rules] of Object.entries(schema)) {
const value = data[field];
if (rules.required && !value) {
errors.push(`${field} is required`);
continue;
}
if (value) {
if (rules.type === 'string' && typeof value !== 'string') {
errors.push(`${field} must be a string`);
}
if (rules.maxLength && value.length > rules.maxLength) {
errors.push(`${field} exceeds maximum length of ${rules.maxLength}`);
}
if (rules.pattern && !rules.pattern.test(value)) {
errors.push(`${field} format is invalid`);
}
}
}
if (errors.length > 0) {
throw new Error(`Validation errors: ${errors.join(', ')}`);
}
return true;
};
Getting Started Checklist
Phase 1: Basic Integration (Week 1)
- Sign up for THE8.AI API access
- Generate API key and configure authentication
- Install SDK or implement REST API calls
- Test basic visitor identification with sample data
- Implement error handling and logging
- Set up rate limiting protection
- Configure caching for optimal performance
Phase 2: Advanced Features (Week 2-3)
- Implement behavioral tracking with custom events
- Set up webhook endpoints for real-time notifications
- Integrate with CRM systems (Salesforce, HubSpot)
- Build custom intent scoring algorithms
- Create visitor segmentation rules
- Set up A/B testing framework
- Implement progressive profiling strategies
Phase 3: Optimization and Scale (Week 4+)
- Monitor API performance and optimize bottlenecks
- Implement advanced caching strategies
- Set up automated testing and CI/CD
- Create custom dashboards and reporting
- Scale infrastructure for production traffic
- Train team on API usage and best practices
- Document implementation for future reference
API Support and Resources
Getting Help
Documentation and Resources:
- API Reference: https://docs.the8.ai/api
- SDKs and Libraries: https://github.com/the8ai/sdks
- Code Examples: https://docs.the8.ai/examples
- Postman Collection: https://the8.ai/postman
Support Channels:
- Email Support: [email protected]
- Developer Slack: https://the8.ai/slack
- Stack Overflow: Tag questions with
the8ai
- GitHub Issues: https://github.com/the8ai/api-issues
Service Level Agreement
Uptime Guarantee:
- 99.9% uptime SLA for production API
- <100ms average response time
- 24/7 monitoring and alerting
- Automatic failover across regions
Support Response Times:
- Critical issues: <2 hours
- High priority: <8 hours
- Normal priority: <24 hours
- Low priority: <72 hours
Transform your website into a lead identification powerhouse with THE8.AI's Visitor Identification API. Start building intelligent visitor tracking that converts anonymous traffic into qualified opportunities.