### Track Server-Side Events (cURL Example)
Source: https://www.supalytics.co/docs/api/server-side-events
Example demonstrating how to track server-side events using cURL. It includes the endpoint, authorization header, content type, and a JSON payload with event details and metadata.
```shell
curl -X POST https://api.supalytics.co/v1/events \
-H "Authorization: Bearer sly_xxx..." \
-H "Content-Type: application/json" \
-d '{
"name": "subscription_created",
"visitor_id": "abc123",
"metadata": {
"plan": "pro",
"amount": 29
}
}'
```
--------------------------------
### Filter Example: Traffic from Google
Source: https://www.supalytics.co/docs/api/analytics
This filter tuple targets traffic originating from google.com. It uses the 'is' operator and the 'referrer' field.
```json
["is", "referrer", "google.com"]
```
--------------------------------
### Add Supalytics Tracking Script to Website Head
Source: https://www.supalytics.co/docs/install-script
This script tag should be added to the `
` section of your website to integrate Supalytics tracking. Ensure you replace 'YOUR_SITE_ID' with your actual site ID. The 'defer' attribute is recommended to prevent blocking page rendering.
```html
```
--------------------------------
### Filter Example: Pages Containing '/blog'
Source: https://www.supalytics.co/docs/api/analytics
This filter tuple targets pages whose URLs contain the string '/blog'. It uses the 'contains' operator and the 'page' field.
```json
["contains", "page", "/blog"]
```
--------------------------------
### Track Button Click Event with JavaScript
Source: https://www.supalytics.co/docs/custom-events
Implement event tracking for button clicks using JavaScript event listeners. This example demonstrates capturing a 'cta_click' event with location metadata.
```javascript
document.querySelector('#cta-button').addEventListener('click', () => {
window.supalytics.trackEvent('cta_click', { location: 'hero' })
})
```
--------------------------------
### Analytics API - Get Overview Stats (JSON)
Source: https://www.supalytics.co/docs/api/analytics
A simple JSON request body to retrieve core overview statistics like pageviews and visitors. This example is useful for obtaining a quick summary of website traffic.
```json
{
"metrics": ["pageviews", "visitors"]
}
```
--------------------------------
### Custom Date Range Example (JSON)
Source: https://www.supalytics.co/docs/api/analytics
This JSON snippet shows how to specify a custom date range for analytics queries using an array of two ISO date strings.
```json
{
"date_range": ["2024-01-01", "2024-01-31"]
}
```
--------------------------------
### Track Event in React Component
Source: https://www.supalytics.co/docs/custom-events
Integrate Supalytics event tracking within a React functional component. This example shows how to trigger a 'signup_click' event with source metadata upon button click.
```javascript
function SignupButton() {
const handleClick = () => {
window.supalytics.trackEvent('signup_click', { source: 'navbar' })
}
return
}
```
--------------------------------
### Track Payment with Supalytics API (cURL)
Source: https://www.supalytics.co/docs/api/revenue-attribution
This example demonstrates how to track a new subscription purchase using the Supalytics Revenue Attribution API via cURL. It includes the necessary endpoint, headers, and JSON body with payment details.
```shell
curl -X POST https://api.supalytics.co/v1/payments \
-H "Authorization: Bearer sly_xxx..." \
-H "Content-Type: application/json" \
-d '{
"amount": 29.99,
"currency": "USD",
"transaction_id": "pay_1234567890",
"visitor_id": "abc123",
"mode": "subscription",
"event": "purchase"
}'
```
```shell
curl -X POST https://api.supalytics.co/v1/payments \
-H "Authorization: Bearer sly_xxx..." \
-H "Content-Type: application/json" \
-d '{
"amount": 49.00,
"currency": "USD",
"transaction_id": "sub_trial_abc123",
"visitor_id": "abc123",
"mode": "subscription",
"event": "trial"
}'
```
--------------------------------
### Get Traffic by Country with Revenue (JSON)
Source: https://www.supalytics.co/docs/api/analytics
Retrieves traffic statistics including visitors and revenue, broken down by country. Includes configuration for metrics, dimensions, and a revenue flag.
```json
{
"metrics": ["visitors", "revenue", "conversion_rate"],
"dimensions": ["country"],
"include_revenue": true,
"limit": 20
}
```
--------------------------------
### Track Form Submission Event with JavaScript
Source: https://www.supalytics.co/docs/custom-events
Track form submissions by attaching an event listener to the form element. This example logs a 'form_submit' event with the form identifier.
```javascript
document.querySelector('form').addEventListener('submit', () => {
window.supalytics.trackEvent('form_submit', { form: 'contact' })
})
```
--------------------------------
### Track Event in Next.js Component (Client Component)
Source: https://www.supalytics.co/docs/custom-events
Implement Supalytics event tracking in a Next.js client component, ensuring the `window.supalytics` object is available before tracking. This example tracks a 'download' event with file metadata.
```javascript
'use client'
export function DownloadButton() {
const handleClick = () => {
if (typeof window !== 'undefined' && window.supalytics) {
window.supalytics.trackEvent('download', { file: 'guide.pdf' })
}
}
return
}
```
--------------------------------
### Example Analytics API Response (JSON)
Source: https://www.supalytics.co/docs/api/analytics
This JSON object illustrates a typical response from the Supalytics analytics API. It contains an array of results, where each result includes dimensions and their corresponding metrics, along with metadata about the query.
```json
{
"results": [
{
"dimensions": { "page": "/blog/getting-started" },
"metrics": { "pageviews": 1234, "visitors": 567 }
},
{
"dimensions": { "page": "/blog/advanced-tips" },
"metrics": { "pageviews": 890, "visitors": 432 }
}
],
"meta": {
"date_range": ["2024-11-22", "2024-12-22"],
"total_rows": 2,
"query_time_ms": 23
}
}
```
--------------------------------
### Track Backend-Only Server-Side Events (JavaScript)
Source: https://www.supalytics.co/docs/api/server-side-events
Example for tracking server-side events when no visitor context is available, such as for cron jobs or webhooks. The `visitor_id` is omitted in this case.
```javascript
await fetch("https://api.supalytics.co/v1/events", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUPALYTICS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "daily_report_sent",
metadata: { recipients: 150 },
}),
});
```
--------------------------------
### Filter Example: Visitors from US or UK
Source: https://www.supalytics.co/docs/api/analytics
This filter tuple selects visitors from either the US or the UK. It uses the 'is' operator with comma-separated values for the 'country' field.
```json
["is", "country", "US,UK"]
```
--------------------------------
### Analytics API
Source: https://www.supalytics.co/docs/api/analytics
Query your analytics data programmatically. Get pageviews, visitors, and other metrics with flexible filtering and grouping.
```APIDOC
## POST /v1/analytics
### Description
Query your analytics data programmatically. Get pageviews, visitors, and other metrics with flexible filtering and grouping.
### Method
POST
### Endpoint
https://api.supalytics.co/v1/analytics
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **metrics** (string[]) - Required - Metrics to return. See Available Metrics.
- **date_range** (string or [string, string]) - Optional - Time period. Default: "30d".
- **dimensions** (string[]) - Optional - Group results by dimension. Max 2. See Available Dimensions.
- **filters** ([operator, field, value][]) - Optional - Filter data. See Filters.
- **limit** (number) - Optional - Max results (1-1000). Default: 100.
- **offset** (number) - Optional - Skip results for pagination. Default: 0.
- **include_revenue** (boolean) - Optional - Include revenue metrics. Default: false.
### Request Example
```json
{
"metrics": ["pageviews", "visitors"],
"date_range": "30d",
"dimensions": ["page"],
"filters": [
["contains", "page", "/blog"]
],
"limit": 10
}
```
### Response
#### Success Response (200)
- **results** (array) - An array of dimension and metric objects.
- **dimensions** (object) - Object containing the dimensions by which the data is grouped.
- **metrics** (object) - Object containing the requested metrics.
- **meta** (object) - Metadata about the response.
- **date_range** (array) - The actual date range for the returned data.
- **total_rows** (number) - The total number of rows matching the query.
- **query_time_ms** (number) - The time taken to execute the query in milliseconds.
#### Response Example
```json
{
"results": [
{
"dimensions": { "page": "/blog/getting-started" },
"metrics": { "pageviews": 1234, "visitors": 567 }
},
{
"dimensions": { "page": "/blog/advanced-tips" },
"metrics": { "pageviews": 890, "visitors": 432 }
}
],
"meta": {
"date_range": ["2024-11-22", "2024-12-22"],
"total_rows": 2,
"query_time_ms": 23
}
}
```
### Error Handling
- **401 Unauthorized**: Invalid or missing API key.
- **403 Forbidden**: Usage limit exceeded.
- **429 Too Many Requests**: Rate limit exceeded.
```
--------------------------------
### Filter Example: Exclude Mobile Devices
Source: https://www.supalytics.co/docs/api/analytics
This filter tuple excludes data from mobile devices. It uses the 'is_not' operator and the 'device' field.
```json
["is_not", "device", "mobile"]
```
--------------------------------
### Initiate OAuth Login with Visitor ID (JavaScript)
Source: https://www.supalytics.co/docs/backfill-existing-subscriptions
Client-side JavaScript function to capture the visitor ID and initiate the OAuth login flow by requesting an OAuth URL from the server. It expects `window.supalytics.visitorId` to be available.
```javascript
const handleOAuthLogin = async () => {
const visitorId = window.supalytics?.visitorId || null;
// Your server builds the OAuth URL with visitorId
const response = await fetch('/api/auth/oauth-url', {
method: 'POST',
body: JSON.stringify({
provider: 'google',
supalyticsVisitorId: visitorId,
}),
});
const { authUrl } = await response.json();
window.location.href = authUrl;
};
```
--------------------------------
### Build OAuth URL with Visitor ID Parameter (Node.js)
Source: https://www.supalytics.co/docs/backfill-existing-subscriptions
Server-side Node.js function to construct an OAuth URL, ensuring the `supalyticsVisitorId` is appended as a URL parameter to the callback URL if provided. It utilizes environment variables for the application URL.
```javascript
const buildOAuthUrl = (provider, supalyticsVisitorId) => {
const callbackUrl = new URL('/auth/callback', process.env.APP_URL);
if (supalyticsVisitorId) {
callbackUrl.searchParams.set('supalyticsVisitorId', supalyticsVisitorId);
}
// Use this callback URL when initiating OAuth
return getOAuthUrl(provider, callbackUrl.toString());
};
```
--------------------------------
### Query Analytics Data with cURL
Source: https://www.supalytics.co/docs/api/analytics
This snippet demonstrates how to query analytics data using the cURL command-line tool. It specifies the endpoint, authentication headers, and a JSON payload containing the desired metrics, date range, dimensions, and filters. This is useful for direct API interaction and scripting.
```shell
curl -X POST https://api.supalytics.co/v1/analytics \
-H "Authorization: Bearer sly_xxx..." \
-H "Content-Type: application/json" \
-d '{
"metrics": ["pageviews", "visitors"],
"date_range": "30d",
"dimensions": ["page"],
"filters": [
["contains", "page", "/blog"]
],
"limit": 10
}'
```
--------------------------------
### Tracking Events with JavaScript API
Source: https://www.supalytics.co/docs/custom-events
Use the `window.supalytics.trackEvent()` method for more control over event tracking, including adding metadata.
```APIDOC
## Tracking Events with JavaScript API
### Description
Use the `window.supalytics.trackEvent()` function to programmatically track custom events and their associated metadata.
### Method
JavaScript API
### Endpoint
`window.supalytics.trackEvent(eventName: string, metadata?: Record): Promise`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **eventName** (string) - Required - The name of the event to track.
- **metadata** (object) - Optional - Key-value pairs of additional data to associate with the event.
### Request Example - Basic Event
```javascript
window.supalytics.trackEvent('signup_click')
```
### Request Example - Event with Metadata
```javascript
window.supalytics.trackEvent('purchase', {
plan: 'pro',
price: 29,
currency: 'USD'
})
```
### Request Example - Button Click Handler
```javascript
document.querySelector('#cta-button').addEventListener('click', () => {
window.supalytics.trackEvent('cta_click', { location: 'hero' })
})
```
### Request Example - Form Submission Handler
```javascript
document.querySelector('form').addEventListener('submit', () => {
window.supalytics.trackEvent('form_submit', { form: 'contact' })
})
```
### Request Example - React Component
```javascript
function SignupButton() {
const handleClick = () => {
window.supalytics.trackEvent('signup_click', { source: 'navbar' })
}
return
}
```
### Request Example - Next.js Component
```javascript
'use client'
export function DownloadButton() {
const handleClick = () => {
if (typeof window !== 'undefined' && window.supalytics) {
window.supalytics.trackEvent('download', { file: 'guide.pdf' })
}
}
return
}
```
### Response
#### Success Response (200)
This method returns a Promise that resolves when the event has been tracked.
#### Response Example
(No specific response body is returned for success, the promise resolves)
```
--------------------------------
### Capture and Store Supalytics Visitor ID at Signup (Client-Side)
Source: https://www.supalytics.co/docs/revenue-attribution
Captures the Supalytics visitor ID from the browser's global scope during user signup and sends it to the server for storage. This is recommended for accurate attribution, especially for SaaS models with free plans or trials. It handles cases where the visitor ID might not be available.
```javascript
const signupData = {
email: userEmail,
// ... other signup data
supalyticsVisitorId: window.supalytics?.visitorId || null,
};
await fetch('/api/signup', {
method: 'POST',
body: JSON.stringify(signupData),
});
```
--------------------------------
### Supalytics Client API Reference
Source: https://www.supalytics.co/docs/custom-events
Documentation for the `window.supalytics.trackEvent` method, detailing its parameters and their types. This function is used to track custom events from the client-side.
```javascript
window.supalytics.trackEvent(
eventName: string,
metadata?: Record
): Promise
```
--------------------------------
### Create Stripe Customer with Supalytics Visitor ID Metadata (Server-Side)
Source: https://www.supalytics.co/docs/revenue-attribution
Server-side code to create a new customer in Stripe, including the Supalytics visitor ID in the customer's metadata. This approach associates the visitor ID with the Stripe customer object for later use in payment creation.
```javascript
const customer = await stripe.customers.create({
email: userEmail,
metadata: {
supalytics_visitor_id: visitorId, // from client request
},
});
```
--------------------------------
### Capture Visitor ID on Client-Side Login
Source: https://www.supalytics.co/docs/backfill-existing-subscriptions
This JavaScript code captures the visitor ID from the Supalytics SDK on the client-side during user login and sends it to the server via a POST request.
```javascript
// Client-side: capture on login
const handleLogin = async () => {
const visitorId = window.supalytics?.visitorId || null;
await fetch('/api/auth/login', {
method: 'POST',
body: JSON.stringify({
email,
password,
supalyticsVisitorId: visitorId,
}),
});
};
```
--------------------------------
### Handle OAuth Callback with Visitor ID (Node.js)
Source: https://www.supalytics.co/docs/backfill-existing-subscriptions
Server-side Node.js function to process the OAuth callback. It extracts the `supalyticsVisitorId` from the URL parameters, authenticates the user, and if the visitor ID exists, it stores it and updates Stripe subscription metadata before redirecting to the dashboard.
```javascript
const handleOAuthCallback = async (request) => {
const url = new URL(request.url);
const supalyticsVisitorId = url.searchParams.get('supalyticsVisitorId');
// After authenticating user...
const user = await authenticateOAuthUser(request);
// Store visitor ID and update Stripe (same as Step 3 & 4)
if (supalyticsVisitorId) {
await storeVisitorIdAndUpdateStripe(user.id, supalyticsVisitorId);
}
return redirect('/dashboard');
};
```
--------------------------------
### Revenue Attribution API
Source: https://www.supalytics.co/docs/api/errors
The Revenue Attribution API allows you to track revenue from various payment providers.
```APIDOC
## POST /v1/payments
### Description
Track revenue from any payment provider.
### Method
POST
### Endpoint
/v1/payments
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **payment_provider** (string) - Required - The name of the payment provider.
* **transaction_id** (string) - Required - The unique identifier for the transaction.
* **amount** (number) - Required - The amount of the payment.
* **currency** (string) - Required - The currency of the payment (e.g., USD).
* **timestamp** (string) - Required - The time the payment occurred (ISO 8601 format).
* **user_id** (string) - Optional - The ID of the user associated with the payment.
### Request Example
```json
{
"payment_provider": "Stripe",
"transaction_id": "ch_12345abcde",
"amount": 99.99,
"currency": "USD",
"timestamp": "2023-10-27T10:00:00Z",
"user_id": "user_xyz789"
}
```
### Response
#### Success Response (200)
* **message** (string) - A confirmation message indicating the revenue was tracked successfully.
#### Response Example
```json
{
"message": "Revenue tracked successfully."
}
```
```
--------------------------------
### Track Server-Side Events (JavaScript Fetch API)
Source: https://www.supalytics.co/docs/api/server-side-events
JavaScript code snippet using the Fetch API to send server-side events. It shows how to set up the request with necessary headers and a JSON body, utilizing environment variables for the API key.
```javascript
await fetch("https://api.supalytics.co/v1/events", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUPALYTICS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "upgraded",
visitor_id: user.storedVisitorId,
metadata: { plan: "enterprise" },
}),
});
```
--------------------------------
### Store Visitor ID on Server (Preserve First-Touch)
Source: https://www.supalytics.co/docs/backfill-existing-subscriptions
This server-side JavaScript code snippet retrieves the authenticated user and their Supalytics visitor ID from the request body. It updates the user's record in the database with the visitor ID only if a visitor ID doesn't already exist, thus preserving first-touch attribution.
```javascript
// Server-side: after successful authentication
const user = await getAuthenticatedUser();
const { supalyticsVisitorId } = requestBody;
if (supalyticsVisitorId) {
// Check if user already has a visitor ID
const existingUser = await db.user.findUnique({
where: { id: user.id },
select: { supalyticsVisitorId: true },
});
// Only update if no existing visitor ID (preserve first-touch)
if (!existingUser.supalyticsVisitorId) {
await db.user.update({
where: { id: user.id },
data: { supalyticsVisitorId },
});
}
}
```
--------------------------------
### POST /v1/analytics
Source: https://www.supalytics.co/docs/api
This endpoint allows you to query your analytics data programmatically. You can use this to retrieve and analyze your website's traffic and user behavior data.
```APIDOC
## POST /v1/analytics
### Description
Query your analytics data programmatically.
### Method
POST
### Endpoint
`/v1/analytics`
### Parameters
#### Query Parameters
* **startDate** (string) - Required - The start date for the analytics query (YYYY-MM-DD).
* **endDate** (string) - Required - The end date for the analytics query (YYYY-MM-DD).
* **dimensions** (string) - Optional - Comma-separated list of dimensions to group data by (e.g., 'country,device').
* **metrics** (string) - Optional - Comma-separated list of metrics to retrieve (e.g., 'visitors,pageviews').
#### Request Body
* **filters** (object) - Optional - An object containing filters to apply to the query.
* **field** (string) - The field to filter on (e.g., 'page', 'referrer').
* **operator** (string) - The comparison operator (e.g., '=', '!=').
* **value** (string) - The value to filter by.
```
--------------------------------
### Authenticate API Requests with Bearer Token
Source: https://www.supalytics.co/docs/api
All requests to the Supalytics API require an API key for authentication. This snippet demonstrates the format of the 'Authorization' header using a Bearer token. Ensure you replace 'sly_xxx...' with your actual API key obtained from the Supalytics settings.
```text
Authorization: Bearer sly_xxx...
```
--------------------------------
### Tracking Events with HTML Data Attributes
Source: https://www.supalytics.co/docs/custom-events
The simplest way to track events without JavaScript. Use `data-supalytics-e` for the event name and `data-supalytics-e-*` for metadata.
```APIDOC
## Tracking Events with HTML Data Attributes
### Description
Track user interactions directly from HTML elements using custom data attributes.
### Method
HTML Data Attributes
### Example - Basic Event
```html
```
### Example - Event with Metadata
```html
```
### Metadata Format
`data-supalytics-e-price="49"` will be tracked as metadata `{ price: "49" }`.
```
--------------------------------
### Track Custom Events with JavaScript API and Metadata
Source: https://www.supalytics.co/docs/custom-events
Add structured metadata to your events when using the JavaScript API. This provides rich context about the event, such as purchase details or user actions.
```javascript
window.supalytics.trackEvent('purchase', {
plan: 'pro',
price: 29,
currency: 'USD'
})
```
--------------------------------
### Query Analytics Data using Supalytics API
Source: https://www.supalytics.co/docs/api
This code snippet shows how to send a POST request to the /v1/analytics endpoint to programmatically query your analytics data. You will need to include your API key in the 'Authorization' header for the request to be processed successfully.
```text
POST /v1/analytics
Authorization: Bearer sly_xxx...
```
--------------------------------
### Filter Traffic by Referrer and Country (JSON)
Source: https://www.supalytics.co/docs/api/analytics
Fetches analytics data, such as pageviews and visitors, filtered by specific referrers and countries. Demonstrates the use of multiple filter conditions.
```json
{
"metrics": ["pageviews", "visitors"],
"dimensions": ["page"],
"filters": [
["is", "referrer", "twitter.com"],
["is", "country", "US"]
]
}
```
--------------------------------
### Error Codes
Source: https://www.supalytics.co/docs/api/errors
Defines the API error codes and their meanings for troubleshooting.
```APIDOC
## Error Codes
### Description
API error codes and what they mean.
### Method
N/A
### Endpoint
N/A
### Parameters
None
### Request Example
None
### Response
#### Success Response (200)
* **status** (integer) - The HTTP status code of the error.
* **description** (string) - A description of the error.
#### Response Example
```json
[
{ "status": 400, "description": "Invalid request body" },
{ "status": 401, "description": "Missing or invalid API key" },
{ "status": 403, "description": "Insufficient permissions" },
{ "status": 429, "description": "Rate limit exceeded (100 req/sec)" },
{ "status": 500, "description": "Server error" }
]
```
```
--------------------------------
### Track Event with HTML Data Attributes and Metadata
Source: https://www.supalytics.co/docs/custom-events
Enhance event tracking by including additional context using `data-supalytics-e-*` attributes. These attributes are automatically converted into metadata for the event.
```html
```
--------------------------------
### Add Visitor ID Column to Users Table
Source: https://www.supalytics.co/docs/backfill-existing-subscriptions
This SQL command adds a new text column named 'supalytics_visitor_id' to your 'users' table to store visitor identification information.
```sql
ALTER TABLE users
ADD COLUMN supalytics_visitor_id TEXT;
```
--------------------------------
### Traffic by country with revenue
Source: https://www.supalytics.co/docs/api/analytics
Retrieves traffic statistics broken down by country, including revenue metrics.
```APIDOC
## Traffic by country with revenue
### Description
Get traffic data including visitors, revenue, and conversion rate, grouped by country.
### Method
POST
### Endpoint
/analytics/query
### Request Body
- **metrics** (array) - Required - A list of metrics to retrieve. Should include at least 'visitors' and 'revenue'.
- **dimensions** (array) - Required - A list of dimensions to group the metrics by. Should include 'country'.
- **include_revenue** (boolean) - Required - Set to true to include revenue metrics.
- **limit** (integer) - Optional - The maximum number of results to return.
### Request Example
```json
{
"metrics": ["visitors", "revenue", "conversion_rate"],
"dimensions": ["country"],
"include_revenue": true,
"limit": 20
}
```
### Response
#### Success Response (200)
- **country** (string) - The name of the country.
- **visitors** (integer) - The number of visitors from the country.
- **revenue** (float) - The total revenue generated from the country.
- **conversion_rate** (float) - The conversion rate for visitors from the country.
#### Response Example
```json
{
"data": [
{
"country": "United States",
"visitors": 15000,
"revenue": 7500.50,
"conversion_rate": 0.045
},
{
"country": "Canada",
"visitors": 8000,
"revenue": 3000.00,
"conversion_rate": 0.030
}
]
}
```
```
--------------------------------
### Track Event with HTML Data Attributes
Source: https://www.supalytics.co/docs/custom-events
Use HTML `data-supalytics-e` attributes to track user interactions directly from your markup without writing JavaScript. This is the simplest method for basic event tracking.
```html
```
--------------------------------
### Track Custom Events with JavaScript API
Source: https://www.supalytics.co/docs/custom-events
Utilize the `window.supalytics.trackEvent()` JavaScript function for more dynamic and controlled event tracking. This method allows for programmatic event triggering.
```javascript
window.supalytics.trackEvent('signup_click')
```
--------------------------------
### POST /v1/payments - Track Revenue Attribution
Source: https://www.supalytics.co/docs/api/server-side-events
Track revenue from any payment provider using this endpoint.
```APIDOC
## POST /v1/payments
### Description
Track revenue from any payment provider.
### Method
POST
### Endpoint
`https://api.supalytics.co/v1/payments`
```
--------------------------------
### Analytics API - Top Pages by Visitors (JSON)
Source: https://www.supalytics.co/docs/api/analytics
This JSON request body demonstrates how to retrieve a list of top pages ranked by visitor count. It specifies the desired metrics, groups the results by 'page' dimension, and sets a limit for the number of results.
```json
{
"metrics": ["pageviews", "visitors"],
"dimensions": ["page"],
"limit": 10
}
```
--------------------------------
### Server-Side Events API
Source: https://www.supalytics.co/docs/api/analytics
Track events from your backend using the Supalytics REST API.
```APIDOC
## POST /v1/events
### Description
Track events from your backend.
### Method
POST
### Endpoint
/v1/events
### Request Body
- **metrics** (array) - Required - A list of metrics to retrieve.
- **dimensions** (array) - Required - A list of dimensions to group the metrics by.
- **include_revenue** (boolean) - Optional - Whether to include revenue metrics.
- **limit** (integer) - Optional - The maximum number of results to return.
- **filters** (array) - Optional - A list of filters to apply to the query.
### Request Example
```json
{
"metrics": ["visitors", "revenue", "conversion_rate"],
"dimensions": ["country"],
"include_revenue": true,
"limit": 20
}
```
### Response
#### Success Response (200)
- **data** (array) - The analytics data.
#### Response Example
```json
{
"data": [
{
"country": "United States",
"visitors": 10000,
"revenue": 5000,
"conversion_rate": 0.05
}
]
}
```
```
--------------------------------
### Tracking Events with Server-Side API
Source: https://www.supalytics.co/docs/custom-events
Track events from your backend using the Server-Side Events API, ideal for webhooks, cron jobs, or server code.
```APIDOC
## Tracking Events with Server-Side API
### Description
Send event data directly from your backend to Supalytics using the Server-Side Events API.
### Method
POST
### Endpoint
`https://api.supalytics.co/v1/events`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **name** (string) - Required - The name of the event.
- **visitor_id** (string) - Required - The unique identifier for the visitor.
- **metadata** (object) - Optional - Key-value pairs of additional data.
### Request Example
```javascript
await fetch("https://api.supalytics.co/v1/events", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUPALYTICS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "subscription_created",
visitor_id: user.visitorId,
metadata: { plan: "pro" },
}),
});
```
### Response
#### Success Response (200)
Indicates the event was successfully received by the Supalytics API.
#### Response Example
(Typically an empty or minimal success confirmation)
```
--------------------------------
### Authentication
Source: https://www.supalytics.co/docs/api
All requests to the Supalytics API require an API key for authentication. You can generate your API key in the 'Settings -> API Keys' section of your Supalytics account.
```APIDOC
## Authentication
All requests require an API key. Create one in **Settings → API Keys**.
### Request Header Example
```
Authorization: Bearer sly_xxx...
```
```
--------------------------------
### POST /v1/payments - Track Revenue
Source: https://www.supalytics.co/docs/api/revenue-attribution
Record revenue from any payment provider, including one-time payments and subscriptions, with traffic source attribution.
```APIDOC
## POST /v1/payments
### Description
Track revenue from any payment provider (Paddle, LemonSqueezy, custom billing, etc.) with traffic source attribution.
### Method
POST
### Endpoint
`https://api.supalytics.co/v1/payments`
### Parameters
#### Headers
- **Authorization** (string) - Required - Bearer token for authentication.
- **Content-Type** (string) - Required - `application/json`.
#### Request Body
- **amount** (number) - Required - Payment amount in dollars (e.g., 29.99). For trials, use the plan price (potential revenue).
- **currency** (string) - Required - 3-letter ISO currency code (e.g., "USD", "EUR").
- **transaction_id** (string) - Required - Unique ID from your payment provider.
- **visitor_id** (string) - Optional - Supalytics visitor ID for attribution.
- **mode** (string) - Optional - `subscription` or `payment` (one-time). Defaults to `subscription`.
- **event** (string) - Optional - Event type. Defaults to `purchase`. See Event Types below.
- **timestamp** (string) - Optional - ISO 8601 timestamp (defaults to now).
### Event Types
- **purchase**: New purchase (one-time or first subscription payment)
- **trial**: Free trial started
- **renewal**: Recurring subscription payment
- **refund**: Full refund
- **partial_refund**: Partial refund
- **chargeback**: Disputed charge
- **upgrade**: Plan upgrade
- **downgrade**: Plan downgrade
- **cancellation**: Subscription cancelled
- **past_due**: Payment failed, subscription at risk
### Request Example
```json
{
"amount": 29.99,
"currency": "USD",
"transaction_id": "pay_1234567890",
"visitor_id": "abc123",
"mode": "subscription",
"event": "purchase"
}
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message.
- **transaction_id** (string) - The recorded transaction ID.
#### Response Example
```json
{
"message": "Payment recorded successfully",
"transaction_id": "pay_1234567890"
}
```
### Rate Limits
- **100 requests per second** per API key
- Rate limit headers in response: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
```
--------------------------------
### Track Server-Side Events with Client-Passed Visitor ID (JavaScript)
Source: https://www.supalytics.co/docs/api/server-side-events
Illustrates passing a visitor ID from the client-side to the server, and then using that ID in a server-side event tracked by Supalytics. This is useful when the user is actively on the site.
```javascript
// Client-side: send visitor ID with your API request
const visitorId = window.supalytics?.visitorId;
await fetch("/api/upgrade", {
method: "POST",
body: JSON.stringify({
plan: "pro",
visitorId, // pass to your backend
}),
});
```
```javascript
// Server-side: use the passed visitor ID
export async function POST(req) {
const { plan, visitorId } = await req.json();
// Your upgrade logic...
await fetch("https://api.supalytics.co/v1/events", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUPALYTICS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "upgraded",
visitor_id: visitorId,
metadata: { plan },
}),
});
}
```
--------------------------------
### Rate Limits
Source: https://www.supalytics.co/docs/api
The Supalytics API enforces rate limits to ensure fair usage and stability. Currently, the limit is 100 requests per second per API key.
```APIDOC
## Rate Limits
100 requests per second per API key.
```
--------------------------------
### POST /v1/analytics - Query Analytics Data
Source: https://www.supalytics.co/docs/api/server-side-events
Query your analytics data programmatically using this endpoint.
```APIDOC
## POST /v1/analytics
### Description
Query your analytics data programmatically.
### Method
POST
### Endpoint
`https://api.supalytics.co/v1/analytics`
```
--------------------------------
### Capture Supalytics Visitor ID at Checkout (Client-Side)
Source: https://www.supalytics.co/docs/revenue-attribution
Client-side code to capture the Supalytics visitor ID specifically at the checkout stage. This method is suitable for direct purchase scenarios but may lead to less accurate attribution for conversions that occur after the initial browsing session.
```javascript
const visitorId = window.supalytics?.visitorId || null;
await fetch('/api/create-checkout', {
method: 'POST',
body: JSON.stringify({
supalyticsVisitorId: visitorId,
// ... checkout data
}),
});
```
--------------------------------
### Filter by referrer and country
Source: https://www.supalytics.co/docs/api/analytics
Filters analytics data to include only traffic from specific referrers and countries.
```APIDOC
## Filter by referrer and country
### Description
Retrieve analytics data, such as pageviews and visitors, filtered by specific referrers and countries.
### Method
POST
### Endpoint
/analytics/query
### Request Body
- **metrics** (array) - Required - A list of metrics to retrieve. E.g., `["pageviews", "visitors"]`.
- **dimensions** (array) - Required - A list of dimensions to group the metrics by. E.g., `["page"]`.
- **filters** (array) - Required - A list of filter conditions. Each condition is an array with three elements: `[operator, field, value]`.
- Example filter for referrer: `["is", "referrer", "twitter.com"]`
- Example filter for country: `["is", "country", "US"]`
### Request Example
```json
{
"metrics": ["pageviews", "visitors"],
"dimensions": ["page"],
"filters": [
["is", "referrer", "twitter.com"],
["is", "country", "US"]
]
}
```
### Response
#### Success Response (200)
- **page** (string) - The page URL.
- **pageviews** (integer) - The number of pageviews.
- **visitors** (integer) - The number of visitors.
#### Response Example
```json
{
"data": [
{
"page": "/homepage",
"pageviews": 5000,
"visitors": 2500
},
{
"page": "/products",
"pageviews": 3000,
"visitors": 1500
}
]
}
```
```
--------------------------------
### Analytics API - Daily Pageview Trend (JSON)
Source: https://www.supalytics.co/docs/api/analytics
This JSON request body illustrates how to fetch daily pageview trends over a specified date range. It requests 'pageviews' and 'visitors' metrics, groups them by 'date' dimension, and sets the date range to the last 30 days.
```json
{
"metrics": ["pageviews", "visitors"],
"dimensions": ["date"],
"date_range": "30d"
}
```
--------------------------------
### Store Supalytics Visitor ID with User Record (Server-Side)
Source: https://www.supalytics.co/docs/revenue-attribution
Stores the captured Supalytics visitor ID alongside other user information in the database. This server-side operation assumes the visitor ID has been received from the client-side and is associated with a user's record.
```javascript
await db.user.create({
data: {
email: signupData.email,
supalyticsVisitorId: signupData.supalyticsVisitorId,
// ...
},
});
```
--------------------------------
### Resume Tracking via Browser Console (JavaScript)
Source: https://www.supalytics.co/docs/block-your-traffic
To stop blocking your own traffic and resume analytics tracking for the current browser, use the `supalytics.unblockTracking()` JavaScript function in the browser console.
```javascript
supalytics.unblockTracking()
```
--------------------------------
### Block Tracking via Browser Console (JavaScript)
Source: https://www.supalytics.co/docs/block-your-traffic
Use the `supalytics.blockTrackingForMe()` JavaScript function in the browser console to prevent tracking for the current browser. This method offers per-browser control and does not block other devices on the network.
```javascript
supalytics.blockTrackingForMe()
```
--------------------------------
### Self-Opt-Out Tracking Script
Source: https://www.supalytics.co/docs/features
This JavaScript snippet demonstrates how to implement self-opt-out functionality for the Supalytics tracking script. This allows users to block tracking for themselves, ensuring compliance with privacy regulations. No external libraries are required.
```javascript
supalytics.blockTrackingForMe();
```
--------------------------------
### Track Events with Server-Side API
Source: https://www.supalytics.co/docs/custom-events
Send event data from your backend to Supalytics using the Server-Side Events API. This is ideal for tracking events originating from server code, webhooks, or cron jobs. Requires an API key for authentication.
```javascript
await fetch("https://api.supalytics.co/v1/events", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUPALYTICS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "subscription_created",
visitor_id: user.visitorId,
metadata: { plan: "pro" },
}),
});
```
--------------------------------
### Update Stripe Subscription Metadata
Source: https://www.supalytics.co/docs/backfill-existing-subscriptions
This JavaScript code snippet updates the metadata of active Stripe subscriptions for a user. It associates the captured Supalytics visitor ID with each relevant subscription, ensuring future renewals are correctly attributed.
```javascript
// After storing the visitor ID, update Stripe subscriptions
if (supalyticsVisitorId && !existingUser.supalyticsVisitorId) {
// Get user's active subscriptions from your database
const subscriptions = await db.subscription.findMany({
where: {
userId: user.id,
status: { in: ['active', 'trialing'] },
},
});
for (const subscription of subscriptions) {
await stripe.subscriptions.update(subscription.stripeSubscriptionId, {
metadata: {
supalytics_visitor_id: supalyticsVisitorId,
},
});
}
}
```
--------------------------------
### POST /v1/events - Track Server-Side Events
Source: https://www.supalytics.co/docs/api/server-side-events
Track events from your server when client-side tracking isn't available. This endpoint allows you to send event data directly from your backend to Supalytics.
```APIDOC
## POST /v1/events
### Description
Track events from your server when client-side tracking isn't available.
### Method
POST
### Endpoint
`https://api.supalytics.co/v1/events`
### Parameters
#### Request Body
- **name** (string) - Required - Event name. Lowercase, numbers, underscores, hyphens. Max 64 chars.
- **visitor_id** (string) - Optional - Visitor ID for attribution.
- **metadata** (object) - Optional - Custom data. Max 10 keys, values max 255 chars.
### Request Example
```json
{
"name": "subscription_created",
"visitor_id": "abc123",
"metadata": {
"plan": "pro",
"amount": 29
}
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the event was tracked successfully.
#### Response Example
```json
{
"success": true
}
```
### Visitor ID Options
**Option 1: Use stored visitor ID**
If you store visitor IDs when users sign up, use that ID.
**Option 2: Pass from client**
If the user is currently on your site, pass the visitor ID from client to server.
**Option 3: No visitor ID**
For backend-only events (cron jobs, webhooks without user context), omit the visitor ID.
### Rate Limits
- 100 requests per second per API key
- Rate limit headers in response: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
```
--------------------------------
### Send Supalytics Visitor ID to Server for Stripe Customer Metadata (Client-Side)
Source: https://www.supalytics.co/docs/revenue-attribution
Client-side code to capture the Supalytics visitor ID and send it to a server endpoint. This is part of an alternative method to store the visitor ID directly within Stripe customer metadata instead of a local database.
```javascript
const visitorId = window.supalytics?.visitorId || null;
await fetch('/api/signup', {
method: 'POST',
body: JSON.stringify({ email: userEmail, visitorId }),
});
```