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 page or reach us at our contact page.
Installation
npm install @swetrix/node
Usage
Set up
// alternatively you can use the import syntaxconst { Swetrix } = require('@swetrix/node')
const swetrix = newSwetrix('YOUR_PROJECT_ID')
The Swetrix constructor accepts 2 params: project ID (string) and options object.
Options object is the following (it's similar to what the main Swetrix tracking library looks like):
exportinterfaceLibOptions {
/**
* When set to `true`, all tracking logs will be printed to console.
*/
devMode?: 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/**
* Optional profile ID for long-term user tracking.
* If set, it will be used for all pageviews and events unless overridden per-call.
*/
profileId?: string
}
Important: Async/Await Support
All tracking methods in this SDK return Promises, allowing you to await them if needed:
// You can await tracking callsawait swetrix.trackPageView(ip, userAgent, { pg: '/home' })
await swetrix.track(ip, userAgent, { ev: 'button_click' })
// Or fire-and-forget (no await)
swetrix.trackPageView(ip, userAgent, { pg: '/home' })
Tracking pageviews
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!
You can read about it in details on our Events API documentation page.
Tracking pageviews can be done by calling the following function:
The pageview object is described by the following interfaces:
exportinterfaceTrackPageViewOptions {
/**
* 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/** 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/** Pageview-related metadata object with string values. */
meta?: {
[key: string]: string | number | boolean | null | undefined
}
/** Optional profile ID for long-term user tracking. Overrides the global profileId if set. */
profileId?: string
}
exportinterfacePerformanceMetrics {
/* 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
}
Tracking custom events
You can track custom events by calling track function, the syntax is similar to tracking pageviews:
The custom event object is described by the following interface:
exportinterfaceTrackEventOptions {
/**
* 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/** Event-related metadata object with string values. */
meta?: {
[key: string]: string | number | boolean | null | undefined
}
/** Optional profile ID for long-term user tracking. Overrides the global profileId if set. */
profileId?: string
}
Tracking errors
You can also track error events by calling trackError function, the syntax is similar to tracking pageviews:
The error object is described by the following interface:
exportinterfaceTrackErrorOptions {
/**
* Error name (e.g. ParseError).
*/name: string/**
* Error message (e.g. Malformed input).
*/
message?: string | null/**
* On what line in your code did the error occur (e.g. 1520)
*/
lineno?: number | null/**
* On what column in your code did the error occur (e.g. 26)
*/
colno?: number | null/**
* In what file did the error occur (e.g. https://example.com/broken.js)
*/
filename?: string | null/**
* Stack trace of the error.
*/
stackTrace?: string | null/**
* Visitor's timezone (used as a backup in case IP geolocation fails).
*/
tz?: string/** A locale of the user (e.g. en-US or uk-UA) */
lc?: string/** A page to record the error event for (e.g. /home) */
pg?: string/** Error-related metadata object with string values. */
meta?: {
[key: string]: string | number | boolean | null | undefined
}
}
Heartbeat events
Heartbeat 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.
You can send heartbeat events by calling the following function:
await swetrix.heartbeat('192.155.52.12', 'Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0')
Make sure to pass your website visitors IP address and User Agent instead of these example values.
Feature Flags
Feature flags allow you to control feature rollouts to your users. You can evaluate flags server-side based on user context.
Getting all feature flags
const flags = await swetrix.getFeatureFlags(
'192.155.52.12',
'Mozilla/5.0...',
{ profileId: 'user-123' }, // optional
)
if (flags['new-checkout']) {
// Show new checkout flow
}
Getting a single feature flag
const isEnabled = await swetrix.getFeatureFlag(
'dark-mode',
'192.155.52.12',
'Mozilla/5.0...',
{ profileId: 'user-123' }, // optionalfalse, // default value if flag not found
)
if (isEnabled) {
// Enable dark mode
}
Clearing the feature flags cache
Feature flags are cached for 5 minutes by default. You can force a refresh:
// Clear the cache
swetrix.clearFeatureFlagsCache()
// Or force refresh on next callconst flags = await swetrix.getFeatureFlags(ip, userAgent, options, true)
A/B Testing (Experiments)
Run A/B tests and get the assigned variant for each user.
We found that @swetrix/node demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.It has 1 open source maintainer collaborating on the project.
Package last updated on 10 Feb 2026
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.