Web client for serverless-website-analytics
npm install serverless-website-analytics-client- Serverless Website Analytics Client
* Usage
+ Standalone Import Script Usage
- Tracking
* Attribute tracking
* Manual tracking
+ SDK Client Usage
- Vue
- React
- Svelte
* Package src
* Developing
* Contributing
* FAQ
+ The network calls to the backend fail with 403
+ Why not fetch with keepalive in the client
There are two ways to use the client:
- Standalone import script - Single line, standard JS script in your HTML.
- SDK client - Import the SDK client into your project and use in any SPA.
Then include the standalone script in your HTML:
``html`
...
...
You need to replace with the origin of your deployed backend. Available attributes on the scriptsite
are:
- - Required. The name of your site, this must correspond with the name you specified when deploying theserverless-website-analytics backend.api-url
- - Optional. Uses the same origin as the current script if not specified. This is the URL to the backend.attr-tracking
Allowing it to be specified opens a few use cases for testing.
- - Optional. If "true", the script will track all button and a HTML elements that have theswa-event attribute on them. Example: . See below for options.serverless-website-analytics
- - Optional. This is only required if the browser does not support document.currentScript
(All modern browsers since 2015 do). Only specify the tag, no value is needed.
#### Tracking
##### Attribute tracking
If you specified the attr-tracking attribute on the script tag, then all button and a HTML elements that have theswa-event attribute on them will be tracked. The swa-event attribute is required and the following attributes areswa-event-category
available:
- - Optional. The category of the event that can be used to group events.swa-event-data
- - Optional. The data of the event. Defaults to 1.swa-event-async
- - Optional. If present, the event will be sent asynchronously
with no guarantee of delivery but a better chance of not being canceled if page is unloaded right after.
`html
##### Manual tracking
You can find the instantiated instance of the serverless-website-analytics component under the window at window.swa.`
This enables you to call all the functions like tracking manually. Example:js`
window.swa.v1.analyticsTrack('about_click')
#### Beacon/pixel tracking
Beacon/pixel tracking can be used as alternative to HTML attribute tracking. Beacon tracking is useful for
tracking events outside your domain, like email opens, external blog views, etc.
`html`![]()
site
The and event fields are required. The category field and all the other fields are optional, exceptreferrer
the field, which is not supported.
Install the client:
``
npm install serverless-website-analytics-client
Irrelevant of the framework, you have to do the following to track page views on your site:
1. Initialize the client only once with analyticsPageInit. The site name must correspond with one that you specifiedserverless-website-analytics
when deploying the backend. You also need the URL to the backend. Make sure your frontendOrigin
site's is whitelisted in the backend config.analyticsPageChange
2. On each route change call the function with the name of the new page.
Beacon/pixel tracking is also supported but it is not recommended as it looses some info the SDK gathers. This includes
the session_id, user_id and referrerfields. The first two can still be specified but the reffer field ca not.
> [!IMPORTANT]
> The following sections show you how to do it in a few frameworks, but you can still DIY with the SDK in ANY framework.
> The OpenAPI spec
> can be used for any language that isn't TS/JS.
#### Vue
_./usage/vue/vue-project/src/main.ts_
`typescript
...
import * as swaClient from 'serverless-website-analytics-client';
const app = createApp(App);
app.use(router);
swaClient.v1.analyticsPageInit({
inBrowser: true, //Not SSR
site: "
apiUrl: "
// debug: true,
});
router.afterEach((event) => {
swaClient.v1.analyticsPageChange(event.path);
});
app.mount('#app');
export { swaClient };
`
Tracking:
_./usage/vue/vue-project/src/App.vue_
`typescript`
import {swaClient} from "./main";
...
// (event: string, data?: number, category?: string)
swaClient.v1.analyticsTrack("vue", count.value, "test")
#### React
_./usage/react/react-project/src/main.tsx_
`typescript
...
import * as swaClient from 'serverless-website-analytics-client';
const router = createBrowserRouter([
...
]);
swaClient.v1.analyticsPageInit({
inBrowser: true, //Not SSR
site: "
apiUrl: "
// debug: true,
});
router.subscribe((state) => {
swaClient.v1.analyticsPageChange(state.location.pathname);
});
swaClient.v1.analyticsPageChange("/");
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
)
export { swaClient };
`
Tracking:
_./usage/react/react-project/src/App.tsx_
`typescript``
import {swaClient} from "./main.tsx";
...
// (event: string, data?: number, category?: string)
swaClient.v1.analyticsTrack("vue", count.value, "test")
#### Svelte
_./usage/svelte/svelte-project/src/App.svelte_
`sveltehtml
`
Tracking:
_./usage/svelte/svelte-project/src/lib/Counter.svelte_
`sveltehtml``
#### Angular
See example at: https://github.com/cebert/serverless-web-analytics-demo-spa-application
#### PHP
See example at: https://github.com/wheeleruniverse/wheelerrecommends
#### ..Any other framework
The src located at package/src/index.ts does not use any libraries to generate the API. The TypeScript types howeverOpenAPI-Ingest.yaml
are generated from the file that is copied(manually) from the backendcd src/src && npm run generate-openapi-ingest
(). Once the latest OpenAPI-Ingest.yaml is copied to the package/srccd package && npm run generate-types
directory the command can be run to generate the latest TS types.
The client is written in a functional manner and leverages namespaces for the versioning.
The deploy scripts are managed by wireit which just supercharges your npm scripts.package/src/scripts.ts
It calls the certain functions in the file to do things like generate the API TS types from the/src
OpenAPI spec and package the app from the to the /dist directory.
Commits MUST follow the Conventional Commits standard.
Commit names are used to determine the next logical version number as per semantic-release.
A small cheat sheet, in order to get a:
- Patch - Have at least 1 commit name with a fix: typefeat:
- Minor - Have at least 1 commit name with a typeBREAKING CHANGE:
- Major - Have at least 1 commit message (in the footer) that includes the words:
A new Major version should only be rolled when a new version of the backend ingest API is rolled out. The client package
major version must always match the current ingest API latest version.
A GitHub workflow is used to create the new version on GitHub and NPM. It is only triggered on the condition that it
is a push to main (after a PR is merged) and that the /package files changed.
All contributions are welcome!
There are currently no test other than manually verifying the code works as expected
by the frameworks as in the Usage section. There is also no style enforced, but I would prefer the following for the
time being:
- 2 spaces
- Semicolons on line-endings
- Braces on new lines for functions, types can be inline.
I know barbaric 😅. Tests, linting, prettier and pre commit hooks still need to be added and then the style
mention above can be forgo.
This is because the Origin that is sending the request has not been added to the ALLOWED_ORIGINS config.
Examples of Origins:
- If you are doing local development then your origin might look like http://localhost:5173https://rehanvdm.com
- If it from your personal blog then it might look like but don't forget to also whitelist allhttps://www.rehanvdm.com
possible subdomains as well like: .
If this value is currently set to allow all Origins (not recommended) with a * then the 403 is caused by somethingOrigin
else and not the whitelisting.
The navigator.sendBeacon(...) has type ping in Chrome or beacon in FireFox instead of POST, it also doesOPTION
not send preflight calls even if it is not the same host. Browsers just handle it slightly differentlykeepalive` set.
and the probability of it being delivered is greater than fetch with
More on the topic.