@tbdhdev/beacon-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +586 -2
- package/dist/astro.d.ts +10 -0
- package/dist/astro.js +26 -0
- package/dist/astro.js.map +1 -0
- package/dist/index-t-jJl5-d.d.ts +40 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/nuxt.d.ts +10 -0
- package/dist/nuxt.js +42 -0
- package/dist/nuxt.js.map +1 -0
- package/dist/react.d.ts +6 -0
- package/dist/react.js +15 -0
- package/dist/react.js.map +1 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +102 -0
- package/dist/server.js.map +1 -0
- package/dist/solid.d.ts +7 -0
- package/dist/solid.js +44 -0
- package/dist/solid.js.map +1 -0
- package/dist/src-DaAShSXp.js +300 -0
- package/dist/src-DaAShSXp.js.map +1 -0
- package/dist/sveltekit.d.ts +7 -0
- package/dist/sveltekit.js +20 -0
- package/dist/sveltekit.js.map +1 -0
- package/dist/tanstack-router.d.ts +12 -0
- package/dist/tanstack-router.js +18 -0
- package/dist/tanstack-router.js.map +1 -0
- package/dist/vue.d.ts +20 -0
- package/dist/vue.js +31 -0
- package/dist/vue.js.map +1 -0
- package/package.json +113 -3
- package/src/astro.ts +29 -0
- package/src/core.ts +542 -0
- package/src/index.ts +58 -0
- package/src/nuxt.ts +50 -0
- package/src/react.ts +13 -0
- package/src/server.ts +219 -0
- package/src/solid.ts +63 -0
- package/src/sveltekit.ts +16 -0
- package/src/tanstack-router.ts +24 -0
- package/src/vue.ts +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joshue Abance
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,587 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tbdhdev/beacon-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Privacy-friendly Beacon analytics for apps built with a framework: React, Next.js, TanStack Router
|
|
4
|
+
and Start, Vue, Nuxt, Svelte, SvelteKit, Solid, SolidStart and Astro. Pageviews, custom events, outbound
|
|
5
|
+
links, downloads and Core Web Vitals, sent straight to your self-hosted Beacon instance.
|
|
6
|
+
Nothing is stored in cookies or localStorage.
|
|
7
|
+
|
|
8
|
+
Not using a framework? Paste the zero-install `<script>` snippet from the dashboard instead.
|
|
9
|
+
It runs the same tracker without a build step.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @tbdhdev/beacon-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The integrations support the current major version of each framework: React 19 (Next.js 16),
|
|
18
|
+
Vue 3.5, Nuxt 4, SvelteKit 3 with Svelte 5, Solid 2 with Solid Router 2, Solid 1.9 with Solid
|
|
19
|
+
Router 0.16 (what SolidStart 2 runs on), TanStack Router and Start 1, and Astro 7. Older versions
|
|
20
|
+
are not supported.
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
Call `init()` once in code that runs in the browser:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { init } from "@tbdhdev/beacon-sdk";
|
|
28
|
+
|
|
29
|
+
init({
|
|
30
|
+
websiteId: "your-website-uuid",
|
|
31
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
That records the first pageview and every client-side navigation (`pushState`, back/forward,
|
|
36
|
+
and `replaceState` to another path). Your website id and event URL are in the dashboard, on
|
|
37
|
+
the website's **Settings** tab under **Tracking code**.
|
|
38
|
+
|
|
39
|
+
## Options
|
|
40
|
+
|
|
41
|
+
| Option | Default | What it does |
|
|
42
|
+
| :-------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
43
|
+
| `websiteId` | required | Website id from the dashboard. |
|
|
44
|
+
| `endpoint` | `/x/e` | Event URL: your Beacon origin + ingest prefix + event path. Relative URLs resolve against the page. If you rename the event path in Settings → Tracking, update it here. |
|
|
45
|
+
| `autoPageviews` | `true` | Record pageviews from the browser history. Set `false` to call `page()` from your router. |
|
|
46
|
+
| `outbound` | `false` | Track clicks on links to other hosts. |
|
|
47
|
+
| `downloads` | `false` | Track clicks on file links (`pdf`, `zip`, `csv`, `docx`, `mp4`, ...). |
|
|
48
|
+
| `webVitals` | `false` | Send LCP, INP, CLS and TTFB when the page is hidden, and CLS and INP again if they grow. |
|
|
49
|
+
| `hashRouting` | `false` | The app routes in the URL hash (`/#/pricing`, e.g. Vue's `createWebHashHistory`, React Router's `HashRouter`): record `/pricing` as the page. Also set it in framework integrations. |
|
|
50
|
+
|
|
51
|
+
## API
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { identify, page, track } from "@tbdhdev/beacon-sdk";
|
|
55
|
+
|
|
56
|
+
track("signup_clicked", { plan: "pro" }); // custom event; prop values: string | number | boolean
|
|
57
|
+
identify("user_123", { plan: "pro" }); // opt-in, for your own logged-in users; kept in memory only
|
|
58
|
+
page(); // record a pageview for the current URL, or page("/virtual/path")
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
- **SSR-safe.** Every function is a no-op on the server, so importing the SDK in shared code
|
|
62
|
+
is fine.
|
|
63
|
+
- **Call order doesn't matter.** `track()`, `identify()` and `page()` calls made before `init()`
|
|
64
|
+
are queued and sent right after it.
|
|
65
|
+
- **`init()` runs once.** Later calls are ignored, so React Strict Mode and remounts are safe.
|
|
66
|
+
- **Repeated pageviews are skipped.** `page()` for the page already recorded (same path and
|
|
67
|
+
query) does nothing. Campaign params (`utm_*`, `gclid`, `fbclid`, `msclkid`) don't count, so
|
|
68
|
+
removing them after landing is not a new page. With automatic pageviews, `replaceState` on the
|
|
69
|
+
same path (filters synced to the URL) updates the URL without a pageview.
|
|
70
|
+
- **What counts as a view.** A page the browser prerenders sends nothing until the visitor
|
|
71
|
+
actually opens it. A page restored from the back/forward cache is recorded again.
|
|
72
|
+
- **Link clicks.** `outbound` and `downloads` also catch middle-clicks (open in a new tab), links
|
|
73
|
+
inside open shadow roots (web components), and same-origin `<a download>` links whatever the
|
|
74
|
+
file extension.
|
|
75
|
+
- **Web vitals belong to the page load.** In a single-page app they are filed under the page
|
|
76
|
+
that loaded, not the route open when the tab is hidden. Good scores are reported too (a CLS
|
|
77
|
+
of 0, an INP from a fast first interaction). If the visitor comes back and CLS or INP get
|
|
78
|
+
worse, the next hide sends the new values, and the dashboard still counts the page load once.
|
|
79
|
+
|
|
80
|
+
### Declarative events
|
|
81
|
+
|
|
82
|
+
No JavaScript needed: any element with `data-beacon-event` sends an event on click, with each
|
|
83
|
+
`data-beacon-prop-*` attribute as a prop.
|
|
84
|
+
|
|
85
|
+
```html
|
|
86
|
+
<button data-beacon-event="signup_clicked" data-beacon-prop-plan="pro">
|
|
87
|
+
Sign up
|
|
88
|
+
</button>
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Frameworks
|
|
92
|
+
|
|
93
|
+
### React (Vite, React Router)
|
|
94
|
+
|
|
95
|
+
A client-only app can start Beacon at module scope. Automatic pageviews pick up React Router
|
|
96
|
+
navigations.
|
|
97
|
+
|
|
98
|
+
```tsx
|
|
99
|
+
// main.tsx
|
|
100
|
+
import { init } from "@tbdhdev/beacon-sdk";
|
|
101
|
+
|
|
102
|
+
init({
|
|
103
|
+
websiteId: "your-website-uuid",
|
|
104
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
105
|
+
});
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### Next.js (App Router)
|
|
109
|
+
|
|
110
|
+
Render `<Beacon>` from `@tbdhdev/beacon-sdk/react` in the root layout. It is a client component, so
|
|
111
|
+
the layout can stay a server component. For exact pageviews, turn `autoPageviews` off and
|
|
112
|
+
record them from the router:
|
|
113
|
+
|
|
114
|
+
```tsx
|
|
115
|
+
// app/layout.tsx
|
|
116
|
+
import { Beacon } from "@tbdhdev/beacon-sdk/react";
|
|
117
|
+
import { Suspense, type ReactNode } from "react";
|
|
118
|
+
import { Pageviews } from "./pageviews";
|
|
119
|
+
|
|
120
|
+
export default function RootLayout({ children }: { children: ReactNode }) {
|
|
121
|
+
return (
|
|
122
|
+
<html lang="en">
|
|
123
|
+
<body>
|
|
124
|
+
{children}
|
|
125
|
+
<Beacon
|
|
126
|
+
websiteId="your-website-uuid"
|
|
127
|
+
endpoint="https://beacon.example.com/x/e"
|
|
128
|
+
autoPageviews={false}
|
|
129
|
+
/>
|
|
130
|
+
{/* useSearchParams() needs a Suspense boundary on statically rendered pages. */}
|
|
131
|
+
<Suspense>
|
|
132
|
+
<Pageviews />
|
|
133
|
+
</Suspense>
|
|
134
|
+
</body>
|
|
135
|
+
</html>
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
```tsx
|
|
141
|
+
// app/pageviews.tsx
|
|
142
|
+
"use client";
|
|
143
|
+
import { page } from "@tbdhdev/beacon-sdk";
|
|
144
|
+
import { usePathname, useSearchParams } from "next/navigation";
|
|
145
|
+
import { useEffect } from "react";
|
|
146
|
+
|
|
147
|
+
export function Pageviews() {
|
|
148
|
+
const pathname = usePathname();
|
|
149
|
+
const search = useSearchParams().toString();
|
|
150
|
+
|
|
151
|
+
useEffect(() => page(), [pathname, search]);
|
|
152
|
+
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Next.js clears `<title>` on client navigation and sets the new one a moment later. A pageview
|
|
158
|
+
that finds the title empty waits for it (up to 1 second), so titles in your reports stay
|
|
159
|
+
correct.
|
|
160
|
+
|
|
161
|
+
`<Beacon>` takes the same props as `init()`. Render it once; later prop changes are ignored.
|
|
162
|
+
|
|
163
|
+
### Framework integrations
|
|
164
|
+
|
|
165
|
+
Each integration below starts Beacon once, only in the browser, and records pageviews from the
|
|
166
|
+
framework's own navigation event instead of watching the History API, after the new page's
|
|
167
|
+
`<title>` is set. They take the same options as `init()` except `autoPageviews`. Import
|
|
168
|
+
`track`, `identify` and `page` from `@tbdhdev/beacon-sdk` anywhere, unless noted.
|
|
169
|
+
|
|
170
|
+
| Framework | Import | Pageviews from |
|
|
171
|
+
| :------------------------------- | :------------------------------------ | :----------------------------------- |
|
|
172
|
+
| TanStack Router, TanStack Start | `@tbdhdev/beacon-sdk/tanstack-router` | `router.subscribe("onRendered")` |
|
|
173
|
+
| Vue 3 (Vue Router) | `@tbdhdev/beacon-sdk/vue` | `router.afterEach`, after the render |
|
|
174
|
+
| Nuxt 4 | `@tbdhdev/beacon-sdk/nuxt` | the `page:loading:end` hook |
|
|
175
|
+
| SvelteKit | `@tbdhdev/beacon-sdk/sveltekit` | `afterNavigate` |
|
|
176
|
+
| Solid, SolidStart (Solid Router) | `@tbdhdev/beacon-sdk/solid` | `useLocation()` changes |
|
|
177
|
+
| Astro | `@tbdhdev/beacon-sdk/astro` | page load and `astro:page-load` |
|
|
178
|
+
|
|
179
|
+
#### TanStack Router and TanStack Start
|
|
180
|
+
|
|
181
|
+
Pass the router to `initBeacon()` where you create it. It works with the React, Solid and Vue
|
|
182
|
+
flavors of TanStack Router. In TanStack Start, `getRouter()` also runs on the server; Beacon
|
|
183
|
+
only starts in the browser, and the first pageview is recorded after hydration.
|
|
184
|
+
|
|
185
|
+
```tsx
|
|
186
|
+
import { createRouter } from "@tanstack/react-router";
|
|
187
|
+
// src/router.tsx
|
|
188
|
+
import { initBeacon } from "@tbdhdev/beacon-sdk/tanstack-router";
|
|
189
|
+
import { routeTree } from "./routeTree.gen";
|
|
190
|
+
|
|
191
|
+
export function getRouter() {
|
|
192
|
+
const router = createRouter({ routeTree });
|
|
193
|
+
|
|
194
|
+
initBeacon(router, {
|
|
195
|
+
websiteId: "your-website-uuid",
|
|
196
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
return router;
|
|
200
|
+
}
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Set each route's title with `head: () => ({ meta: [{ title: "..." }] })` and render
|
|
204
|
+
`<HeadContent />`.
|
|
205
|
+
|
|
206
|
+
#### Vue 3
|
|
207
|
+
|
|
208
|
+
Install the plugin with your router. Without `router`, it behaves like `init()` and follows the
|
|
209
|
+
History API.
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
// main.ts
|
|
213
|
+
import { beacon } from "@tbdhdev/beacon-sdk/vue";
|
|
214
|
+
|
|
215
|
+
createApp(App)
|
|
216
|
+
.use(router)
|
|
217
|
+
.use(beacon, {
|
|
218
|
+
websiteId: "your-website-uuid",
|
|
219
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
220
|
+
router,
|
|
221
|
+
})
|
|
222
|
+
.mount("#app");
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
```vue
|
|
226
|
+
<script setup lang="ts">
|
|
227
|
+
import { useBeacon } from "@tbdhdev/beacon-sdk/vue";
|
|
228
|
+
|
|
229
|
+
const { track } = useBeacon();
|
|
230
|
+
</script>
|
|
231
|
+
|
|
232
|
+
<template>
|
|
233
|
+
<button @click="track('signup_clicked', { plan: 'pro' })">Sign up</button>
|
|
234
|
+
</template>
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Pageviews are recorded on the `nextTick` after `afterEach`, so a title set in another
|
|
238
|
+
`afterEach` hook or by the new page's components is already there.
|
|
239
|
+
|
|
240
|
+
#### Nuxt 4
|
|
241
|
+
|
|
242
|
+
Add the module and configure it under `beacon`. `useBeacon()` is auto-imported.
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
// nuxt.config.ts
|
|
246
|
+
export default defineNuxtConfig({
|
|
247
|
+
modules: ["@tbdhdev/beacon-sdk/nuxt"],
|
|
248
|
+
beacon: {
|
|
249
|
+
websiteId: "your-website-uuid",
|
|
250
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
251
|
+
},
|
|
252
|
+
});
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
The options become public runtime config, so they can also be set when the app starts instead
|
|
256
|
+
of at build time: `NUXT_PUBLIC_BEACON_WEBSITE_ID`, `NUXT_PUBLIC_BEACON_ENDPOINT` and so on.
|
|
257
|
+
Nuxt only reads such a variable for a key that exists, so list the key under `beacon` (e.g.
|
|
258
|
+
`websiteId: ""`).
|
|
259
|
+
|
|
260
|
+
The module adds a client-only plugin. It records a pageview on Nuxt's `page:loading:end` hook,
|
|
261
|
+
which runs once per navigation (query-only ones included) and on the first load (one that shows
|
|
262
|
+
`error.vue` is recorded once it has rendered), and waits for
|
|
263
|
+
Nuxt to write the `useHead()` title. Router hooks run too early: they see the previous page's
|
|
264
|
+
title.
|
|
265
|
+
|
|
266
|
+
#### Svelte (without SvelteKit)
|
|
267
|
+
|
|
268
|
+
Svelte has no router of its own, so call `init()` before mounting. Automatic pageviews follow
|
|
269
|
+
any router that uses the History API, and back/forward pageviews wait for the app to render.
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
// main.ts
|
|
273
|
+
import { init } from "@tbdhdev/beacon-sdk";
|
|
274
|
+
import { mount } from "svelte";
|
|
275
|
+
import App from "./app.svelte";
|
|
276
|
+
|
|
277
|
+
init({
|
|
278
|
+
websiteId: "your-website-uuid",
|
|
279
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
280
|
+
});
|
|
281
|
+
mount(App, { target: document.querySelector("#app")! });
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
#### SvelteKit
|
|
285
|
+
|
|
286
|
+
Call `initBeacon()` from the root layout. It uses `afterNavigate`, so it must run during
|
|
287
|
+
component initialization. During SSR it does nothing.
|
|
288
|
+
|
|
289
|
+
```svelte
|
|
290
|
+
<!-- src/routes/+layout.svelte -->
|
|
291
|
+
<script lang="ts">
|
|
292
|
+
import { initBeacon } from "@tbdhdev/beacon-sdk/sveltekit";
|
|
293
|
+
|
|
294
|
+
let { children } = $props();
|
|
295
|
+
|
|
296
|
+
initBeacon({ websiteId: "your-website-uuid", endpoint: "https://beacon.example.com/x/e" });
|
|
297
|
+
</script>
|
|
298
|
+
|
|
299
|
+
{@render children()}
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
This entry imports `$app/navigation`, so its export carries a `svelte` condition. That tells
|
|
303
|
+
`vite-plugin-svelte` to bundle it for SSR instead of leaving it to Node.
|
|
304
|
+
|
|
305
|
+
#### Solid and SolidStart
|
|
306
|
+
|
|
307
|
+
Render `<Beacon>` once inside the router, for example in the root layout. It works on Solid 2
|
|
308
|
+
with Solid Router 2, and on Solid 1.9 with Solid Router 0.16, which SolidStart 2 runs on. With
|
|
309
|
+
Solid 2 and Solid Router 2:
|
|
310
|
+
|
|
311
|
+
```tsx
|
|
312
|
+
import { createRouter } from "@solidjs/router";
|
|
313
|
+
import { Beacon } from "@tbdhdev/beacon-sdk/solid";
|
|
314
|
+
import { Loading } from "solid-js";
|
|
315
|
+
|
|
316
|
+
const Router = createRouter({ routes });
|
|
317
|
+
|
|
318
|
+
render(
|
|
319
|
+
() => (
|
|
320
|
+
<Router>
|
|
321
|
+
{(props) => (
|
|
322
|
+
<Loading fallback={<p>Loading…</p>}>
|
|
323
|
+
<Beacon
|
|
324
|
+
websiteId="your-website-uuid"
|
|
325
|
+
endpoint="https://beacon.example.com/x/e"
|
|
326
|
+
/>
|
|
327
|
+
{props.children}
|
|
328
|
+
</Loading>
|
|
329
|
+
)}
|
|
330
|
+
</Router>
|
|
331
|
+
),
|
|
332
|
+
document.querySelector("#app")!,
|
|
333
|
+
);
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
On Solid 2, keep `<Beacon>` inside the `<Loading>` that wraps your routes: the first pageview then
|
|
337
|
+
waits until the first route has loaded, so it carries that page's title even when the route loads
|
|
338
|
+
data first. Outside that boundary, it would send the title from your HTML instead.
|
|
339
|
+
|
|
340
|
+
With Solid 1.9 and Solid Router 0.16, render it in `<Router root={...}>`. In SolidStart, that is
|
|
341
|
+
`src/app.tsx`:
|
|
342
|
+
|
|
343
|
+
```tsx
|
|
344
|
+
import { MetaProvider } from "@solidjs/meta";
|
|
345
|
+
import { Router } from "@solidjs/router";
|
|
346
|
+
import { FileRoutes } from "@solidjs/start/router";
|
|
347
|
+
import { Beacon } from "@tbdhdev/beacon-sdk/solid";
|
|
348
|
+
import { Suspense } from "solid-js";
|
|
349
|
+
|
|
350
|
+
export default function App() {
|
|
351
|
+
return (
|
|
352
|
+
<Router
|
|
353
|
+
root={(props) => (
|
|
354
|
+
<MetaProvider>
|
|
355
|
+
<Beacon
|
|
356
|
+
websiteId="your-website-uuid"
|
|
357
|
+
endpoint="https://beacon.example.com/x/e"
|
|
358
|
+
/>
|
|
359
|
+
<Suspense>{props.children}</Suspense>
|
|
360
|
+
</MetaProvider>
|
|
361
|
+
)}
|
|
362
|
+
>
|
|
363
|
+
<FileRoutes />
|
|
364
|
+
</Router>
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
The first pageview is recorded after hydration, once a navigation in flight has finished (a
|
|
370
|
+
redirect on load counts only its target); nothing runs during SSR. The export carries a `solid`
|
|
371
|
+
condition, so the Solid Vite plugin bundles it for SSR instead of leaving it to Node, which would
|
|
372
|
+
load a second copy of Solid Router.
|
|
373
|
+
|
|
374
|
+
Solid Router handles same-origin links itself, so give file links a `download` attribute
|
|
375
|
+
(`<a href="/report.csv" download>`); otherwise the router navigates to them.
|
|
376
|
+
|
|
377
|
+
#### Astro
|
|
378
|
+
|
|
379
|
+
Add the integration. It injects a small script into every page that records the page load
|
|
380
|
+
and, with `<ClientRouter />` (View Transitions), every `astro:page-load`.
|
|
381
|
+
|
|
382
|
+
```js
|
|
383
|
+
// astro.config.mjs
|
|
384
|
+
import beacon from "@tbdhdev/beacon-sdk/astro";
|
|
385
|
+
import { defineConfig } from "astro/config";
|
|
386
|
+
|
|
387
|
+
export default defineConfig({
|
|
388
|
+
integrations: [
|
|
389
|
+
beacon({
|
|
390
|
+
websiteId: "your-website-uuid",
|
|
391
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
392
|
+
}),
|
|
393
|
+
],
|
|
394
|
+
});
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
With `<ClientRouter />`, page scripts run only once, so bind DOM listeners in an
|
|
398
|
+
`astro:page-load` handler.
|
|
399
|
+
|
|
400
|
+
### Other frameworks
|
|
401
|
+
|
|
402
|
+
Call `init()` once from client-only code. Automatic pageviews follow any router that uses the
|
|
403
|
+
History API.
|
|
404
|
+
|
|
405
|
+
## Sending events through your own site
|
|
406
|
+
|
|
407
|
+
Ad blockers refuse requests to hosts and paths they know serve analytics. A full-stack app (Next.js,
|
|
408
|
+
TanStack Start, ...) can send events to one of its own routes instead, which forwards them to
|
|
409
|
+
Beacon from your server:
|
|
410
|
+
|
|
411
|
+
1. In **Settings → API keys**, create a key with the `write:events` scope for this website. Keep
|
|
412
|
+
it in a server-only env var such as `BEACON_API_KEY`.
|
|
413
|
+
2. Add a route that passes the request to `proxyBeacon()` from `@tbdhdev/beacon-sdk/server`. Any path
|
|
414
|
+
works; avoid words blockers look for, such as `analytics`, `track`, `collect` or `beacon`.
|
|
415
|
+
3. Set the browser SDK's `endpoint` to that path.
|
|
416
|
+
|
|
417
|
+
Next.js (App Router):
|
|
418
|
+
|
|
419
|
+
```ts
|
|
420
|
+
// app/api/e/route.ts
|
|
421
|
+
import { forwardedFor, proxyBeacon } from "@tbdhdev/beacon-sdk/server";
|
|
422
|
+
|
|
423
|
+
export function POST(request: Request) {
|
|
424
|
+
return proxyBeacon(request, {
|
|
425
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
426
|
+
apiKey: process.env.BEACON_API_KEY!,
|
|
427
|
+
// Right on Vercel; see "The visitor's IP" below for other hosts.
|
|
428
|
+
clientIp: forwardedFor(request),
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
```tsx
|
|
434
|
+
<Beacon websiteId="your-website-uuid" endpoint="/api/e" autoPageviews={false} />
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
TanStack Start:
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
import { createFileRoute } from "@tanstack/react-router";
|
|
441
|
+
// src/routes/api/e.ts
|
|
442
|
+
import { forwardedFor, proxyBeacon } from "@tbdhdev/beacon-sdk/server";
|
|
443
|
+
|
|
444
|
+
export const Route = createFileRoute("/api/e")({
|
|
445
|
+
server: {
|
|
446
|
+
handlers: {
|
|
447
|
+
POST: ({ request }) =>
|
|
448
|
+
proxyBeacon(request, {
|
|
449
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
450
|
+
apiKey: process.env.BEACON_API_KEY!,
|
|
451
|
+
// Right on Vercel; see "The visitor's IP" below for other hosts.
|
|
452
|
+
clientIp: forwardedFor(request),
|
|
453
|
+
}),
|
|
454
|
+
},
|
|
455
|
+
},
|
|
456
|
+
});
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
```ts
|
|
460
|
+
initBeacon(router, { websiteId: "your-website-uuid", endpoint: "/api/e" });
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
Any route handler that gets a standard `Request` works the same way: SvelteKit `+server.ts`, Astro
|
|
464
|
+
endpoints, Remix, Hono, Bun and Deno. Read the env var inside the handler, as above: on Cloudflare
|
|
465
|
+
and other edge runtimes it is only set per request.
|
|
466
|
+
|
|
467
|
+
The proxy forwards the body and the browser headers Beacon reads (`User-Agent`,
|
|
468
|
+
`Accept-Language`, `Origin`, `DNT`, `Sec-GPC`), never cookies. Beacon then handles the event as
|
|
469
|
+
if the browser had sent it: the same visitor, bot filtering, Do Not Track and allowed hostnames,
|
|
470
|
+
with rate limits per visitor (IPv6 per /56) rather than for your whole server. A ceiling per API
|
|
471
|
+
key (`RATE_LIMIT_PER_KEY` on the Beacon server, default 1000 requests per second) guards against
|
|
472
|
+
abuse, and one IPv6 /48 gets a tenth of it. Keep it above your peak traffic: visitors from enough
|
|
473
|
+
different networks could use it up.
|
|
474
|
+
|
|
475
|
+
### The visitor's IP
|
|
476
|
+
|
|
477
|
+
The key vouches for the IP you pass as `clientIp`, so take it from a source your host guarantees.
|
|
478
|
+
`forwardedFor(request)` reads the last `x-forwarded-for` entry. That is right on Vercel and behind
|
|
479
|
+
a proxy that sets or appends to the header, such as Caddy, or Nginx with
|
|
480
|
+
`proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`. With nothing in front (`next start`,
|
|
481
|
+
Bun, Deno or Node exposed directly), visitors can send their own `x-forwarded-for` to fake their IP
|
|
482
|
+
and country and dodge the per-visitor limit, so use another source. (`next start` fills the header
|
|
483
|
+
from the socket only when the visitor sent none, so it needs a proxy in front.)
|
|
484
|
+
|
|
485
|
+
| Where | `clientIp` |
|
|
486
|
+
| :--------------------------------------- | :--------------------------------------------------- |
|
|
487
|
+
| Vercel, or behind Caddy or Nginx | `forwardedFor(request)` |
|
|
488
|
+
| Cloudflare | `request.headers.get("cf-connecting-ip")` |
|
|
489
|
+
| Netlify | `request.headers.get("x-nf-client-connection-ip")` |
|
|
490
|
+
| Fly.io | `request.headers.get("fly-client-ip")` |
|
|
491
|
+
| TanStack Start on Node, nothing in front | `getRequestIP()` from `@tanstack/react-start/server` |
|
|
492
|
+
| SvelteKit | `getClientAddress()` from the request event |
|
|
493
|
+
| `Bun.serve`, nothing in front | `server.requestIP(request)?.address` |
|
|
494
|
+
| `Deno.serve`, nothing in front | `info.remoteAddr.hostname` |
|
|
495
|
+
|
|
496
|
+
Without an IP (`clientIp` left out, `null`, or a lookup that comes back empty), visitors are told
|
|
497
|
+
apart only by user agent, with no country, and all of them share a tenth of the key's ceiling, so
|
|
498
|
+
one client sending junk can use it up. `proxyBeacon()` warns once in your server log when that
|
|
499
|
+
happens.
|
|
500
|
+
|
|
501
|
+
The route answers with Beacon's status (`202` when accepted) and no body, `500` when `endpoint` or
|
|
502
|
+
`apiKey` is missing, and `502` when Beacon can't be reached within `timeoutMs` (default `5000`).
|
|
503
|
+
Your Beacon server must be as recent as this SDK: an older one counts proxied events as server
|
|
504
|
+
events, all under one visitor.
|
|
505
|
+
|
|
506
|
+
## Excluding your own visits
|
|
507
|
+
|
|
508
|
+
Open your site once with `#beacon-ignore=true` at the end of the URL. That browser stops
|
|
509
|
+
sending events until you open it with `#beacon-ignore=false`. This is the only thing Beacon
|
|
510
|
+
ever writes to storage.
|
|
511
|
+
|
|
512
|
+
## Server-side events
|
|
513
|
+
|
|
514
|
+
`@tbdhdev/beacon-sdk/server` sends events from anything with `fetch`: Node, Bun, Deno, edge
|
|
515
|
+
functions, route handlers, server actions, workers and CI. It authenticates with an API key,
|
|
516
|
+
so create one in **Settings → API keys** with the `write:events` scope and keep it in a
|
|
517
|
+
server-only env var. Never import this entry into browser code.
|
|
518
|
+
|
|
519
|
+
```ts
|
|
520
|
+
import { createBeaconServer } from "@tbdhdev/beacon-sdk/server";
|
|
521
|
+
|
|
522
|
+
const beacon = createBeaconServer({
|
|
523
|
+
websiteId: "your-website-uuid",
|
|
524
|
+
endpoint: "https://beacon.example.com/x/e",
|
|
525
|
+
apiKey: process.env.BEACON_API_KEY!,
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
await beacon.track("purchase", { amount: 49, currency: "USD" });
|
|
529
|
+
await beacon.identify("user_123", { plan: "pro" });
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
Every call takes an optional last argument with request details. Forward the end user's IP
|
|
533
|
+
and user agent so the event counts toward their visit, with the same browser, OS and country
|
|
534
|
+
as their pageviews. The IP is only used for the visitor hash and the country, and
|
|
535
|
+
is never stored. Your server's own IP, user agent and language are never used: events sent
|
|
536
|
+
without these details (from a cron job or a webhook) are grouped under one anonymous visitor
|
|
537
|
+
with no browser, country or language.
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
// e.g. in a Next.js route handler
|
|
541
|
+
export async function POST(request: Request) {
|
|
542
|
+
await beacon.track(
|
|
543
|
+
"checkout_completed",
|
|
544
|
+
{ amount: 49 },
|
|
545
|
+
{
|
|
546
|
+
url: request.headers.get("referer") ?? undefined,
|
|
547
|
+
// Your proxy appends the address it saw: earlier entries come from the client and can be forged.
|
|
548
|
+
ip: request.headers.get("x-forwarded-for")?.split(",").at(-1)?.trim(),
|
|
549
|
+
userAgent: request.headers.get("user-agent") ?? undefined,
|
|
550
|
+
distinctId: "user_123",
|
|
551
|
+
},
|
|
552
|
+
);
|
|
553
|
+
|
|
554
|
+
return new Response(null, { status: 204 });
|
|
555
|
+
}
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
| Context field | What it does |
|
|
559
|
+
| :------------------------------ | :---------------------------------------------------------------------- |
|
|
560
|
+
| `url` | Page the event belongs to (absolute URL). Shows up as the event's page. |
|
|
561
|
+
| `ip` | End user's IP, for the visitor hash and country. |
|
|
562
|
+
| `userAgent` | End user's `user-agent`, for the visitor hash, browser, OS and device. |
|
|
563
|
+
| `distinctId` | Your own user id, like `identify()` in the browser. |
|
|
564
|
+
| `title`, `referrer`, `language` | Optional page details. |
|
|
565
|
+
|
|
566
|
+
Take `ip` from what your own proxy or platform sets. The example reads the last
|
|
567
|
+
`x-forwarded-for` entry, which is right behind exactly one proxy that appends to the header;
|
|
568
|
+
behind more hops, or on a platform with its own client IP header, use that instead. Never use
|
|
569
|
+
the first entry: any client can send its own `x-forwarded-for`.
|
|
570
|
+
|
|
571
|
+
Calls return a promise that rejects when Beacon refuses the event: `401` for an unknown key or
|
|
572
|
+
one without the `write:events` scope, `403` for an expired key or one that doesn't cover this
|
|
573
|
+
website, `404` for an unknown website, `400` for an invalid event. Events that Beacon deliberately skips (excluded
|
|
574
|
+
IPs or paths) still resolve. A request that takes longer than `timeoutMs` (default `5000`, set
|
|
575
|
+
it in `createBeaconServer()`) is abandoned and rejects too. To keep analytics out of your response time, don't `await` the
|
|
576
|
+
call; catch its error instead, or hand it to your platform's `waitUntil()` on edge runtimes:
|
|
577
|
+
|
|
578
|
+
```ts
|
|
579
|
+
beacon.track("signup", { plan: "pro" }).catch(console.error);
|
|
580
|
+
```
|
|
581
|
+
|
|
582
|
+
Without the SDK, `POST` the same JSON to the event URL with `Authorization: Bearer <key>`. The
|
|
583
|
+
dashboard's **Server & CI** tab has ready-made `fetch` and `curl` snippets.
|
|
584
|
+
|
|
585
|
+
## License
|
|
586
|
+
|
|
587
|
+
MIT
|
package/dist/astro.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { AstroIntegration } from "astro";
|
|
2
|
+
import { o as BeaconConfig } from "./index-t-jJl5-d.js";
|
|
3
|
+
export type BeaconAstroOptions = Omit<BeaconConfig, "autoPageviews">;
|
|
4
|
+
/** Astro integration: `integrations: [beacon({ websiteId, endpoint })]` in `astro.config.mjs`. */
|
|
5
|
+
export default function beacon(config: BeaconAstroOptions): AstroIntegration;
|
|
6
|
+
/**
|
|
7
|
+
* Browser side of the integration, imported by the script it injects into every page. Records
|
|
8
|
+
* the page load and every `<ClientRouter />` (View Transitions) navigation.
|
|
9
|
+
*/
|
|
10
|
+
export declare function start(config: BeaconAstroOptions): void;
|
package/dist/astro.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { n as init, r as page } from "./src-DaAShSXp.js";
|
|
2
|
+
// src/astro.ts
|
|
3
|
+
/** Astro integration: `integrations: [beacon({ websiteId, endpoint })]` in `astro.config.mjs`. */
|
|
4
|
+
function beacon(config) {
|
|
5
|
+
return {
|
|
6
|
+
name: "@tbdhdev/beacon-sdk",
|
|
7
|
+
hooks: { "astro:config:setup": ({ injectScript }) => {
|
|
8
|
+
injectScript("page", `import { start } from "@tbdhdev/beacon-sdk/astro"; start(${JSON.stringify(config)});`);
|
|
9
|
+
} }
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Browser side of the integration, imported by the script it injects into every page. Records
|
|
14
|
+
* the page load and every `<ClientRouter />` (View Transitions) navigation.
|
|
15
|
+
*/
|
|
16
|
+
function start(config) {
|
|
17
|
+
init({
|
|
18
|
+
...config,
|
|
19
|
+
autoPageviews: false
|
|
20
|
+
});
|
|
21
|
+
page();
|
|
22
|
+
document.addEventListener("astro:page-load", () => page());
|
|
23
|
+
}
|
|
24
|
+
export { beacon as default, start };
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=astro.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"astro.js","names":[],"sources":["../src/astro.ts"],"sourcesContent":["import type { AstroIntegration } from \"astro\";\nimport { type BeaconConfig, init, page } from \"./index.js\";\n\nexport type BeaconAstroOptions = Omit<BeaconConfig, \"autoPageviews\">;\n\n/** Astro integration: `integrations: [beacon({ websiteId, endpoint })]` in `astro.config.mjs`. */\nexport default function beacon(config: BeaconAstroOptions): AstroIntegration {\n return {\n name: \"@tbdhdev/beacon-sdk\",\n hooks: {\n \"astro:config:setup\": ({ injectScript }) => {\n injectScript(\n \"page\",\n `import { start } from \"@tbdhdev/beacon-sdk/astro\"; start(${JSON.stringify(config)});`,\n );\n },\n },\n };\n}\n\n/**\n * Browser side of the integration, imported by the script it injects into every page. Records\n * the page load and every `<ClientRouter />` (View Transitions) navigation.\n */\nexport function start(config: BeaconAstroOptions): void {\n init({ ...config, autoPageviews: false });\n page();\n document.addEventListener(\"astro:page-load\", () => page());\n}\n"],"mappings":";;;AAMA,SAAwB,OAAO,QAA8C;CAC3E,OAAO;EACL,MAAM;EACN,OAAO,EACL,uBAAuB,EAAE,mBAAmB;GAC1C,aACE,QACA,4DAA4D,KAAK,UAAU,MAAM,EAAE,GACrF;EACF,EACF;CACF;AACF;;;;;AAMA,SAAgB,MAAM,QAAkC;CACtD,KAAK;EAAE,GAAG;EAAQ,eAAe;CAAM,CAAC;CACxC,KAAK;CACL,SAAS,iBAAiB,yBAAyB,KAAK,CAAC;AAC3D"}
|