Search Event
Track when users perform searches on your site. This event maps to Facebook Search
and TikTok Search standard events, enabling search retargeting audiences,
intent-based optimization, and product discovery analysis.
When to Use This Event
The search event should be triggered when a user performs a search.
This typically occurs when:
- User submits a search query on your site
- User uses autocomplete search suggestions
- User filters or refines search results
- User searches within a specific category
| Platform | Event Name | Key Parameter |
|---|---|---|
| Facebook Pixel / CAPI | Search |
search_string |
| TikTok Pixel / Events API | Search |
query |
SDK Loading
Load the AxiTrace SDK synchronously in your <head> before any tracking calls:
<!-- In <head> -->
<script src="https://stat.axitrace.com/axitrack.js"></script>
<script>
Axitrace.init({
publicKey: 'pk_live_YOUR_PUBLIC_KEY'
});
</script>
The SDK is ~11 KB gzipped. Loading synchronously in <head> ensures
Axitrace._instance is available when your search handler fires.
Client-Side vs Server-Side Tracking
For each search event, use either the JavaScript SDK or the server-side API — not both.
The JavaScript SDK automatically fires Facebook and TikTok pixels with a matching
eventID, then sends the event to the AxiTrace backend which forwards it to CAPI.
Facebook/TikTok deduplicates using the shared eventID, counting one event.
If you also send the same event via the server-side PHP SDK, it generates a different
eventID — causing Facebook/TikTok to count the event twice.
Recommendation: Use the JavaScript SDK for search events triggered by user interactions in the browser. Reserve server-side tracking for searches that happen without a browser (e.g., API-driven search, mobile apps, or server-to-server integrations).
Request Parameters
User Identification
At least one of these identifiers is required:
| Field | Type | Description |
|---|---|---|
client_id |
string | Your custom user/visitor identifier (use SDK's vt_vid cookie value) |
user_id |
string | Authenticated user ID |
session_id |
string | Current session identifier (use SDK's vt_sid cookie value) |
For server-side events, you must pass the same user identifiers that the JavaScript SDK generates. The SDK stores these in cookies:
vt_vid— Visitor ID (persistent anonymous identifier → use asclient_id)vt_sid— Session ID (current browsing session → use assession_id)vt_uid— User ID (set viaidentify()→ use asuser_id)
Read these cookies and pass them in your server-side events to properly link all events to the same user profile. See the User Identification guide for complete details.
Required Fields
| Field | Type | Description |
|---|---|---|
search_term |
string |
The search query entered by the user. Required, must be non-empty.
Maps to Facebook search_string and TikTok query.
|
Optional Parameters (via params)
Include these fields in the params object for enhanced tracking:
| Field | Type | Description |
|---|---|---|
results_count |
integer | Number of search results returned |
category |
string | Category filter applied (if any). Maps to Facebook content_category |
filters |
object | Applied filters (price range, brand, size, etc.) |
sort_by |
string | Sort option used (relevance, price_asc, price_desc, etc.) |
page |
integer | Current page number in paginated results |
Customer Data (for Facebook CAPI)
Include these fields in the params object to enhance Facebook Conversions API matching:
| Field | Type | Description |
|---|---|---|
phone |
string | Phone number (E.164 format recommended). Sent as plain text — AxiTrace auto-hashes for Facebook. |
first_name |
string | User's first name. Sent as plain text — AxiTrace auto-hashes for Facebook. |
last_name |
string | User's last name. Sent as plain text — AxiTrace auto-hashes for Facebook. |
city |
string | City name |
state |
string | State or province |
zip |
string | ZIP or postal code |
country |
string | Country code (ISO 3166-1 alpha-2) |
fbp |
string | Facebook Pixel browser ID (from _fbp cookie) |
fbc |
string | Facebook Click ID (from _fbc cookie) |
Send all customer data (phone, first_name, last_name, etc.) as plain text. AxiTrace passes these values to the Facebook PHP SDK, which automatically normalizes and SHA-256 hashes them before sending to CAPI. Pre-hashing will cause double-hashing and break Facebook's matching.
Pixel Deduplication
When using the JavaScript SDK, search events are automatically deduplicated
between browser pixels and server-side CAPI:
- SDK generates a unique
eventSalt(UUID) for eachtrack()call - SDK fires
fbq('track', 'Search', {search_string: term}, {eventID: eventSalt})in the browser - SDK fires
ttq.track('Search', {query: term}, {event_id: eventSalt})in the browser - SDK sends the event (with the same
eventSalt) to the AxiTrace backend - Backend forwards the event to Facebook CAPI and TikTok Events API with the same
eventSaltas the event ID - Facebook/TikTok matches the pixel event and CAPI event by
eventIDand counts it once
This happens automatically — you don't need to manage event IDs manually.
Server-Enriched Fields
The following fields are automatically added by the server:
| Field | Description |
|---|---|
ip |
Client IP address (extracted from X-Forwarded-For, CF-Connecting-IP, etc.) |
userAgent |
Browser User-Agent string |
timestamp |
Server timestamp (ISO 8601 format) |
Examples
JavaScript SDK (Recommended for Browser Events)
// Basic search tracking
Axitrace._instance.track('search', {
search_term: 'blue running shoes'
});
// Search with results count and filters
Axitrace._instance.track('search', {
search_term: 'wireless headphones',
results_count: 42,
category: 'Electronics',
filters: {
brand: 'Sony',
price_min: 50,
price_max: 200
},
sort_by: 'price_asc'
});
Server-Side (cURL)
# Basic search
curl -X POST https://stat.axitrace.com/v1/search \
-u "sk_live_YOUR_SECRET_KEY:" \
-H "Content-Type: application/json" \
-d '{
"client_id": "value-from-vt_vid-cookie",
"session_id": "value-from-vt_sid-cookie",
"search_term": "blue running shoes"
}'
Server-Side with Full Data (cURL)
# Search with results and Facebook CAPI data
curl -X POST https://stat.axitrace.com/v1/search \
-u "sk_live_YOUR_SECRET_KEY:" \
-H "Content-Type: application/json" \
-d '{
"client_id": "value-from-vt_vid-cookie",
"user_id": "user-12345",
"session_id": "value-from-vt_sid-cookie",
"search_term": "wireless headphones",
"params": {
"results_count": 42,
"category": "Electronics",
"filters": {
"brand": "Sony",
"price_min": 50,
"price_max": 200
},
"sort_by": "relevance",
"fbp": "fb.1.1234567890.987654321",
"fbc": "fb.1.1234567890.AbCdEfGhIjKl"
}
}'
Server-Side (AxiTrace PHP SDK)
<?php
use AxiTrace\AxiTrace;
// Initialize — auto-reads vt_vid, vt_sid, _fbp, _fbc cookies
$axitrace = AxiTrace::init('sk_live_YOUR_SECRET_KEY');
// Get search parameters from request
$searchTerm = $_GET['q'] ?? '';
$category = $_GET['category'] ?? null;
// Perform search in your system
$results = performSearch($searchTerm, $category);
// Track to AxiTrace (cookies are read automatically)
$response = $axitrace->search($searchTerm, array_filter([
'results_count' => count($results),
'category' => $category,
'sort_by' => $_GET['sort'] ?? 'relevance',
'page' => (int)($_GET['page'] ?? 1),
]));
// $response->getEventId() — unique event identifier
When using AxiTrace::init(), the SDK automatically reads:
vt_vidcookie →client_idvt_sidcookie →session_id_fbpcookie →params.fbp_fbccookie →params.fbc- URL parameters →
fbclid,utm_source,gclid, etc.
You don't need to manually extract and pass these values — the SDK handles it.
Call $axitrace->disableAutoReadCookies() if you want to set identifiers manually.
PHP SDK — Advanced (Using SearchEvent Directly)
<?php
use AxiTrace\AxiTrace;
use AxiTrace\Model\Event\SearchEvent;
$axitrace = AxiTrace::init('sk_live_YOUR_SECRET_KEY');
// Create search event with full control
$event = new SearchEvent('wireless headphones');
$event->setResultsCount(42);
$event->setCategory('Electronics');
$event->setFilters([
'brand' => 'Sony',
'price_min' => 50,
'price_max' => 200,
]);
$event->setSortBy('relevance');
$event->setPage(1);
// Add Facebook CAPI data for higher match quality
$event->setPhone('+1234567890'); // Plain text — auto-hashed by AxiTrace
$event->setFirstName('John'); // Plain text — auto-hashed by AxiTrace
$event->setLastName('Doe'); // Plain text — auto-hashed by AxiTrace
$response = $axitrace->track($event);
Server-Side (PHP — Manual cURL)
<?php
// If you prefer not to use the PHP SDK, you can call the API directly
$secretKey = getenv('AXITRACE_SECRET_KEY');
// Read AxiTrace SDK cookies — CRITICAL for user profile linking
$visitorId = $_COOKIE['vt_vid'] ?? null;
$sessionId = $_COOKIE['vt_sid'] ?? null;
// Read Facebook cookies for CAPI matching
$fbp = $_COOKIE['_fbp'] ?? null;
$fbc = $_COOKIE['_fbc'] ?? null;
// Get search parameters
$searchTerm = $_GET['q'] ?? '';
$category = $_GET['category'] ?? null;
// Perform search in your system
$results = performSearch($searchTerm, $category);
// Track to AxiTrace
$data = [
'client_id' => $visitorId,
'session_id' => $sessionId,
'search_term' => $searchTerm,
'params' => array_filter([
'results_count' => count($results),
'category' => $category,
'sort_by' => $_GET['sort'] ?? 'relevance',
'page' => (int)($_GET['page'] ?? 1),
'fbp' => $fbp,
'fbc' => $fbc,
]),
];
$ch = curl_init('https://stat.axitrace.com/v1/search');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_USERPWD => $secretKey . ':',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'User-Agent: MyApp/1.0'
],
CURLOPT_POSTFIELDS => json_encode($data)
]);
$response = curl_exec($ch);
curl_close($ch);
Server-Side (Python)
import os
import requests
from flask import request
secret_key = os.environ.get('AXITRACE_SECRET_KEY')
@app.route('/search')
def search():
# Read AxiTrace SDK cookies — CRITICAL for user profile linking
visitor_id = request.cookies.get('vt_vid')
session_id = request.cookies.get('vt_sid')
# Read Facebook cookies for CAPI matching
fbp = request.cookies.get('_fbp')
fbc = request.cookies.get('_fbc')
# Get search parameters
search_term = request.args.get('q', '')
category = request.args.get('category')
# Perform search
results = perform_search(search_term, category)
# Track to AxiTrace
requests.post(
'https://stat.axitrace.com/v1/search',
auth=(secret_key, ''),
json={
'client_id': visitor_id,
'session_id': session_id,
'search_term': search_term,
'params': {
'results_count': len(results),
'category': category,
'sort_by': request.args.get('sort', 'relevance'),
'page': int(request.args.get('page', 1)),
'fbp': fbp,
'fbc': fbc,
}
}
)
return render_results(results)
Response
Success Response (200 OK)
{
"success": true,
"eventId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"action": "search"
}
Error Responses
| Status | Error | Description |
|---|---|---|
400 |
at least one of client_id, user_id, or session_id is required |
No user identifier provided |
400 |
search_term is required |
Missing or empty search query |
401 |
unauthorized |
Invalid or missing API key |
E-commerce Integration Examples
WooCommerce (WordPress)
// Track WooCommerce search results page
document.addEventListener('DOMContentLoaded', function() {
// Check if we're on a search results page
var searchParams = new URLSearchParams(window.location.search);
var searchTerm = searchParams.get('s');
if (searchTerm && typeof Axitrace !== 'undefined' && Axitrace._instance) {
// Count visible products
var resultCount = document.querySelectorAll('.products .product').length;
Axitrace._instance.track('search', {
search_term: searchTerm,
results_count: resultCount
});
}
});
React Search Component
// SearchBox.jsx
import { useState, useCallback } from 'react';
import { useDebounce } from './hooks/useDebounce';
export function SearchBox({ onSearch }) {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const performSearch = useCallback(async (searchTerm) => {
if (!searchTerm.trim()) return;
// Fetch results from your API
const response = await fetch(`/api/search?q=${encodeURIComponent(searchTerm)}`);
const data = await response.json();
setResults(data.results);
// Track search event — fires Facebook Search + TikTok Search pixels automatically
if (typeof Axitrace !== 'undefined') {
Axitrace._instance.track('search', {
search_term: searchTerm,
results_count: data.results.length
});
}
}, []);
// Debounce search to avoid tracking every keystroke
const debouncedSearch = useDebounce(performSearch, 500);
const handleSubmit = (e) => {
e.preventDefault();
performSearch(query);
};
return (
<form onSubmit={handleSubmit}>
<input
type="search"
value={query}
onChange={(e) => {
setQuery(e.target.value);
debouncedSearch(e.target.value);
}}
placeholder="Search products..."
/>
<button type="submit">Search</button>
</form>
);
}
Best Practices
- Track actual searches — Fire the event after the search is performed, not on every keystroke
- Include results count — Track
results_countto identify searches with no results (inventory gaps) - Debounce autocomplete — For instant search, debounce to avoid excessive events (500ms recommended)
- Track filters — Include applied filters to understand user refinement behavior
- Link to browser session — Pass SDK cookie values (
vt_vid,vt_sid) to connect server-side searches with user profiles - Track zero-result searches — These reveal inventory gaps or search optimization opportunities
- Don't double-track — Choose either JS SDK or server-side for each event. Sending both creates duplicate events with different eventIDs.
- Use the PHP SDK — Prefer
AxiTrace::init()over manual cURL calls. The SDK auto-reads cookies, forwards client IP/user-agent, and handles attribution parameters.
Search events enable powerful analytics. AxiTrace helps you analyze:
- Top search terms by volume and conversion rate
- Searches with zero results (product gaps)
- Search-to-purchase conversion funnel
- Most effective search refinements
- Search behavior by traffic source