{"id":23084303,"url":"https://github.com/swetrix/swetrix-node","last_synced_at":"2026-05-26T14:05:22.040Z","repository":{"id":193677944,"uuid":"689272800","full_name":"Swetrix/swetrix-node","owner":"Swetrix","description":"Swetrix NodeJS server-side tracking module","archived":false,"fork":false,"pushed_at":"2024-10-26T20:14:20.000Z","size":26,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-12-11T22:35:55.648Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Swetrix.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/funding.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"swetrix","ko_fi":"andriir"}},"created_at":"2023-09-09T09:43:31.000Z","updated_at":"2024-10-26T20:13:43.000Z","dependencies_parsed_at":null,"dependency_job_id":"5abddd86-3f9b-4aca-bd47-fa9bede746c6","html_url":"https://github.com/Swetrix/swetrix-node","commit_stats":null,"previous_names":["swetrix/swetrix-node"],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Swetrix%2Fswetrix-node","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Swetrix%2Fswetrix-node/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Swetrix%2Fswetrix-node/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Swetrix%2Fswetrix-node/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Swetrix","download_url":"https://codeload.github.com/Swetrix/swetrix-node/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":229988928,"owners_count":18155821,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-16T15:50:57.235Z","updated_at":"2026-05-26T14:05:22.027Z","avatar_url":"https://github.com/Swetrix.png","language":"TypeScript","funding_links":["https://github.com/sponsors/swetrix","https://ko-fi.com/andriir"],"categories":[],"sub_categories":[],"readme":"\u003cpicture\u003e\n  \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://swetrix.com/assets/logo_white.png\"\u003e\n  \u003cimg alt=\"\" src=\"https://swetrix.com/assets/logo_blue.png\" height=\"80\"\u003e\n\u003c/picture\u003e\n\n\u003e [!NOTE]\n\u003e This repository has been archived. Development has moved to the [Swetrix monorepo](https://github.com/Swetrix/swetrix) under [`packages/tracker-node`](https://github.com/Swetrix/swetrix/tree/main/packages/tracker-node). Please open issues and pull requests there instead.\n\n# `@swetrix/node` - Swetrix NodeJS integration\n\nThis repository contains the analytics script for server-side tracking of your website.\n\nFeel free to contribute to the source code by opening a pull requests. \\\nFor 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).\n\n# Installation\n\n`npm install @swetrix/node`\n\n# Usage\n\n## Set up\n\n```javascript\n// alternatively you can use the import syntax\nconst { Swetrix } = require('@swetrix/node')\n```\n\n```javascript\nconst swetrix = new Swetrix('YOUR_PROJECT_ID')\n```\n\nThe `Swetrix` constructor accepts 2 params: project ID (string) and options object.\\\nOptions object is the following (it's similar to what the main Swetrix tracking library looks like):\n\n```typescript\nexport interface LibOptions {\n  /**\n   * When set to `true`, all tracking logs will be printed to console.\n   */\n  devMode?: boolean\n\n  /**\n   * When set to `true`, the tracking library won't send any data to server.\n   * Useful for development purposes when this value is set based on `.env` var.\n   */\n  disabled?: boolean\n\n  /**\n   * Set a custom URL of the API server (for selfhosted variants of Swetrix).\n   */\n  apiURL?: string\n\n  /**\n   * If set to `true`, only unique events will be saved.\n   * This param is useful when tracking single-page landing websites.\n   */\n  unique?: boolean\n\n  /**\n   * Optional profile ID for long-term user tracking.\n   * If set, it will be used for all pageviews and events unless overridden per-call.\n   */\n  profileId?: string\n}\n```\n\n## Important: Async/Await Support\n\nAll tracking methods in this SDK return Promises, allowing you to await them if needed:\n\n```javascript\n// You can await tracking calls\nawait swetrix.trackPageView(ip, userAgent, { pg: '/home' })\nawait swetrix.track(ip, userAgent, { ev: 'button_click' })\n\n// Or fire-and-forget (no await)\nswetrix.trackPageView(ip, userAgent, { pg: '/home' })\n```\n\n## Tracking pageviews\n\n**To track pageviews, custom events and heartbeat events you have to pass your website visitors IP address and user agent, otherwise functionality like unique visitors or live visitors tracking will not work!**\\\nYou can read about it in details on our [Events API](https://docs.swetrix.com/events-api#unique-visitors-tracking) documentation page.\n\nTracking pageviews can be done by calling the following function:\n\n```javascript\nawait swetrix.trackPageView('192.155.52.12', 'Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0', {\n  lc: 'en-US',\n  pg: '/hi',\n  ref: 'https://www.swetrix.com/',\n})\n```\n\nIt accepts 3 arguments:\n\n- Client IP address\n- Client user agent\n- Pageview object\n\nThe pageview object is described by the following interfaces:\n\n```typescript\nexport interface TrackPageViewOptions {\n  /**\n   * 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)\n   */\n  tz?: string\n\n  /** 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 */\n  pg?: string\n\n  /** A locale of the user (e.g. en-US or uk-UA) */\n  lc?: string\n\n  /** A referrer URL (e.g. https://example.com/) */\n  ref?: string\n\n  /** A source of the pageview (e.g. ref, source or utm_source GET parameter) */\n  so?: string\n\n  /** A medium of the pageview (e.g. utm_medium GET parameter) */\n  me?: string\n\n  /** A campaign of the pageview (e.g. utm_campaign GET parameter) */\n  ca?: string\n\n  /** If set to true, only unique visits will be saved */\n  unique?: boolean\n\n  /** An object with performance metrics related to the page load. See Performance metrics for more details */\n  perf?: PerformanceMetrics\n\n  /** Pageview-related metadata object with string values. */\n  meta?: {\n    [key: string]: string | number | boolean | null | undefined\n  }\n\n  /** Optional profile ID for long-term user tracking. Overrides the global profileId if set. */\n  profileId?: string\n}\n\nexport interface PerformanceMetrics {\n  /* DNS Resolution time */\n  dns?: number\n\n  /* TLS handshake time */\n  tls?: number\n\n  /* Connection time */\n  conn?: number\n\n  /* Response Time (Download) */\n  response?: number\n\n  /* Browser rendering the HTML page time */\n  render?: number\n\n  /* DOM loading timing */\n  dom_load?: number\n\n  /* Page load timing */\n  page_load?: number\n\n  /* Time to first byte */\n  ttfb?: number\n}\n```\n\n## Tracking custom events\n\nYou can track custom events by calling `track` function, the syntax is similar to tracking pageviews:\n\n```javascript\nawait swetrix.track('192.155.52.12', 'Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0', {\n  ev: 'hello1234',\n})\n```\n\nThis function accepts 3 arguments:\n\n- Client IP address\n- Client user agent\n- Custom event object\n\nThe custom event object is described by the following interface:\n\n```typescript\nexport interface TrackEventOptions {\n  /**\n   * An event identifier you want to track. This has to be a string, which:\n   * 1. Contains only English letters (a-Z A-Z), numbers (0-9), underscores (_) and dots (.).\n   * 2. Is fewer than 64 characters.\n   * 3. Starts with an English letter.\n   */\n  ev: string\n\n  /** If set to true, only 1 custom event will be saved per session */\n  unique?: boolean\n\n  /** A page that user sent data from (e.g. /home) */\n  page?: string\n\n  /** A locale of the user (e.g. en-US or uk-UA) */\n  lc?: string\n\n  /** A referrer URL (e.g. https://example.com/) */\n  ref?: string\n\n  /** A source of the event (e.g. ref, source or utm_source GET parameter) */\n  so?: string\n\n  /** A medium of the event (e.g. utm_medium GET parameter) */\n  me?: string\n\n  /** A campaign of the event (e.g. utm_campaign GET parameter) */\n  ca?: string\n\n  /** Event-related metadata object with string values. */\n  meta?: {\n    [key: string]: string | number | boolean | null | undefined\n  }\n\n  /** Optional profile ID for long-term user tracking. Overrides the global profileId if set. */\n  profileId?: string\n}\n```\n\n## Tracking errors\n\nYou can also track error events by calling `trackError` function, the syntax is similar to tracking pageviews:\n\n```javascript\nawait swetrix.trackError('192.155.52.12', 'Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0', {\n  name: 'ParseError',\n  message: 'Malformed input',\n  lineno: 1520,\n  colno: 26,\n  filename: 'https://example.com/broken.js',\n})\n```\n\nThis function accepts 3 arguments:\n\n- Client IP address\n- Client user agent\n- Error object\n\nThe error object is described by the following interface:\n\n```typescript\nexport interface TrackErrorOptions {\n  /**\n   * Error name (e.g. ParseError).\n   */\n  name: string\n\n  /**\n   * Error message (e.g. Malformed input).\n   */\n  message?: string | null\n\n  /**\n   * On what line in your code did the error occur (e.g. 1520)\n   */\n  lineno?: number | null\n\n  /**\n   * On what column in your code did the error occur (e.g. 26)\n   */\n  colno?: number | null\n\n  /**\n   * In what file did the error occur (e.g. https://example.com/broken.js)\n   */\n  filename?: string | null\n\n  /**\n   * Stack trace of the error.\n   */\n  stackTrace?: string | null\n\n  /**\n   * Visitor's timezone (used as a backup in case IP geolocation fails).\n   */\n  tz?: string\n\n  /** A locale of the user (e.g. en-US or uk-UA) */\n  lc?: string\n\n  /** A page to record the error event for (e.g. /home) */\n  pg?: string\n\n  /** Error-related metadata object with string values. */\n  meta?: {\n    [key: string]: string | number | boolean | null | undefined\n  }\n}\n```\n\n## Heartbeat events\n\nHeartbeat events are used to determine if the user session is still active. This allows you to see the 'Live Visitors' counter in the Dashboard panel. It's recommended to send heartbeat events every 30 seconds. We also extend the session lifetime after receiving a pageview or custom event.\n\nYou can send heartbeat events by calling the following function:\n\n```javascript\nawait swetrix.heartbeat('192.155.52.12', 'Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0')\n```\n\nMake sure to pass your website visitors IP address and User Agent instead of these example values.\n\n## Feature Flags\n\nFeature flags allow you to control feature rollouts to your users. You can evaluate flags server-side based on user context.\n\n### Getting all feature flags\n\n```javascript\nconst flags = await swetrix.getFeatureFlags(\n  '192.155.52.12',\n  'Mozilla/5.0...',\n  { profileId: 'user-123' }, // optional\n)\n\nif (flags['new-checkout']) {\n  // Show new checkout flow\n}\n```\n\n### Getting a single feature flag\n\n```javascript\nconst isEnabled = await swetrix.getFeatureFlag(\n  'dark-mode',\n  '192.155.52.12',\n  'Mozilla/5.0...',\n  { profileId: 'user-123' }, // optional\n  false, // default value if flag not found\n)\n\nif (isEnabled) {\n  // Enable dark mode\n}\n```\n\n### Clearing the feature flags cache\n\nFeature flags are cached for 5 minutes by default. You can force a refresh:\n\n```javascript\n// Clear the cache\nswetrix.clearFeatureFlagsCache()\n\n// Or force refresh on next call\nconst flags = await swetrix.getFeatureFlags(ip, userAgent, options, true)\n```\n\n## A/B Testing (Experiments)\n\nRun A/B tests and get the assigned variant for each user.\n\n### Getting all experiments\n\n```javascript\nconst experiments = await swetrix.getExperiments(\n  '192.155.52.12',\n  'Mozilla/5.0...',\n  { profileId: 'user-123' }, // optional\n)\n\n// experiments = { 'exp-123': 'variant-a', 'exp-456': 'control' }\nconst checkoutVariant = experiments['checkout-experiment-id']\n\nif (checkoutVariant === 'new-checkout') {\n  showNewCheckout()\n} else {\n  showOriginalCheckout()\n}\n```\n\n### Getting a single experiment variant\n\n```javascript\nconst variant = await swetrix.getExperiment(\n  'checkout-redesign-experiment-id',\n  '192.155.52.12',\n  'Mozilla/5.0...',\n  { profileId: 'user-123' }, // optional\n  null, // default variant if experiment not found\n)\n\nif (variant === 'new-checkout') {\n  showNewCheckout()\n} else if (variant === 'control') {\n  showOriginalCheckout()\n} else {\n  // Experiment not running or user not included\n  showOriginalCheckout()\n}\n```\n\n### Clearing the experiments cache\n\n```javascript\nswetrix.clearExperimentsCache()\n```\n\n## Profile ID\n\nGet an anonymous profile ID for long-term user tracking. Useful for revenue attribution with payment providers.\n\n```javascript\nconst profileId = await swetrix.getProfileId('192.155.52.12', 'Mozilla/5.0...')\n\n// Pass to your payment provider for revenue attribution\n// e.g., Paddle Checkout customData: { swetrix_profile_id: profileId }\n```\n\nIf you set a `profileId` in the constructor options, it will be returned directly instead of generating one.\n\n## Session ID\n\nGet the current session ID for the visitor. Session IDs are generated server-side based on IP and user agent.\n\n```javascript\nconst sessionId = await swetrix.getSessionId('192.155.52.12', 'Mozilla/5.0...')\n\n// Use for revenue attribution or session-based tracking\n```\n\n## Revenue Attribution Example\n\nHere's a complete example of using profile and session IDs for revenue attribution with Paddle:\n\n```javascript\nconst swetrix = new Swetrix('YOUR_PROJECT_ID')\n\napp.get('/checkout', async (req, res) =\u003e {\n  const ip = req.ip\n  const userAgent = req.headers['user-agent']\n\n  const [profileId, sessionId] = await Promise.all([\n    swetrix.getProfileId(ip, userAgent),\n    swetrix.getSessionId(ip, userAgent),\n  ])\n\n  res.json({\n    checkoutConfig: {\n      // ... your checkout configuration\n      customData: {\n        swetrix_profile_id: profileId,\n        swetrix_session_id: sessionId,\n      },\n    },\n  })\n})\n```\n\n# Selfhosted API\n\nIf you are selfhosting the [Swetrix-API](https://github.com/Swetrix/swetrix-api), be sure to point the `apiURL` parameter to: `https://yourapiinstance.com/log`\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fswetrix%2Fswetrix-node","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fswetrix%2Fswetrix-node","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fswetrix%2Fswetrix-node/lists"}