MB default). Keep batches under 1MB for optimal performance.
The endpoint expects a JSON-formatted request body. Query parameters are not supported; all data must be transmitted in the request payload.
| Field | Type | Required | Description |
|---|
events | Array<Object> | Yes | A collection of analytics event objects. Must be a valid JavaScript array. |
timestamp | string | number | No | Optional ISO 8601 string or Unix timestamp representing when the batch was generated. Reserved for client-side event ordering. |
Event Object Schema
While the route only strictly validates that events is an array, each event object should follow a consistent structure to ensure compatibility with logging and downstream analytics pipelines:
type (string, required): The category or identifier of the event (e.g., "page_view", "search_query", "api_call").
payload (object, optional): Additional metadata, context, or dimensions associated with the event.
userId (string, optional): Identifier for the user triggering the event.
sessionId (string, optional): Session identifier for grouping related interactions.
Example Request Body
{
"timestamp": "2024-05-20T14:32:00Z",
"events": [
{
"type": "page_view",
"payload": { "url": "/docs/api-reference", "referrer": "https://google.com" }
},
{
"type": "search_query",
"payload": { "query": "rate limiting", "results_count": 12 }
}
]
}
The endpoint returns standardized JSON responses. All responses include a Content-Type: application/json header.
Success Response (200 OK)
Returned when the payload is valid and events are successfully parsed and processed.
{
"success": true,
"received": 2
}
success (boolean): Confirms successful ingestion.
received (number): The exact count of events successfully extracted from the events array.
Error Responses
| Status Code | Condition | Response Body |
|---|
400 Bad Request | Missing events field or events is not an array | {"error": "Invalid events"} |
500 Internal Server Error | Unexpected server-side failure during JSON parsing or processing | {"error": "Failed to process events"} |
5. Usage Example
The following curl command demonstrates how to send a batch of analytics events to the endpoint:
curl -X POST https://codcompass.com/api/analytics \
-H "Content-Type: application/json" \
-d '{
"timestamp": "2024-05-20T14:32:00Z",
"events": [
{
"type": "article_read",
"payload": { "slug": "nextjs-api-routes", "duration_ms": 4500 }
},
{
"type": "bookmark_added",
"payload": { "article_id": "art_8832" }
}
]
}'
Expected Output:
{"success": true, "received": 2}
6. Common Pitfalls
- Passing a Single Object Instead of an Array: The route explicitly checks
Array.isArray(events). Sending "events": { "type": "click" } will trigger a 400 error. Always wrap single events in an array, or implement a client-side queue that flushes events in batches.
- Omitting the
type Property: While the current implementation does not strictly validate individual event objects, the type field is required for the internal logging logic (event.type). Events without a type will be logged as undefined, making them impossible to filter or analyze in downstream dashboards.
- Ignoring Network Reliability & Idempotency: Because the endpoint is public and stateless, it does not guarantee exactly-once delivery. In unstable network conditions, clients should implement retry logic with exponential backoff. Additionally, avoid sending large payloads (>1MB) in a single request; chunk events into smaller batches to prevent serverless function timeouts or payload size limits.
The /api/analytics endpoint is designed to operate independently but integrates seamlessly with other platform APIs to enrich event data and manage tracking behavior:
- Session & Authentication APIs: Pair analytics payloads with authenticated user data from session management endpoints to attach
userId, role, or tenant metadata before transmission. This enables accurate user journey mapping across anonymous and authenticated states.
- Feature Flag & Configuration APIs: Use configuration endpoints to dynamically adjust event sampling rates, disable tracking in development environments, or toggle specific event categories without modifying client-side code.
- Webhook & Integration Routing APIs: Forward processed analytics events to third-party services (e.g., PostHog, Mixpanel, or custom data warehouses) using the platform’s webhook routing system. The
/api/analytics route can be extended to trigger these integrations conditionally based on event type or payload content.
This endpoint follows a lightweight, stateless design pattern optimized for Next.js serverless functions. Developers extending the route should ensure database connections are properly managed, sensitive PII is sanitized before logging, and downstream analytics providers are configured to handle the expected event schema.