Skip to content

📈 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!

initial commit

Blue Mousea5ed0794b58b
diff --git a/.github/funding.yml b/.github/funding.yml
new file mode 100644
index 000000000..f7cbd9642
--- /dev/null
+++ b/.github/funding.yml
@@ -0,0 +1,2 @@
+github: swetrix
+ko_fi: andriir
diff --git a/README.md b/README.md
new file mode 100644
index 000000000..dac3edc13
--- /dev/null
+++ b/README.md
@@ -0,0 +1,16 @@
+<img src="https://swetrix.com/assets/logo_blue.png" alt="" height="80" />
+
+# @swetrix/node
+## Swetrix NodeJS integration
+
+This repository contains the analytics script for server-side tracking of your website.
+
+Feel free to contribute to the source code by opening a pull requests. \
+For any questions, you can open an issue ticket, refer to our [FAQs](https://swetrix.com/#faq) page or reach us at our [contact page](https://swetrix.com/contact).
+
+# Selfhosted API
+If you are selfhosting the [Swetrix-API](https://github.com/Swetrix/swetrix-api), be sure to point the `apiUrl` parameter to: `https://yourapiinstance.com/log`
+
+# Donate
+You can support the project by donating us at https://ko-fi.com/andriir \
+We can only run our services by once again asking for your financial support!
diff --git a/package.json b/package.json
new file mode 100644
index 000000000..cb24cb596
--- /dev/null
+++ b/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "@swetrix/node",
+ "version": "1.0.0",
+ "description": "Swetrix NodeJS server-side tracking module",
+ "main": "dist/swetrix.cjs.js",
+ "module": "dist/swetrix.es5.js",
+ "esnext": "dist/esnext/index.js",
+ "typings": "dist/esnext/index.d.ts",
+ "scripts": {
+ "prebuild": "rimraf dist",
+ "prepublish": "npm run build",
+ "build": "rollup -c && tsc -p tsconfig.esnext.json",
+ "start": "rollup -c -w",
+ "tsc": "tsc -p tsconfig.esnext.json"
+ },
+ "keywords": [
+ "swetrix",
+ "analytics",
+ "monitoring",
+ "metrics",
+ "privacy"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/Swetrix/swetrix-js.git"
+ },
+ "author": "Andrii R. <[email protected]>",
+ "funding": "https://ko-fi.com/andriir",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/Swetrix/swetrix-js/issues"
+ },
+ "homepage": "https://swetrix.com/docs",
+ "dependencies": {
+ "@types/node": "^20.5.9",
+ "tslib": "^2.6.2"
+ },
+ "devDependencies": {
+ "@rollup/plugin-commonjs": "^25.0.4",
+ "@rollup/plugin-node-resolve": "^15.2.1",
+ "rimraf": "^4.4.1",
+ "rollup": "^2.79.1",
+ "rollup-plugin-node-resolve": "^5.2.0",
+ "rollup-plugin-sourcemaps": "^0.6.3",
+ "rollup-plugin-typescript2": "^0.35.0",
+ "typescript": "^5.2.2"
+ }
+}
diff --git a/rollup.config.js b/rollup.config.js
new file mode 100644
index 000000000..0bd5fd267
--- /dev/null
+++ b/rollup.config.js
@@ -0,0 +1,18 @@
+import { nodeResolve } from '@rollup/plugin-node-resolve'
+import commonjs from '@rollup/plugin-commonjs'
+import sourceMaps from 'rollup-plugin-sourcemaps'
+import typescript from 'rollup-plugin-typescript2'
+import pkg from './package.json'
+
+export default [
+ {
+ input: 'src/index.ts',
+ output: [
+ { file: pkg.main, format: 'cjs' },
+ { file: pkg.module, format: 'es' },
+ ],
+ plugins: [
+ typescript(), nodeResolve(), commonjs(), sourceMaps(),
+ ]
+ },
+]
diff --git a/src/Lib.ts b/src/Lib.ts
new file mode 100644
index 000000000..e69de29bb
diff --git a/src/index.ts b/src/index.ts
new file mode 100644
index 000000000..b39104123
--- /dev/null
+++ b/src/index.ts
@@ -0,0 +1,211 @@
+import { isInBrowser } from './utils'
+
+export interface LibOptions {
+ /**
+ * When set to `true`, all tracking logs will be printed to console and localhost events will be sent to server.
+ */
+ debug?: boolean
+
+ /**
+ * When set to `true`, the tracking library won't send any data to server.
+ * Useful for development purposes when this value is set based on `.env` var.
+ */
+ disabled?: boolean
+
+ /** Set a custom URL of the API server (for selfhosted variants of Swetrix). */
+ apiURL?: string
+
+ /**
+ * If set to `true`, only unique events will be saved.
+ * This param is useful when tracking single-page landing websites.
+ */
+ unique?: boolean
+
+ /** A list of Regular Expressions or string pathes to ignore. */
+ ignore?: Array<string | RegExp>
+
+ /** Do not send paths from ignore list to API. If set to `false`, the page view information will be sent to the Swetrix API, but the page will be displayed as a 'Redacted page' in the dashboard. */
+ doNotAnonymise?: boolean
+}
+
+export interface TrackEventOptions {
+ /**
+ * An event identifier you want to track. This has to be a string, which:
+ * 1. Contains only English letters (a-Z A-Z), numbers (0-9), underscores (_) and dots (.).
+ * 2. Is fewer than 64 characters.
+ * 3. Starts with an English letter.
+ */
+ ev: string
+
+ /** If set to true, only 1 custom event will be saved per session */
+ unique?: boolean
+
+ /** A page that user sent data from (e.g. /home) */
+ page?: string
+
+ /** A locale of the user (e.g. en-US or uk-UA) */
+ lc?: string
+
+ /** A referrer URL (e.g. https://example.com/) */
+ ref?: string
+
+ /** A source of the event (e.g. ref, source or utm_source GET parameter) */
+ so?: string
+
+ /** A medium of the event (e.g. utm_medium GET parameter) */
+ me?: string
+
+ /** A campaign of the event (e.g. utm_campaign GET parameter) */
+ ca?: string
+}
+
+export interface PerformanceMetrics {
+ /* DNS Resolution time */
+ dns?: number
+
+ /* TLS handshake time */
+ tls?: number
+
+ /* Connection time */
+ conn?: number
+
+ /* Response Time (Download) */
+ response?: number
+
+ /* Browser rendering the HTML page time */
+ render?: number
+
+ /* DOM loading timing */
+ dom_load?: number
+
+ /* Page load timing */
+ page_load?: number
+
+ /* Time to first byte */
+ ttfb?: number
+}
+
+export interface TrackPageViewOptions {
+ /**
+ * Visitor's timezone (used as a backup in case IP geolocation fails). I.e. if it's set to Europe/Kiev and IP geolocation fails, we will set the country of this entry to Ukraine)
+ */
+ tz?: string
+
+ /** A page to record the pageview event for (e.g. /home). All our scripts send the pg string with a slash (/) at the beginning, it's not a requirement but it's best to do the same so the data would be consistent when used together with our official scripts */
+ pg?: string
+
+ /** Previous page user was on */
+ prev?: string
+
+ /** A locale of the user (e.g. en-US or uk-UA) */
+ lc?: string
+
+ /** A referrer URL (e.g. https://example.com/) */
+ ref?: string
+
+ /** A source of the pageview (e.g. ref, source or utm_source GET parameter) */
+ so?: string
+
+ /** A medium of the pageview (e.g. utm_medium GET parameter) */
+ me?: string
+
+ /** A campaign of the pageview (e.g. utm_campaign GET parameter) */
+ ca?: string
+
+ /** If set to true, only unique visits will be saved */
+ unique?: boolean
+
+ /** An object with performance metrics related to the page load. See Performance metrics for more details */
+ perf?: PerformanceMetrics
+}
+
+const DEFAULT_API_HOST = 'https://api.swetrix.com/log'
+
+export class Lib {
+ constructor(private projectID: string, private options?: LibOptions) {
+ this.heartbeat = this.heartbeat.bind(this)
+ }
+
+ track(event: TrackEventOptions): void {
+ if (!this.canTrack()) {
+ return
+ }
+
+ const data = {
+ pid: this.projectID,
+ ...event,
+ }
+ this.sendRequest('custom', data)
+ }
+
+ trackPageView(pageview?: TrackPageViewOptions) {
+ if (!this.canTrack()) {
+ return
+ }
+
+ const { pg } = pageview || {}
+
+ const shouldIgnore = this.checkIgnore(pg)
+
+ if (shouldIgnore && this.options?.doNotAnonymise) return
+
+ const data = {
+ pid: this.projectID,
+ ...(pageview || {}),
+ }
+
+ this.sendRequest('', data)
+ }
+
+ heartbeat(): void {
+ if (!this.canTrack()) {
+ return
+ }
+
+ const data = {
+ pid: this.projectID,
+ }
+ this.sendRequest('heartbeat', data)
+ }
+
+ private checkIgnore(path?: string): boolean {
+ const ignore = this.options?.ignore
+
+ if (Array.isArray(ignore)) {
+ for (let i = 0; i < ignore.length; ++i) {
+ if (ignore[i] === path) return true
+ // @ts-ignore
+ if (ignore[i] instanceof RegExp && ignore[i].test(path)) return true
+ }
+ }
+ return false
+ }
+
+ private debug(message: string): void {
+ if (this.options?.debug) {
+ console.log('[Swetrix]', message)
+ }
+ }
+
+ private canTrack(): boolean {
+ if (this.options?.disabled) {
+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.')
+ return false
+ }
+
+ if (isInBrowser()) {
+ this.debug('Tracking disabled: script runs in browser environment.')
+ return false
+ }
+
+ return true
+ }
+
+ private sendRequest(path: string, body: object): void {
+ const host = this.options?.apiURL || DEFAULT_API_HOST
+ const req = new XMLHttpRequest()
+ req.open('POST', `${host}/${path}`, true)
+ req.setRequestHeader('Content-Type', 'application/json')
+ req.send(JSON.stringify(body))
+ }
+}
diff --git a/src/utils.ts b/src/utils.ts
new file mode 100644
index 000000000..6d57aba7d
--- /dev/null
+++ b/src/utils.ts
@@ -0,0 +1,47 @@
+const findInSearch = (exp: RegExp): string | undefined => {
+ const res = location.search.match(exp)
+ return (res && res[2]) || undefined
+}
+
+const utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/
+const utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/
+const utmMediumRegex = /[?&](utm_medium)=([^?&]+)/
+
+export const isInBrowser = () => {
+ return typeof document !== 'undefined'
+}
+
+export const isLocalhost = () => {
+ return location?.hostname === 'localhost' || location?.hostname === '127.0.0.1' || location?.hostname === ''
+}
+
+export const isAutomated = () => {
+ return navigator?.webdriver
+}
+
+export const getLocale = () => {
+ return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language
+}
+
+export const getTimezone = () => {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone
+ } catch (e) {
+ return
+ }
+}
+
+export const getReferrer = (): string | undefined => {
+ return document.referrer || undefined
+}
+
+export const getUTMSource = () => findInSearch(utmSourceRegex)
+
+export const getUTMMedium = () => findInSearch(utmMediumRegex)
+
+export const getUTMCampaign = () => findInSearch(utmCampaignRegex)
+
+export const getPath = (): string => {
+ // TODO: Maybe we should also include such data as location.hash or location.search
+ return location.pathname || ''
+}
diff --git a/tsconfig.esnext.json b/tsconfig.esnext.json
new file mode 100644
index 000000000..901fb91ab
--- /dev/null
+++ b/tsconfig.esnext.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "moduleResolution": "node",
+ "target": "es2020",
+ "module": "es2015",
+ "lib": ["dom"],
+ "strict": true,
+ "sourceMap": true,
+ "declaration": true,
+ "allowSyntheticDefaultImports": true,
+ "experimentalDecorators": true,
+ "emitDecoratorMetadata": true,
+ "outDir": "dist/esnext",
+ "typeRoots": ["node_modules/@types"]
+ },
+ "include": ["src"]
+}
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 000000000..3fe10f8db
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "moduleResolution": "node",
+ "target": "es5",
+ "module": "es2015",
+ "lib": ["es2015", "es2016", "es2017", "dom"],
+ "strict": true,
+ "allowSyntheticDefaultImports": true,
+ "experimentalDecorators": true,
+ "emitDecoratorMetadata": true,
+ "sourceMap": true,
+ "declaration": false,
+ "outDir": "dist/lib",
+ "typeRoots": ["node_modules/@types"]
+ },
+ "include": ["src"]
+}