📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Docs for new features
Blue Mouse0250a8f212f0
diff --git a/docs/docs/api/events.md b/docs/docs/api/events.mdindex 8da962617..56e89d880 100644--- a/docs/docs/api/events.md+++ b/docs/docs/api/events.md@@ -150,6 +150,46 @@ curl -i -X POST https://api.swetrix.com/log/hb \-d '{"pid":"YOUR_PROJECT_ID"}'```+#### WebSocket Heartbeat++For more efficient heartbeat tracking (like long-running sessions, desktop applications, etc.), you can use the WebSocket interface as an alternative to the HTTP endpoint.++**Connection Details:**++- **URL:** `https://api.swetrix.com`+- **Namespace:** `/hb`+- **Query Parameters:**+ - `pid` (Required): Your Project ID.++**Events:**++- `connected`: Emitted by the server when the session is successfully established.+- `error`: Emitted if the connection is rejected (e.g., missing PID, invalid origin, or bot detected).++**Example (using socket.io-client):**++```javascript+import { io } from 'socket.io-client'++const socket = io('https://api.swetrix.com/hb', {+ query: {+ pid: 'YOUR_PROJECT_ID',+ },+ transports: ['websocket'], // Optional: force WebSocket transport+})++socket.on('connected', () => {+ console.log('Heartbeat session established')+})++socket.on('error', (err) => {+ console.error('Heartbeat error:', err.message)+})++// The server automatically handles the heartbeat interval (every 60s)+// Keep the connection open as long as the user is active on the page+```+```json title="Response (201 Created)"{}```diff --git a/docs/docs/captcha/introduction.md b/docs/docs/captcha/introduction.mdindex 66a2e0cd7..c801a84e3 100644--- a/docs/docs/captcha/introduction.md+++ b/docs/docs/captcha/introduction.md@@ -3,8 +3,16 @@ title: Introductionslug: /captcha/introduction----Swetrix CAPTCHA is a fully open source, cookieless and privacy-friendly CAPTCHA service. It is designed to be used on websites and web applications to prevent bots from performing automated actions.+Swetrix CAPTCHA is a fully open source, cookieless, and privacy-friendly CAPTCHA service. It is designed to be used on websites and web applications to prevent bots from performing automated actions.-The CAPTCHA challenge is presented to the user in the form of sequence of letters and numbers. The user has to type the letters and numbers in the correct order to solve the challenge.+## How it works++Unlike traditional CAPTCHAs that require users to identify objects in images or solve puzzles, Swetrix CAPTCHA uses a **Proof of Work (PoW)** mechanism.++1. **Challenge Request**: When a user interacts with a protected form, the client requests a challenge from the Swetrix server.+2. **PoW Calculation**: The client-side script performs a cryptographic calculation (Proof of Work) in the background. This requires a small amount of computational power from the user's device, which is trivial for a legitimate user but computationally expensive for bots trying to spam at scale.+3. **Verification**: The solution to the PoW challenge is sent back to the server for verification.++This approach provides a seamless user experience (no more "select all traffic lights") while effectively deterring automated bots.You can find the demonstration of the CAPTCHA widget [here](https://captcha.swetrix.com/demo).diff --git a/docs/docs/features/ask-ai.md b/docs/docs/features/ask-ai.mdnew file mode 100644index 000000000..29c8d5846--- /dev/null+++ b/docs/docs/features/ask-ai.md@@ -0,0 +1,31 @@+---+title: Ask AI+slug: /features/ask-ai+---++import useBaseUrl from '@docusaurus/useBaseUrl';++Ask AI is a powerful feature that allows you to query your analytics data using natural language. Instead of manually filtering and analyzing complex datasets, you can simply ask a question and get immediate insights.++## How it works++Ask AI uses advanced language models to understand your questions and translate them into queries against your analytics data. It can help you find trends, anomalies, and specific metrics without needing to know the underlying query language or navigate through multiple dashboard views.++<img alt="Ask AI" src={useBaseUrl('img/features/ask-ai.png')} />++## Examples++You can ask questions like:++- "How many unique visitors did we have last week?"+- "What is the most popular page in the US?"+- "Compare the conversion rate of mobile vs. desktop users."+- "Show me a breakdown of traffic sources for the 'Signup' event."++## Usage++1. Navigate to the **Ask AI** tab in your project dashboard.+2. Type your question in the input box.+3. Review the generated answer and data visualization.++Ask AI is designed to make data accessibility easier for everyone on your team, regardless of their technical expertise.diff --git a/docs/docs/features/experiments.md b/docs/docs/features/experiments.mdnew file mode 100644index 000000000..2cb04a7bc--- /dev/null+++ b/docs/docs/features/experiments.md@@ -0,0 +1,57 @@+---+title: Experiments (A/B Testing)+slug: /features/experiments+---++import useBaseUrl from '@docusaurus/useBaseUrl';++Experiments (A/B Testing) allow you to test different variations of your application to see which one performs better. You can use experiments to optimize conversion rates, user engagement, and other key metrics.++## Overview++With Swetrix Experiments, you can:++- Create experiments with multiple variants (e.g., Control vs. Variant A vs. Variant B).+- Define goals to measure success.+- Analyze the results to determine the winning variant.++## Client-Side Implementation++To use experiments in your application, you can use the Swetrix tracking script.++### Fetching all experiments++```javascript+import { getExperiments } from 'swetrix'++const experiments = await getExperiments()+// Returns: { 'experiment-id-1': 'variant-a', 'experiment-id-2': 'control' }+```++### Getting a specific experiment variant++```javascript+import { getExperiment } from 'swetrix'++const variant = await getExperiment('checkout-redesign')++if (variant === 'new-checkout') {+ // Show new checkout flow+} else {+ // Show control (original) checkout+}+```++### Attribution++When a user participates in an experiment (i.e., they are assigned a variant), Swetrix automatically tracks this assignment. Subsequent events and pageviews are attributed to the assigned variant, allowing you to measure the impact of the experiment on your metrics.++## Managing Experiments++You can create and manage your experiments in the **Experiments** tab of your project dashboard.++<img alt="Experiments list" src={useBaseUrl('img/features/experiments-list.png')} />++You can also see how your experiments are performing by clicking on the Results button.++<img alt="Experiment results" src={useBaseUrl('img/features/experiment.png')} />diff --git a/docs/docs/features/feature-flags.md b/docs/docs/features/feature-flags.mdnew file mode 100644index 000000000..0bfa85d0f--- /dev/null+++ b/docs/docs/features/feature-flags.md@@ -0,0 +1,65 @@+---+title: Feature Flags+slug: /features/feature-flags+---++import useBaseUrl from '@docusaurus/useBaseUrl';++Feature flags allow you to toggle features on and off for your users without deploying new code. This is useful for rolling out new features gradually, testing in production, or quickly disabling a feature if something goes wrong.++## Overview++With Swetrix Feature Flags, you can:++- Create flags in your dashboard.+- Assign rules to target specific user segments (e.g., by country, browser, or custom attributes).+- Roll out features to a percentage of your users.++## Client-Side Implementation++To use feature flags in your application, you can use the Swetrix tracking script.++### Fetching all flags++```javascript+import { getFeatureFlags } from 'swetrix'++const flags = await getFeatureFlags()++if (flags['new-checkout']) {+ // Show new checkout flow+}+```++### Getting a single flag++```javascript+import { getFeatureFlag } from 'swetrix'++const isEnabled = await getFeatureFlag('dark-mode', {+ // Optional: provide a specific profileId if known,+ // otherwise it uses the one from init() or generates an anonymous one.+ profileId: 'user-123',+})++if (isEnabled) {+ // Enable dark mode+}+```++### Caching++Feature flags are cached for 5 minutes by default to minimize network requests. You can force a refresh or clear the cache if needed:++```javascript+import { clearFeatureFlagsCache } from 'swetrix'++// Clear cache to force a fresh fetch on next call+clearFeatureFlagsCache()+```++## Managing Flags++You can create and manage your feature flags in the **Feature Flags** tab of your project dashboard.++<img alt="Feature flags list" src={useBaseUrl('img/features/feature-flags-list.png')} />diff --git a/docs/docs/features/revenue-tracking.md b/docs/docs/features/revenue-tracking.mdnew file mode 100644index 000000000..263eddca0--- /dev/null+++ b/docs/docs/features/revenue-tracking.md@@ -0,0 +1,32 @@+---+title: Revenue Tracking+slug: /features/revenue-tracking+---++Swetrix allows you to track revenue generated by your users, giving you insights into your project's financial performance alongside your analytics data.++## Overview++Revenue tracking enables you to:++- Monitor total revenue and trends over time.+- Attribute revenue to specific users (profiles).+- Integrate seamlessly with payment providers like Stripe and Paddle.++## Configuration++To set up revenue tracking:++1. Go to your project dashboard.+2. Navigate to **Project Settings**.+3. Click on the **Revenue** tab.++Here you can connect your Stripe or Paddle account. Once connected, Swetrix will automatically start tracking revenue events associated with your project.++## User Attribution++To correctly attribute revenue to specific users, you need to ensure that the user's `profileId` is consistent between Swetrix and your payment provider.++Swetrix generates a `profileId` for users (or you can supply your own). When a user makes a purchase, you should ensure that this identifier is passed to the payment provider so that the revenue event can be linked back to the correct user profile in Swetrix.++For more details on handling `profileId` in your application, refer to the [Script Reference](/swetrix-js-reference#init).diff --git a/docs/docs/script-reference.md b/docs/docs/script-reference.mdindex 43f8d0c07..50785a100 100644--- a/docs/docs/script-reference.md+++ b/docs/docs/script-reference.md@@ -9,7 +9,7 @@ The Swetrix.js is a highly customisable tracking script. The following is a refe## init()-This fuction is used to initialise the analytics.+This function is used to initialise the analytics.Basically you're letting the script know which project do you want to use it with, as well as specifying your custom parameters if needed.It takes two arguments:@@ -25,6 +25,7 @@ swetrix.init('YOUR_PROJECT_ID', {disabled: false,respectDNT: false,apiURL: 'https://api.swetrix.com/log',+ profileId: 'user-123',})```@@ -34,6 +35,7 @@ swetrix.init('YOUR_PROJECT_ID', {| disabled | When set to true, the tracking library won't send any data to server.<br />Useful for development purposes when this value is set based on '.env' var. | `false` || respectDNT | By setting this flag to true, we will not collect ANY kind of data about the user with the DNT setting. <br />This setting is not true by default because our service anonymises all incoming data and does not pass it on to any third parties under any circumstances. | `false` || apiURL | Set a custom URL of the API server (for selfhosted variants of Swetrix). | `'https://api.swetrix.com/log'` |+| profileId | Optional profile ID for long-term user tracking (MAU/DAU). If set, it will be used for all pageviews and events unless overridden per-call. This allows you to track users across sessions and devices. | `undefined` |## track()@@ -52,6 +54,7 @@ Here's an example of how to use this function with all the available options:swetrix.track({ev: 'YOUR_EVENT_NAME',unique: false,+ profileId: 'user-123',})```@@ -60,6 +63,7 @@ swetrix.track({| ev | The event identifier you want to track.<br />This has to be a string, which:<br />1. Contains only English letters (a-Z A-Z), numbers (0-9), underscores (\_) and dots (.).<br />2. Is fewer than 64 characters.<br />3. Starts with an English letter. | REQUIRED PARAMETER || unique | If true, only 1 event with the same ID will be saved per user session.<br />The principle of this parameter is similar to page views and unique views. | `false` || meta | An object that contains event-related metadata. The values of the object must be a primitive type (string, number, boolean, null) which will be converted to a string, the maximum number of keys allowed is `20` and the total length of the values combined must be less than `1000` characters.<br /> This feature is useful if you want to track additional data about your custom events, for example the custom event name might be `Sign up` and the metadata might be `{ affiliate: 'Yes', footer: 'No' }`. | `{}` |+| profileId | Optional profile ID for long-term user tracking. Overrides the global profileId if set. | `undefined` |## trackViews()@@ -77,6 +81,7 @@ Such data will include the following params if available:9. `co` - UTM content ('utm_content' GET param).10. `pg` - the page user currently views (e.g. /hello).11. `perf` - an object which contains performance metrics related to the page load.+12. `profileId` - the profile ID if set.On the server side we also gather users IP Address and User Agent. This data is used to detect whether the page view is unique or not.@@ -99,7 +104,7 @@ swetrix.trackViews({| Name | Description | Default value || --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- || unique | If true, only unique events will be saved. This param is useful when tracking single-page landing websites. | `false` |-| callback | A callback used to edit / prevent sending pageviews.<br />It accepts an object with pageview event data as a parameter which has the following structure: <br />lc: string \| undefined<br />tz: string \| undefined<br />ref: string \| undefined<br />so: string \| undefined<br />me: string \| undefined<br />ca: string \| undefined<br />meta: object \| undefined ("object" should contain string values only)<br />pg: string \| null \| undefined<br /><br />The callback is supposed to return the edited payload or `false` to prevent sending the pageview. If `true` is returned, the payload will be sent as-is. | `undefined` |+| callback | A callback used to edit / prevent sending pageviews.<br />It accepts an object with pageview event data as a parameter which has the following structure: <br />lc: string \| undefined<br />tz: string \| undefined<br />ref: string \| undefined<br />so: string \| undefined<br />me: string \| undefined<br />ca: string \| undefined<br />meta: object \| undefined ("object" should contain string values only)<br />pg: string \| null \| undefined<br />profileId: string \| undefined<br /><br />The callback is supposed to return the edited payload or `false` to prevent sending the pageview. If `true` is returned, the payload will be sent as-is. | `undefined` || heartbeatOnBackground | Send Heartbeat requests when the website tab is not active in the browser.<br />Setting this to `true` means that users who opened your website in inactive browser tab or window will not be counted into users realtime statistics.<br />Setting this to true is usually useful for services like Spotify or Youtube. | `false` || hash | Set to `true` to enable hash-based routing. For example if you have pages like `/#/path` or want to track pages like `/path#hash`. | `false` || search | Set to `true` to enable search-based routing. For example if you have pages like `/path?search`. Although it's not recommended in most cases, you can set both `hash` and `search` to `true` at the same time, in which case the pageview event will be fired when either the hash or the search part of the URL changes (again, both the hash and the search are sent to the server). | `false` |@@ -142,6 +147,7 @@ swetrix.pageview({author: 'Andrii',type: 'story',},+ profileId: 'user-123',},})```@@ -218,3 +224,87 @@ swetrix.trackError({},})```++## getFeatureFlags()++Fetches all feature flags for the project. Results are cached for 5 minutes by default.++```javascript+const flags = await swetrix.getFeatureFlags({+ profileId: 'user-123'+})+// Returns: { 'flag-1': true, 'flag-2': false }+```++Arguments:+1. `options` (optional): `{ profileId?: string }`+2. `forceRefresh` (optional): `boolean` - If true, bypasses the cache.++## getFeatureFlag()++Gets the value of a single feature flag.++```javascript+const isEnabled = await swetrix.getFeatureFlag('new-feature', {+ profileId: 'user-123'+})+```++Arguments:+1. `key`: `string` - The feature flag key.+2. `options` (optional): `{ profileId?: string }`+3. `defaultValue` (optional): `boolean` - Default value if flag not found (default: `false`).++## clearFeatureFlagsCache()++Clears the cached feature flags and experiments, forcing a fresh fetch on the next call.++```javascript+swetrix.clearFeatureFlagsCache()+```++## getExperiments()++Fetches all A/B test experiments for the project.++```javascript+const experiments = await swetrix.getExperiments({+ profileId: 'user-123'+})+// Returns: { 'experiment-1': 'variant-a', 'experiment-2': 'control' }+```++Arguments:+1. `options` (optional): `{ profileId?: string }`+2. `forceRefresh` (optional): `boolean` - If true, bypasses the cache.++## getExperiment()++Gets the variant key for a specific A/B test experiment.++```javascript+const variant = await swetrix.getExperiment('checkout-redesign', {+ profileId: 'user-123'+})+```++Arguments:+1. `experimentId`: `string` - The experiment ID.+2. `options` (optional): `{ profileId?: string }`+3. `defaultVariant` (optional): `string | null` - Default variant if not found (default: `null`).++## getProfileId()++Gets the anonymous profile ID for the current visitor. If `profileId` was set via `init`, returns that. Otherwise, requests server to generate one from IP/UA hash. This ID can be used for revenue attribution.++```javascript+const profileId = await swetrix.getProfileId()+```++## getSessionId()++Gets the current session ID for the visitor. Session IDs are generated server-side based on IP and user agent.++```javascript+const sessionId = await swetrix.getSessionId()+```diff --git a/docs/sidebars.js b/docs/sidebars.jsindex 72697ac63..bae09e94b 100644--- a/docs/sidebars.js+++ b/docs/sidebars.js@@ -23,6 +23,12 @@ module.exports = {},'troubleshooting',],+ Features: [+ 'features/revenue-tracking',+ 'features/ask-ai',+ 'features/feature-flags',+ 'features/experiments',+ ],'Site settings': ['sitesettings/how-to-access-site-settings','sitesettings/how-to-invite-users-to-your-website',diff --git a/docs/static/img/features/ask-ai.png b/docs/static/img/features/ask-ai.pngnew file mode 100644index 000000000..aba11e62cBinary files /dev/null and b/docs/static/img/features/ask-ai.png differdiff --git a/docs/static/img/features/experiment.png b/docs/static/img/features/experiment.pngnew file mode 100644index 000000000..cd17a6f5cBinary files /dev/null and b/docs/static/img/features/experiment.png differdiff --git a/docs/static/img/features/experiments-list.png b/docs/static/img/features/experiments-list.pngnew file mode 100644index 000000000..df2e8e9d2Binary files /dev/null and b/docs/static/img/features/experiments-list.png differdiff --git a/docs/static/img/features/feature-flags-list.png b/docs/static/img/features/feature-flags-list.pngnew file mode 100644index 000000000..2b30f0f06Binary files /dev/null and b/docs/static/img/features/feature-flags-list.png differ