Write your own tracking script
This guide is for anyone who wants to send page views to Tinylytics from their own code instead of loading the embed script. You might want every line that runs on your pages to live in your own bundle, or you might have a strict Content Security Policy, or a router you would rather hook into directly. The embed script makes one small request per page view. Your script makes the same request, and Tinylytics treats the result like any other hit.
Before you start
You need the site’s Site ID. It is the data-site value of the embed tag in Settings → Tracking, and it is shown beside the tag as Site ID:
<script defer src="https://tinylytics.app/js/script.js" data-site="YOUR_SITE_ID"></script>
If your pages still load the old tag, the same ID sits in its URL, between /embed/ and .js.
The request has to come from the visitor’s browser. Tinylytics works out the browser, operating system, country, and unique visitor from the request itself, so a hit sent from your server is recorded as your server, and server user agents such as curl are dropped as bots. To record hits from a backend, use the API instead. To count readers in RSS clients and email, where JavaScript does not run, use the tracking pixel.
Send a page view
A page view is a POST to the collector, with the page details in the query string:
POST https://tinylytics.app/collector/YOUR_SITE_ID?url=…&path=…&referrer=…
| Parameter | Value |
|---|---|
url |
The full address of the page, including its query string. Campaign parameters such as utm_source and ref are read from here. |
path |
The path shown in your stats, usually location.pathname. An empty path is stored as /. |
referrer |
The address the visitor came from, or an empty string when they came from another page on your own site. |
This script reads those values from the page and sends them once. It defines track() so the later sections can reuse it:
<script>
const tinylyticsEndpoint = "https://tinylytics.app/collector/YOUR_SITE_ID"
function track(extra = {}) {
const internal = document.referrer.startsWith(location.origin)
const params = new URLSearchParams({
url: location.href,
path: location.pathname,
referrer: internal ? "" : document.referrer,
...extra
})
fetch(`${tinylyticsEndpoint}?${params}`, { method: "POST", keepalive: true })
}
track()
</script>
Always send referrer, even when it is empty. If it is missing, Tinylytics falls back to the Referer header on the request, which is your own page, and your site starts appearing in its own referrer list.
Keep the request plain: parameters in the query string, no body, no custom headers. The collector does not answer CORS preflight requests, so a request that needs one, such as a JSON body sent with Content-Type: application/json, never arrives.
The sample is an inline script to keep it readable. Under a strict Content Security Policy, move track() into your own bundle and allow https://tinylytics.app in connect-src.
keepalive: true lets the request finish when the visitor leaves the page straight away, which matters most for events sent from a link click.
Count navigations in a single-page app
A router that changes the URL without loading a new document will not run your script again. Replace the bare track() call at the end of the script above with trackPageView(), which skips the request when the address has not changed, so a router that fires twice does not count twice:
let lastTrackedUrl = null
function trackPageView() {
if (location.href === lastTrackedUrl) return
lastTrackedUrl = location.href
track()
}
trackPageView()
Call trackPageView() wherever your router finishes a navigation: a turbo:load listener for Turbo, router.afterEach in Vue Router, or an effect that depends on the location in React Router.
The embed script counts history.pushState and back or forward, and leaves replaceState alone because it only rewrites the address of the page already showing. Do the same, or a router that tidies the query string will count a view each time.
document.referrer does not change on client-side navigation, so every view in the visit reports the address the visitor first arrived from. The embed script behaves the same way.
Send events
An event goes to the same address with two more parameters. Events land on the Events tab and do not count as page views.
| Parameter | Value |
|---|---|
event |
The event name: a category and an action joined by a dot, such as file.download. |
event_value |
Optional. A detail worth keeping, such as the filename. |
document.querySelector("#subscribe")?.addEventListener("click", () => {
track({ event: "button.subscribe" })
})
document.querySelectorAll("a[download]").forEach((link) => {
link.addEventListener("click", () => {
track({ event: "file.download", event_value: link.getAttribute("download") || link.pathname })
})
})
A name is made of letters, digits, _, and -, in at least two parts separated by dots. A name that does not fit, such as a bare click, is dropped without an error. The embed script turns button->click into button.click before sending; your script has to send the dotted form itself.
Keep the same ignore behaviour
Everything under Settings → Ignore rules runs on the server, so IP addresses, countries, browsers, sources, paths, and referrers are filtered for hits from your script with no extra work. The rest of what the embed script does on the page is now up to you.
Your own visits. Visiting your site with ?tiny_ignore=true, or the short ?ti=true, works because the embed script leaves a tinylytics_ignore flag in local storage and checks it before counting. Read the same flag at the top of track(), and handle both URL parameters yourself, so the flag works whichever script set it:
const query = new URLSearchParams(location.search)
const ignoreParam = query.get("tiny_ignore") || query.get("ti")
if (ignoreParam === "true") localStorage.setItem("tinylytics_ignore", "true")
if (ignoreParam === "false") localStorage.removeItem("tinylytics_ignore")
function track(extra = {}) {
if (localStorage.getItem("tinylytics_ignore")) return
// …the rest of track() as above
}
Error pages. Skip error pages works by having the embed script check the page’s status before it counts. Your script cannot see that status, so leave the track() call out of your 404 and error templates instead.
Local development. With Developer mode on, Tinylytics drops any hit whose url is a local address, so testing on your own machine stays out of your stats. With it off, local hits count. Pages opened from a file:// address are dropped unless Accept hits from any domain is on.
Keep the widgets
Your script only counts. Hit counters, kudos, country flags, and the other widgets are drawn by the embed script, and the new embed script also sends a page view whenever it loads. Loading both would count every visit twice.
To keep the widgets and your own counting, load the embed script with data-ignore on the tag. It draws the widgets and sends no page views or events, so a visit is never counted by both scripts:
<script defer src="https://tinylytics.app/js/script.js" data-site="YOUR_SITE_ID" data-ignore></script>
The old script did the same with ?ignore next to its widget parameters.
Check that it works
Open one of your pages with the browser’s developer tools on the Network tab. You should see a POST to /collector/YOUR_SITE_ID that returns 200, and the hit should appear on Overview within a few minutes. A 204 is also fine: it means Tinylytics was briefly unreachable and the hit was queued to be replayed.
A successful response means the collector accepted the request, not that the hit was counted. Bot detection, your ignore rules, and spam protection run afterwards, and a hit they drop leaves no trace in the response. A 429 means one address sent too many requests within a minute. If the request succeeds and nothing appears, work through Hits not showing.
Send hits from your own backend
If the visit never reaches a browser you control, or you want to decide exactly what gets recorded, use the API instead of the collector. POST /sites/:id/hits and POST /sites/:id/events take JSON from your server, with batch versions for importing or replaying many at once. Because the request comes from your server rather than the visitor’s browser, you pass the details the collector would have read from it: user_agent, ip_address or country, and a visitor_id to group a visitor’s hits together.
The API needs a full-access key from Account → API keys, and the site’s numeric ID rather than its Site ID. Keep that key on your server. Anyone who sees it can write to and delete from your account, so it must never appear in a page or a client-side bundle.
The API also tells you what happened: 201 when the hit was recorded, and 202 with a reason when an ignore rule dropped it.
Next
Event tracking
Count the clicks that matter — downloads, signups, subscriptions — with one HTML attribute.
Ignoring your hits
Keep your own reloads out of your numbers, and keep noise out for good.
Pixel tracking
A 1×1 gif for RSS readers and newsletters, where JavaScript never runs.
API
Read your analytics and write hits, events, and kudos from your own backend.