Ir al contenido
HitKeep
Seleccionar idioma
Seleccionar tema
GitHub
Empezar gratis en Cloud

Custom Event Tracking in HitKeep

Esta página aún no está disponible en tu idioma.

Your tracking script captures page views automatically, but you need to measure specific interactions: a purchase, a video play, a form submission. HitKeep’s custom event API lets you record any named action from the browser or from your server.

If you only need baseline browser interactions such as outbound links, file downloads, or form submits, start with Automatic Events. The default tracker already emits outbound_click, file_download, and form_submit without manual window.hk.event() calls.

For how hk.js sends payloads, retries failed delivery, handles SPA navigation, and limits browser storage, see Tracker Architecture.

Use specific event names that describe the business action. Keep properties small, structured, and free of secrets, raw prompts, form field values, and access tokens.

Workflow Example event names Typical path
Signup signup_started, signup_completed Browser or server-side event
Leads demo_requested, contact_form_submitted Browser or server-side event
Downloads whitepaper_downloaded, release_downloaded Browser event when automatic file_download is not specific enough
Ecommerce view_item, add_to_cart, begin_checkout, purchase Browser or server-side event
Assistants assistant.chat_started, assistant.message_sent, assistant.goal_assisted Browser or server-side event

For canonical event, export, storage, and runtime facts, see Facts and Limits.

These examples require the HitKeep 2.18.0 tracker or later. With a 2.17 tracker, use the JavaScript event API.

For a script-tag install, add data-enable-declarative-events="true" to the existing hk.js tag. Keep the script URL and other attributes from your site’s snippet. To generate the attribute from the dashboard, go to Site settings → Tracking → Script tag → Advanced options, turn on Track marked clicks and form submissions, then copy the updated snippet into your site. With the npm tracker, set declarativeEvents: true in your existing init() call.

<script async src="https://your-hitkeep.example/hk.js" data-enable-declarative-events="true"></script>
<a href="/pricing/" data-hk-event="pricing_clicked">See pricing</a>
<form action="/contact" method="post" data-hitkeep-event="contact_form_submitted">
<button type="submit">Send request</button>
</form>

Use either data-hk-event or data-hitkeep-event on the element. Choose a fixed name of 1–64 ASCII characters that starts with a letter or digit and uses only letters, digits, hyphens, and underscores. The tracker skips invalid names. It sends valid names through the regular browser event endpoint without adding properties from the element or reading form fields.

A form event fires on submit. If the submit button has its own marker, that name takes precedence over the form’s name. Use an event from your application’s success callback or backend when you need to measure a confirmed outcome.

Declarative events are off by default. These attributes still suppress built-in automatic events on marked links and forms, including on 2.17. With opt-in, valid markers produce named events even if the corresponding built-in events are disabled. Remove any manual analytics call that would also send an event for the same action.

Open your site in the dashboard and check Events for pricing_clicked or contact_form_submitted after testing the corresponding action.

The hk.js tracking snippet exposes window.hk.event():

<script>
// Record a named event with optional properties
window.hk?.event?.('signup', { plan: 'pro' });
</script>

Call this anywhere in your page JavaScript: button click handlers, form submit callbacks, pricing interactions, onboarding steps, or other product-specific actions.

In React, Vue, Angular, or Astro projects, the typed @hitkeep/tracker npm package exposes the same event API as an importable, compiler-checked track() function.

<button onclick="window.hk?.event?.('cta_clicked', { location: 'hero' })">
Get Started
</button>

Record page_not_found where your server renders its 404 template or where your router finishes navigating to a missing route. A server-rendered error page can return HTTP 404. A single-page app can show a missing route after loading an HTML shell with HTTP 200. The event counts views of the instrumented page in either case. HitKeep does not look up the HTTP status.

Use one of the following integrations for a given view. These examples assume your tracked pathnames are public. Set Referrer-Policy: no-referrer on your site’s responses so same-origin links can be counted without passing their source URL. If a referring site provides a URL beyond its origin, the examples skip the event. Normal pageviews still follow the tracker’s existing collection rules.

Add the listener only to the template your server returns for a missing page. Keep the existing script URL and options. The referrerpolicy attribute keeps the current URL out of the request for hk.js. The window’s load event waits for the async tracker. Include the listener in your site’s approved JavaScript if your content security policy restricts inline scripts.

<script>
window.addEventListener('load', () => {
const referrer = document.referrer;
if (!referrer || referrer === `${new URL(referrer).origin}/`) {
window.hk?.event?.('page_not_found');
}
}, { once: true });
</script>
<script async src="https://your-hitkeep.example.com/hk.js" referrerpolicy="no-referrer"></script>

In your browser entry point, give the catch-all route a name and register one afterEach hook before mounting the router. Use your existing app, routes, components and tracker configuration. The hook handles the initial route, skips aborted navigations and query or fragment changes on the same missing pathname, and counts a visit to a different missing pathname or a return after leaving.

import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import { init, track } from '@hitkeep/tracker';
import App from './App.vue';
import Home from './Home.vue';
import NotFound from './NotFound.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound }
]
});
init({ host: 'https://your-hitkeep.example.com' });
const referrer = document.referrer;
const hasPublicReferrer = !referrer || referrer === `${new URL(referrer).origin}/`;
router.afterEach((to, from, failure) => {
if (failure || to.name !== 'not-found' || !hasPublicReferrer) return;
if (from.name === to.name && from.path === to.path) return;
track('page_not_found');
});
createApp(App).use(router).mount('#app');
  1. Open your site’s Events report and note the count for page_not_found in the current date range.
  2. Visit a public missing page directly with tracking enabled. An ordinary pageview and one named event should arrive. In an SPA, visit a valid route, then navigate back to the missing route. That return adds one more event.
  3. Refresh Events and select page_not_found. Check the count increased by the number of instrumented views. It has no custom property keys. A valid route adds no such event.

The examples check the incoming document.referrer before calling the tracker. The event includes the current pathname and the previous SPA URL or incoming referrer, with query strings and fragments removed. It also includes the session ID, user agent and tracker source/version. The examples add no custom properties. Keep paths containing email addresses, tokens or customer identifiers outside the tracked site. For routes that may contain private data, serve an untracked document. The normal pageview can still include referrer context and recognized campaign parameters when the example suppresses the named event. Set the referrer policy on pages that link from sensitive URLs to control the document.referrer received by the missing page.

Send events from your backend when the server confirms the action or when you need to preserve a historical timestamp. Common examples include purchase confirmations, webhook processing, trial starts, account upgrades, and replayed events from logs.

Use the trusted server-side event API with an API client token:

The url field should reflect the page where the event conceptually occurred. HitKeep uses it for site resolution and session context.

Events become useful when combined with Goals. Create an event-based goal to count conversions:

API reference:

The goal value must match the event name exactly. Once created, the dashboard shows conversion counts and timeseries data for that event.

If you are instrumenting an on-site chatbot, keep the event names predictable so the dedicated AI chatbot dashboard can aggregate them automatically.

Recommended event names:

  • assistant.chat_started
  • assistant.message_sent
  • assistant.response_rendered
  • assistant.citation_clicked
  • assistant.handoff_requested
  • assistant.goal_assisted

Recommended properties include:

  • bot_id, provider, model, surface
  • conversation_id, message_index, intent
  • response_ms, tool_count, citation_count
  • goal_name, goal_value

Use structured metadata rather than raw prompt bodies whenever possible. That keeps storage leaner and avoids collecting sensitive conversation text by default.

For a complete walkthrough, see AI Chatbot Analytics.

  1. Trigger an HTML event, call the browser event API, or send an event from your server.
  2. Open your site in the dashboard.
  3. Navigate to Events to inspect event counts, property breakdowns, and audience panels for pages, sources, devices, countries, city, provider, and ASN context.
  4. Navigate to Goals and create a new Event goal using the event name.
  5. The goal will appear in KPIs, charts, and the Goals timeseries.

City, provider, and ASN are derived from transient IP metadata. They are not custom event properties, and HitKeep does not store raw visitor IP addresses with the event.

Custom events share the ingest endpoint’s rate limiter. The default is 20 requests/sec per IP with a burst of 40. Adjust via configuration if sending high-volume server-side events from a single IP:

Flag Env Variable Default
--ingest-rate-limit HITKEEP_INGEST_RATE_LIMIT 20.0
--ingest-burst HITKEEP_INGEST_BURST 40

See Configuration Reference for all options.

Need event streaming or real-time webhooks on top of custom events? Start with HitKeep Cloud →