# Create Events
Source: https://docs.trench.dev/api-reference/events-create
post /events
Use `track`, `identify`, and `group` to send events to Trench.
This endpoint requires your [public API key](/api-reference/overview#authentication).
Trench is fully compatible with the [Segment Spec](https://segment.com/docs/spec/) schema.
You can use the `track`, `identify`, and `group` methods to send events to Trench via the `/events` endpoint.
# Get Events
Source: https://docs.trench.dev/api-reference/events-get
get /events
Get events based on a query
This endpoint requires your [private API key](/api-reference/overview#authentication).
# API Overview
Source: https://docs.trench.dev/api-reference/overview
Overview of the Trench API
## Trench API Overview
The Trench API provides a comprehensive suite of endpoints to interact with the Trench platform. It is designed to be fully compatible with the [Segment Spec](https://segment.com/docs/spec/) schema, allowing you to seamlessly integrate and send events using familiar methods such as `track`, `identify`, and `group`.
### Events
The `/events` endpoint allows you to create and retrieve events using the `track`, `identify`, and `group` methods. These methods enable you to send detailed event data to Trench, including user interactions, identity information, and group associations. For more information, refer to the [Create Events](./events-create) and the [Get Events](./events-get) documentation.
### Queries
The `/queries` endpoint enables you to execute queries against the Trench platform. This allows you to retrieve and analyze data based on the events and interactions recorded. For more details, refer to the [Execute Queries](./queries-execute) documentation.
### Webhooks
The Trench API also supports webhooks, which allow you to receive real-time notifications about specific events or changes within the platform. You can create, retrieve, and delete webhooks using the respective endpoints. For more information, refer to the following documentation:
* [Get Webhooks](./webhooks-get)
* [Create Webhooks](./webhooks-create)
* [Delete Webhooks](./webhooks-delete)
### Authentication
The Trench API uses bearer token authentication to secure access to its endpoints. You will be issued a **public api key** and a **private api key** to use when making requests. The public key is used only in the [Events](./events-create) endpoint to send data to Trench. It is safe to expose this key to the public internet.
The private key is used on all other endpoints and should be kept secret.
**Note:** Do not use your private API key on public endpoints. Always use your public API key to
avoid unauthorized access and misuse.
# Execute Queries
Source: https://docs.trench.dev/api-reference/queries-execute
post /queries
Overview of the Trench API
This endpoint requires your [private API key](/api-reference/overview#authentication).
This endpoint allows you to execute read-only queries against your Trench data.
The endpoint will proxy the request to the underlying ClickHouse database.
For more information about ClickHouse's query language, see the [official documentation](https://clickhouse.com/docs/en/sql-reference).
## Examples
### Quering event properties, context, and traits
To query a specific nested property, you can use the `JSONExtract` function. For example, to query all events where the `totalAccounts` property is greater than 3, you can use the following query:
```sql theme={null}
SELECT * FROM events WHERE JSONExtract(properties, 'totalAccounts', 'UInt64') > 3
```
Similarly, you can query the context and traits:
```sql theme={null}
SELECT * FROM events WHERE JSONExtract(context, 'country', 'String') = 'Denmark'
```
### Joining identified users with their events
All `identify` calls are sent to the same underlying `events` ClickHouse table, so you can join events with identified users using the `userId` column. For example, to query all events for a user with the ID `user-123`, you can use the following query:
```sql theme={null}
SELECT * FROM events WHERE userId = 'user-123'
```
To get the tracking events and the user's most recently provided email, you can join the `track` and `identify` event types:
```sql theme={null}
SELECT
i.email,
e.*
FROM
events e
LEFT JOIN
(SELECT userId, type, JSONExtract(traits, 'email', 'String') AS email FROM events) i
ON
e.userId = i.userId
WHERE
e.type = 'track'
AND i.type = 'identify';
```
# Create Webhook
Source: https://docs.trench.dev/api-reference/webhooks-create
post /webhooks
Create a new webhook.
This endpoint requires your [private API key](/api-reference/overview#authentication).
Once a webhook is created, events will be sent to it based on the criteria specified in the webhook.
The data sent follows the [Event schema](/api-reference/events-get) and is sent as a JSON array in the POST request in the `data` field. Below is an example request body:
```json theme={null}
{
"data": [
{
"uuid": "b99b40c5-e306-4351-9f1d-9a13bb9e8bd1",
"type": "track",
"event": "ConnectedAccount",
"userId": "123e4567-e89b-12d3-a456-426614174000",
"properties": {
"totalAccounts": 4
},
"timestamp": "2024-10-21T21:32:17.000Z",
"parsedAt": "2024-10-21T21:32:23.194Z"
}
]
}
```
# Delete Webhook
Source: https://docs.trench.dev/api-reference/webhooks-delete
delete /webhooks/{uuid}
Delete a webhook.
This endpoint requires your [private API key](/api-reference/overview#authentication).
# Get Webhooks
Source: https://docs.trench.dev/api-reference/webhooks-get
get /webhooks
Get all webhooks under your account.
This endpoint requires your [private API key](/api-reference/overview#authentication).
# JavaScript Client
Source: https://docs.trench.dev/client
Documentation for the Trench JavaScript client
## Overview
`trench-js` is a client library for both web and Node.js environments that allows you to send events to any Trench instance. This library is designed to be easy to use and integrate into your existing projects. The library is built on top of [Analytics](https://github.com/DavidWells/analytics) and supports all of its [methods](https://github.com/DavidWells/analytics#usage). It can be installed via a package manager or via a CDN script tag.
## Installation via package manager
Install `trench-js` using your preferred package manager:
```bash theme={null}
npm install trench-js
```
You can now initialize the client with your Trench instance URL and public API key:
```ts theme={null}
import Trench from 'trench-js'
const trench = new Trench({
serverUrl: 'your-server-url',
publicApiKey: 'your-public-api-key',
})
```
For example, you can identify a user like this:
```ts theme={null}
trench.identify('user-id', {
email: 'test@example.com',
})
```
And track an event like this:
```ts theme={null}
trench.track('test-event', {
test: 'test-value',
})
```
Or to record a trigger page view:
```ts theme={null}
trench.page()
```
## Installation via CDN script tag
Alternatively, you can use the CDN version:
```html theme={null}
```
This will automatically add the `trench` object to the global scope and you can start tracking events automatically as `autoCaptureEvents` is set to `true` by default.
# Cloud Quickstart
Source: https://docs.trench.dev/cloud-quickstart
Send your first event to Trench Cloud
In this guide, we'll walk you through the process of sending your first event and reading it back using the Trench Cloud API.
The example uses the [Trench JavaScript client](https://www.npmjs.com/package/trench-js), but the same can be achieved by calling the [Events API](https://docs.trench.dev/api-reference/events-create) directly.
## Getting Started
To get started with Trench Cloud, you need to sign up at [app.trench.dev](https://app.trench.dev?utm_campaign=cloud-quickstart). Then, locate the necessary credentials in the `API Keys` tab.
Next, install the Trench JavaScript client using your favorite package manager:
```bash theme={null}
npm install trench-js
```
Alternatively, you can use the hosted version via the script tag below and skip the **Initialize the Client** step:
```html theme={null}
```
After installing the client, you need to initialize it with your API key. Replace `YOUR_API_KEY` and `YOUR_SERVER_URL` with the actual API key and server URL you received:
```javascript theme={null}
import Trench from 'trench-js'
const trench = new Trench({
publicApiKey: 'YOUR_PUBLIC_API_KEY',
serverUrl: 'YOUR_SERVER_URL'
});
```
Optionally, you can identify a user with the `identify` method:
```javascript theme={null}
trench.identify('user-id', {
email: 'test@example.com',
// Add any other traits you want to associate with the user
})
```
Now you can send a sample event to Trench Cloud. Here is an example of how to send an event:
```javascript theme={null}
trench.track("Test Event");
```
This will send an event with the name `Test Event`.
You can verify that the event was received by opening the `Events` tab in the Trench Cloud dashboard.
## Going Further
Now that you've sent your first event, you can learn more about the many things you can do with Trench.
# Contributing to Trench
Source: https://docs.trench.dev/contributing
Trench is an open source project and we welcome contributions from the community.
## Developing and deploying the backend locally
We welcome contributions to improve the backend. Before starting, we recommend opening an issue for discussion to ensure your idea aligns with the project's goals.
### Backend Setup Guide
1. Fork the repository and clone it to your local machine.
2. Navigate to the `apps/trench` directory and copy the `.env.example` file to `.env`:
```bash theme={null}
cp .env.example .env
```
3. Make sure you have the following prerequisites installed:
* [Docker](https://www.docker.com/products/docker-desktop/)
* [Docker Compose](https://docs.docker.com/compose/install/)
* [Node.js](https://nodejs.org/en/download/)
* [pnpm](https://pnpm.io/installation)
4. Start the local development environment:
```bash theme={null}
pnpm install && pnpm dev
```
5. The backend should now be running locally on `http://localhost:4000`.
6. Create a new branch for your changes.
7. Develop your feature or fix and write tests for it. Specifically, writing an end to end test for your feature is highly recommended.
8. Ensure all tests pass by running `pnpm test:e2e` (you will need to be running the dev server locally on port 4000 with HTTP for this to work)
9. Commit your changes and push them to your forked repository.
10. Submit a pull request to the main repository.
## Improving the Documentation
Good documentation is crucial and requires significant time and effort to create and maintain. All our documentation is written in Markdown to make it easy for contributors.
### Documentation Setup Guide
1. Fork the repository and clone it to your local machine.
2. Go to the `apps/docs` directory.
3. Make your edits in the relevant `.mdx` files. Optionally, install and start [Mintlify](https://mintlify.com/) to build the documentation site locally.
4. Commit your changes and push them to your forked repository.
5. Submit a pull request to the main repository.
## Reporting Issues
You can open an issue to report bugs or suggest new features.
### Reporting Bugs
Clearly describe the bug, including steps to reproduce it, what happened, and what you expected to happen. Also, include the browser version, OS, and other relevant software versions (npm, Node.js, etc.) when applicable.
### Suggesting Features
Describe the proposed feature, its functionality, why it is useful, and how users should use it. Provide as much information as possible to facilitate discussion, assessment, and implementation. If you are unsure about any aspect of the feature, feel free to leave it open for discussion.
## Submitting Pull Requests
Pull requests are highly appreciated. If you plan to propose significant changes, please open an issue for discussion first to ensure your PR will be accepted before you invest time in coding it.
### Forking the Repository
1. Fork the repository and clone it to your local machine.
2. Create a branch for your proposed bug fix or new feature. Avoid working directly on the main branch.
### Making Changes
1. Implement your bug fix or feature, write tests for it, and ensure all tests pass.
2. Commit your changes and push your bug fix/feature branch to your forked repository.
3. Submit a pull request to the main branch of the upstream repository (the repository you originally forked).
# Grafana
Source: https://docs.trench.dev/guides/grafana
Step-by-step guide to setup Trench with Grafana dashboard
# Setting up Grafana with Trench
This guide will walk you through setting up Grafana with Trench to visualize your analytics data.
## Prerequisites
* Docker installed
* Trench running locally follow [Self-host Quickstart](/quickstart)
## Setup Steps
Run the following command to start Grafana. This will make Grafana available at [http://localhost:3001](http://localhost:3001) and connect it to your Trench installation.
```bash theme={null}
docker run -d \
--name grafana-trench \
--network trench_app-network \
-p 3001:3000 \
grafana/grafana:latest
```
* Username: `admin`
* Password: `admin`
Go to plugins section and install the ClickHouse plugin.
1. Go to Data Sources section and click on `Add data source`.
2. Select `ClickHouse` as the data source.
3. Configure the data source with these settings:
* Host: `clickhouse`
* Port: `8123`
* Protocol: `http`
* Username: `user`
* Password: `password`
You can import the pre-built dashboard using the JSON configuration provided. Download the [JSON configuration](https://raw.githubusercontent.com/FrigadeHQ/trench/refs/heads/main/apps/docs/json/grafana-dashboard.json) and import it into Grafana.
The Dashboard includes:
* Unique pageviews over time
* Time series visualization
* 6-hour time window by default
Here's an example of sending pageview data:
```bash theme={null}
curl --location 'http://localhost:4000/events' \
--header 'Authorization: Bearer public-d613be4e-di03-4b02-9058-70aa4j04ff28' \
--header 'Content-Type: application/json' \
--data '{
"events": [
{
"userId": "550e8400-e29b-41d4-a716-4466554400",
"type": "track",
"event": "$pageview",
"properties": {
"totalAccounts": 4,
"country": "Denmark"
}
}
]
}'
```
New pageviews should be visible in the dashboard.
#### Next Steps
* Customize the dashboard based on your needs
* Add more panels for different metrics
* Set up alerts
# Introduction
Source: https://docs.trench.dev/introduction
Open source infrastructure for tracking events
Trench is an event tracking system built on top of Apache Kafka and ClickHouse. It can handle large event volumes and provides real-time analytics. Our team built Trench to scale up the real-time event tracking pipeline at Frigade.
## Features
* 🤝 Compliant with the Segment API (Track, Group, Identify)
* 🐳 Deploy quickly with a single production-ready Docker image
* 💻 Process thousands of events per second on a single node
* ⚡ Query data in real-time
* 🔗 Connect data to other destinations with webhooks
* 👥 Open-source and MIT Licensed
## Getting Started
***
# Self-host Quickstart
Source: https://docs.trench.dev/quickstart
Get set up with Trench in less than 5 minutes
The only prerequisite for Trench is a system that has Docker and Docker Compose installed [see installation guide](https://docs.docker.com/compose/install/). We recommend having at least 4GB of RAM and 4 CPU cores for optimal performance if you're running a production environment.
After installing Docker, you can start the local development server by running the following commands:
```sh theme={null}
git clone https://github.com/frigadehq/trench.git
cd trench/apps/trench
cp .env.example .env
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up --build --force-recreate --renew-anon-volumes
```
The above command will start the Trench server that includes a local ClickHouse and Kafka instance on `http://localhost:4000`. You can update the `.env` to change any of the configuration options.
You can find and update the default public and private API key in the `.env` file. Using your public API key, you can send a sample event to Trench as such:
```bash theme={null}
curl -i -X POST \
-H "Authorization: Bearer public-d613be4e-di03-4b02-9058-70aa4j04ff28" \
-H "Content-Type: application/json" \
-d \
'{
"events": [
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"type": "track",
"event": "ConnectedAccount",
"properties": {
"totalAccounts": 4,
"country": "Denmark"
}
}]
}' \
'http://localhost:4000/events'
```
You can query events using the `/events` endpoint (see [API reference](/api-reference/events-get) for more details).
You can also query events directly from your local Trench server. For example, to query events of type `ConnectedAccount`, you can use the following URL:
```bash theme={null}
curl -i -X GET \
-H "Authorization: Bearer private-d613be4e-di03-4b02-9058-70aa4j04ff28" \
'http://localhost:4000/events?event=ConnectedAccount'
```
This will return a JSON response with the event that was just sent:
```json theme={null}
{
"results": [
{
"uuid": "25f7c712-dd86-4db0-89a8-d07d11b73e57",
"type": "track",
"event": "ConnectedAccount",
"userId": "550e8400-e29b-41d4-a716-446655440000",
"properties": {
"totalAccounts": 4,
"country": "Denmark"
},
"timestamp": "2024-10-22T19:34:56.000Z",
"parsedAt": "2024-10-22T19:34:59.530Z"
}
],
"limit": 1000,
"offset": 0,
"total": 1
}
```
Use the queries endpoint to analyze your data. Example:
```bash theme={null}
curl -i -X POST \
-H "Authorization: Bearer private-d613be4e-di03-4b02-9058-70aa4j04ff28" \
-H "Content-Type: application/json" \
-d \
'{
"queries": [
"SELECT COUNT(*) FROM events WHERE userId = '550e8400-e29b-41d4-a716-446655440000'"
]
}' \
'http://localhost:4000/queries'
```
Sample query result:
```json theme={null}
{
"results": [
{
"count": 5
}
],
"limit": 0,
"offset": 0,
"total": 1
}
```
## Going Further
While the above steps are a great starting point, the following video tutorial exemplifies the many things you can do with Trench. In this video, we build a mini version of Google Analytics using Trench and Grafana:
## Related Resources