On this page

Integration guide

Install Keen Analytics

Two minutes, two ways: paste one script tag, or install the keen-analytics package. Either way you get the same tiny tracker, with no cookies and no personal data.

Before you start

You need two values from your dashboard:

  • Site ID: in Settings → Installation. It’s public; it only identifies which site the data belongs to.
  • Collector URL: where the tracker sends data: https://c.getkeen.cc

No account yet? Sign up and add a site first.

Option 1: script tag

The easiest option, for WordPress, Webflow, Shopify, static sites or anything with a <head>. Paste this on every page:

html
<script defer data-site="YOUR_SITE_ID" src="https://c.getkeen.cc/js/a.js"></script>

That’s it. Page views are counted, even in single-page apps, and your page won’t slow down.

Option 2: npm package

For React, Next.js, Vue, Angular, Svelte and other JavaScript apps. No dependencies, TypeScript included, and safe with server-side rendering.

sh
npm install keen-analytics
# or: pnpm add keen-analytics / yarn add keen-analytics

React

Render the component once, near the root of your app. It renders nothing.

tsx
import { KeenAnalytics } from "keen-analytics/react";

export default function App() {
  return (
    <>
      <KeenAnalytics site="YOUR_SITE_ID" host="https://c.getkeen.cc" />
      {/* your app */}
    </>
  );
}

Next.js

With the App Router, add it to app/layout.tsx. Page changes made by the router are counted automatically.

tsx
// app/layout.tsx
import { KeenAnalytics } from "keen-analytics/react";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <KeenAnalytics site="YOUR_SITE_ID" host="https://c.getkeen.cc" />
        {children}
      </body>
    </html>
  );
}

Pages Router: put the same component in pages/_app.tsx.

Vue & Nuxt

ts
// main.ts
import { createApp } from "vue";
import { KeenPlugin } from "keen-analytics/vue";
import App from "./App.vue";

createApp(App)
  .use(KeenPlugin, { site: "YOUR_SITE_ID", host: "https://c.getkeen.cc" })
  .mount("#app");

In components, use inject("keen") (Composition API) or this.$keen (Options API) to send events. With Nuxt, register the plugin in a client-only plugin file (plugins/keen.client.ts).

Angular

ts
// main.ts
import { bootstrapApplication } from "@angular/platform-browser";
import { init } from "keen-analytics";
import { AppComponent } from "./app/app.component";
import { appConfig } from "./app/app.config";

init({ site: "YOUR_SITE_ID", host: "https://c.getkeen.cc" });
bootstrapApplication(AppComponent, appConfig);

Svelte, Astro & others

Any framework: call init once when the app starts in the browser.

ts
import { init } from "keen-analytics";

init({ site: "YOUR_SITE_ID", host: "https://c.getkeen.cc" });

SvelteKit: call it in +layout.svelte inside onMount. Astro: in a <script> in your base layout.

Custom events

Count actions that matter (signups, downloads, button clicks) and use them as goals and funnel steps.

ts
import { track } from "keen-analytics";

track("Signup", { plan: "pro" });

With the script tag, use the global instead, or mark any element without writing JavaScript:

html
<script>keen.track("Signup", { plan: "pro" });</script>

<button data-keen-event="Download">Download the guide</button>
  • Event names: up to 64 letters, digits, spaces or - _ : .
  • Properties: up to 10, with string, number or boolean values.
  • Values that look like emails, phone numbers or card numbers are dropped automatically.
  • Events sent before the script has loaded are queued, not lost.

Revenue attribution

Connect Stripe in Settings → Integrations to see which traffic brings paying customers.

  • Stripe Payment Links (buy.stripe.com) on your pages work automatically.
  • For checkouts you create on your server, follow the Stripe guide in Settings → Integrations.

ref() gives you a short-lived token for the current visit (or null if tracking is blocked). It doesn’t identify anyone.

ts
import { ref } from "keen-analytics";

const token = await ref();

Server-side events

Record conversions that happen on your backend (a completed signup, a trial start) and attribute them to the visit. Create a key in Settings → API, send the visit’s ref() to your server, then:

sh
curl https://c.getkeen.cc/api/v1/events \
  -H "Authorization: Bearer keen_sk_…" \
  -H "Content-Type: application/json" \
  -d '{"name": "trial_started", "ref": "<ref>", "props": {"plan": "pro"}}'

Keep the key on your server: requests from a browser are rejected. The ref is valid for 48 hours.

Bots & AI crawlers

For Next.js, use the guided SDK setup in Settings → Installation. Create an ingestion-only key and run npx keen setup in your website’s app directory. It adds the appropriate proxy/middleware without changing browser tracking. Restart locally, or configure the generated server-only environment values on your host and redeploy.

ts
import { withKeen } from "keen-analytics/next";

// proxy.ts (Next.js 16+) or middleware.ts (Next.js 13–15)
export default withKeen();
export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
};

Already have middleware? Use withKeen(existingHandler) and retain its matcher. Connection status distinguishes setup checks from live website requests. IP verification needs a trusted hosting-specific address resolver; UA claims alone stay unverified. Static exports and upstream cache hits need an edge integration. Version 0.2.0 is source-ready; use the built checkout until it is published to npm.

Open More → Bots & AI crawlers for automated requests, separate from human visitors and revenue. Most crawlers do not execute browser JavaScript. Forward their page requests from your server or edge:

sh
curl -X POST 'https://c.getkeen.cc/api/v1/bot-events' \
  -H 'Authorization: Bearer YOUR_SITE_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{"hostname":"example.com","path":"/pricing","user_agent":"GPTBot/1.0","client_ip":"203.0.113.1"}'

Create a key in Settings → API keys. It is secret: never embed it in a browser, public tracker or client bundle. The key selects the site; the hostname must be one of that site’s allowed domains. Send the actual incoming request’s user agent and path, not the example values above. Only detected bots are recorded; human requests return 202 with {"recorded":false}.

The optional client_ip is used only in memory to verify supported providers against their official published ranges. Use the connection address or a header sanitized by a trusted proxy, never an arbitrary caller-supplied forwarding header. A spoofed crawler user agent alone is labelled UA only, not verified. Providers without a configured official range feed also remain UA only.

Forward asynchronously using your server’s supported background-task mechanism; do not delay page responses. Respect opt-outs and applicable consent rules before forwarding. Send each page request once and avoid also reporting it through the browser tracker. No backfill is possible, rate limits apply, and this report is not a complete access log. Stored fields are minute-level time, normalized page path, a fixed crawler name/category, verification status and a count — no raw IP, user agent, visitor or session ID.

AI assistants (MCP)

Ask Claude, ChatGPT, Cursor or any other MCP client about your analytics in plain language: “Which sources brought the most visitors this month?”, “How does this week compare with the same week last year?”, “Create a goal for the /thanks page”. Keen Analytics runs a remote MCP server at:

text
https://api.getkeen.cc/api/v1/mcp

Sign in with OAuth (recommended). Add the URL as a custom connector (in Claude: Settings → Connectors → Add custom connector). The client registers itself, you sign in to Keen Analytics, pick a workspace and approve. The connection covers every site of that workspace; admins can also let it create and delete goals, funnels and segments. Disconnect it any time under Profile → Connected apps.

Claude Code (then run /mcp to sign in):

sh
claude mcp add --transport http keen https://api.getkeen.cc/api/v1/mcp

Or use a site API key from Settings → API: read-only, for that one site. Cursor, VS Code and other clients with a JSON config:

json
{
  "mcpServers": {
    "keen": {
      "url": "https://api.getkeen.cc/api/v1/mcp",
      "headers": { "Authorization": "Bearer keen_sk_…" }
    }
  }
}
ToolWhat it returns
list_sites, get_siteThe sites the connection covers, and one site's settings
get_overviewVisitors, visits, pageviews, bounce rate and visit time, against a comparison period
get_timeseriesVisitors and pageviews per hour, day, week or month, optionally with the comparison period
get_breakdownTop values of a dimension (source, campaign, page, entry/exit page, country, device, hour, weekday…), with changes
get_pages, get_hourly_heatmapTop pages with entries, exits and scroll depth; visitors by hour and weekday
get_realtime, get_visitorsVisitors right now; individual visitors when small-group hiding is off
get_journeys, get_geo_flowsPaths through the site, and where visitors come from
list_goals, get_goals, get_goal_seriesGoal definitions, conversions and conversions over time
list_funnels, get_funnelFunnel definitions and step-by-step conversion
get_revenue, get_revenue_timeseries, get_revenue_breakdownRevenue, customers and MRR, over time and by first-touch source or product (in cents)
get_conversion, compare_periodsConversion and revenue per visitor by dimension; what changed most since the previous period
get_web_vitals, get_web_vitals_breakdownCore Web Vitals p75, overall and by page, device or country
get_heatmap_pages, get_click_heatmapWhere visitors click and how far they scroll
get_search_queriesGoogle Search Console queries and pages
get_bot_trafficAI crawlers and bots: request counts, IP verification, requested pages and daily activity, separate from human traffic
list_insights, detect_anomalies, get_milestonesAutomatic insights, a fresh anomaly check, and milestones
list_segmentsSaved segments (named filter sets)
create_goal, delete_goal, create_funnel, delete_funnelChange goals and funnels (OAuth connections that may make changes)
create_segment, update_segment, delete_segment, refresh_insightsSave segments and recompute insights (same)

Tools take a period (today, yesterday, 7d, 30d, 90d, 12m, or custom with from and to dates), filters such as [{"dim": "country", "op": "is_not", "values": ["FR"]}] (operators is, is_not, contains, not_contains, starts_with) and compare (previous, year or custom). Small groups stay hidden, as on the dashboard. Treat an API key like a password: revoke it in Settings at any time. Limited to 120 requests per minute.

Options

npm optionScript attributeWhat it does
sitedata-siteYour site ID (required).
hostsrcYour collector URL (required for npm; the script’s own origin for the tag).
firstPartyuse /js/a.p.jsFirst-party storage: a random ID in your site’s localStorage for multi-day attribution. May require consent in some places.
ttlDaysdata-ttlFirst-party mode only: days before that ID is replaced (default 30).
noncenonceCSP nonce for the injected script.

Exclude your own visits with ignoreThisBrowser() (undo with ignoreThisBrowser(false)). Visits from localhost are never counted.

Content Security Policy

If your site sends a CSP header, allow the collector in two directives:

text
script-src  'self' https://c.getkeen.cc;
connect-src 'self' https://c.getkeen.cc;

Using nonces? Pass nonce to init / the component and the injected script will carry it.

Check the installation

  1. Deploy, then open your site in a normal browser window (not on localhost).
  2. Open Realtime in your dashboard: your visit appears within a few seconds. Settings → Installation also shows when the first event arrives.
  3. Nothing? Check the browser’s Network tab for a request to /e on your collector. Ad blockers, a CSP that doesn’t allow the collector, or a site domain that isn’t listed in your settings are the usual causes.

What is collected

Just the page path, the referring site, the screen width, how far down each page was scrolled, and your custom events. From the visit we work out the country and device type, then throw away the IP address. No cookies, and nothing shared between sites. See the privacy principles for details.

Ready to measure your site?

Create a site and get your site ID in under a minute.

Sign up