Monitoring frontend applications with a log endpoint
Understanding what your users are doing on your website or webapp can be a black box. You deploy your app and assume your users use it as you expect. A tool like TRCKRSPACE (opens in a new tab) can help you understand how users use your and help to make data-driven product decisions.
While you can instantly start collecting data directly in the frontend as soon as you sign up, this requires you to publish your project_api_key
in your frontend.
To help you avoid doing this, this guide shows you how you can create a log endpoint in your backend to be able to track events in your frontend, allowing you to restrict your usage events to authenticated users.
Guide
We will now show you an example of a simple Flask endpoint and how you can use your frontend.
Endpoint
To begin the endpoint, we first need to get our project_api_key
from
the TRCKRSPACE App (opens in a new tab). You can find this by clicking
"Manage Project" on the project of your choice.
from http import HTTPStatus
from flask import Flask
app = Flask(__name__)
project_api_key = '{insert your API key here}'
@app.route("/log")
def log_event():
event = request.get_json()
return "Hello, World!", HTTPStatus.OK
First, we will begin by checking the event passed to the endpoint. TRCKRSPACE requires order
and values
in each event. This makes it easier to filter events later when retrieving them. If order
or values
is not provided, we will reject the request with a 400, Bad Request
.
from http import HTTPStatus
from flask import Flask
app = Flask(__name__)
project_api_key = '{insert your API key here}'
@app.route("/log")
def log_event():
usage_event = request.get_json()
if 'order' not in usage_event:
return {'message': 'order is required'}, HTTPStatus.BAD_REQUEST
if 'values' not in usage_event:
return {'message': 'values is required'}, HTTPStatus.BAD_REQUEST
return "Hello, World!", HTTPStatus.OK
We are now ready to pass the event to TRCKRSPACE. We can this by making a post request with our project_api_key
and the event dictionary. If we get a non successful response, we exit early. However, you can modify this logic to fit your application, such as continuing to process the request and logging an error state to your server.
from http import HTTPStatus
from flask import Flask
import requests
app = Flask(__name__)
project_api_key = '{insert your API key here}'
@app.route("/log")
def log_event():
usage_event = request.get_json()
if 'order' not in usage_event:
return {'message': 'order is required'}, HTTPStatus.BAD_REQUEST
if 'values' not in usage_event:
return {'message': 'values is required'}, HTTPStatus.BAD_REQUEST
url = 'https://api.trckrspace.com/usage'
headers = {
'X-Api-Key': project_api_key,
'Accept': 'application/json'
}
resp = requests.post(url, headers=headers, json=usage_event)
# error out if not a 200
assert resp.status_code == HTTPStatus.OK
return "Hello, World!", HTTPStatus.OK
And we are ready to try it out, set up the server:
flask --app app run
And hit the endpoint:
curl http://127.0.0.1:5000/log --data '{"order": ["key"], "values" {"key": "value"}}'
>> Hello, World!
Integrating into your UI
As an example, we will use React to create a simple app with a button:
const url = 'http://127.0.0.1:5000/log';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<button>
Log event
</button>
);
After clicking the butotn, we will send an event to the log endpoint. The endpoint requires that we send event
and category
, but after that, we are free to add any additional valid JSON data types.
const url = 'http://127.0.0.1:5000/log';
const root = ReactDOM.createRoot(document.getElementById('root'));
const logEvent = (event) => {
fetch(url, {
method: "POST",
body: JSON.stringify(event),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
}
root.render(
<button
onClick={
() => logEvent(
{
order: ['category', 'event', 'user'],
values: {
category: 'button-click',
event: 'log-button-clicked',
app: 'my-test-app',
user: 'some-user'
}
}
)
}
>
Log event
</button>
);
You are now ready to run your app and click the button we've created.
yarn start
Viewing your event
After clicking your button you can view the event it created. We will do this via
curl
but you can use any http client. We first need to set some environment
variables:
USER_API_KEY
you can find this in theAPI Key
section of the TRCKRSPACE App (opens in a new tab)startDt
an iso format date that is the minimum date range to search for eventsendDt
an iso format date that is the maximum date range to search for events
For example:
export USER_API_KEY={your api key}
export startDt=2023-09-01
export endDt=2023-09-01
curl 'https://api.trckrspace.com/usage?startDt=${startDt}&endDt={endDt}' \
-X 'GET' \
-H 'Accept: application/json, text/plain, */*' \
-H 'Authorization: Bearer ${USER_API_KEY}' \
>> {
"status": "OK",
"result": [
{
"category": "button-click",
"event": "log-button-clicked",
"app": "my-test-app",
"user": "some-user",
"dateTime": "2023-09-01T11:08:27.632289"
}
]
}