0.0.24 • Published 1 month ago

saasco-analytics v0.0.24

Weekly downloads
-
License
-
Repository
-
Last release
1 month ago

Saasco is a platform of saas apps where members only pay the infrastructure cost of what they use. As a result Saasco apps are up to 99% cheaper than traditional saas products.

The analytics package makes it easy for javascript projects to track website activity. Analytics is a core feature of Saasco and is used to power many other apps.


🔒 Privacy

By default Saasco is privacy friendly, using no cookies and obscuring all activity behind Anonymous IDs. However if you want to power more complex user tracking you can identify users and then all events they do will be attributed to them in your CRM. This can assist with customer support but also for things like drip campaigns and other marketing activities.

Getting Started:

Install by running: npm install saasco-analytics

Copy your Project ID from the project settings page in Saasco: https://saasco.com/your-project/settings/project

Then import Analytics and initiate the lib with your Project ID.

import { Analytics } from 'saasco-analytics';

// Initiate the lib
export const analytics = new Analytics({ projectId: "YOUR-PROJECT-ID" });

Naming Conflict

Because “Analytics” is a common name for analytics tools you can simply import with a different name such as “SaascoAnalytics” to avoid conflicts.

For example:

import { Analytics as SaascoAnalytics } from 'saasco-analytics';

// Initiate the lib
const saascoAnalytics = new SaascoAnalytics({ projectId: "YOUR-PROJECT-ID" });

// Track an event
saascoAnalytics.track('Something happened');

Automatic Page View Tracking

When you initial the lib live above Saasco will automatically start tracking all page views in your app. There is no other configuration. It will automatically track url changes, even for SPAs like NextJs and Vue. You can also manually track pages by opting our of automatic page tracking. For most use cases you don't need to do this.

Tracking Events

With events you can track custom actions users are taking on your site with event properties.

Each event has 2 components:

Name - this is the name of the action that was taken.

We like to follow segments Object Action Framework for naming events.

Properties - This is an object with the values of the event. Such as a the value, currency, or query.

We currently have limited support for properties, but in the future we will support complex querying and actions based on event properties.

// Import analytics
import { analytics } from '../your-analytics';

// Track an event
analytics.track("Searched Movies");

// Track an event with properties
analytics.track("Searched Movies", {
	query:"batman",
	sortBy:"relevancy"
});

Identifying Users

By default Saasco does not track any identifiable data about users, just anonymous user ids and session ids. However if you want to tie events to users you can identify users which will connect events to users in your CRM and power tools like drip campaigns and customer support.

To do this just identify a user with their DistinctId (usually the user ID from your database) and then any properties on the user.

// Import analytics
import { analytics } from '../your-analytics';

// Inside your user logged in function identify a user
// You should only identify users when they login, or their properties change
function signedIn(){
	// Identify a user
	analytics.identify("USER-ID-FROM-YOUR-DB", {
		// Any user properties you want to record with the user
		name:"Tony Hawk",
		email:"tony@xgames.com",
		bestTrick: 900
	});
}

// When a user logs out you can unidentify by identify null
function signedOut(){
	analtyics.identify(null)
}

Identifying users who don't have an ID

Often times you have a users contact details before they sign up for your site. This could be part of the signup flow, or if they were to subscribe to marketing emails before they sign up as a customer

Saasco allows identifying users without an id by simply skipping the ID part of the identify call. This will add contacts to the CRM for email marketing and other tools before users register.

For example:

// Identify a user only by their email
analytics.identify({
    name:"Tony Hawk",
    email:"tony@xgames.com",
    bestTrick: 900
});

By doing this users will get tracked and added to your contacts, and as soon as they do login, assuming they use the same email address, all their properties will be connected.

Soft vs Full identify

When users are identified without a ID we call this is a "Soft Identify". Users who are soft identified can also be called "Leads". Once a user signs up and you identify them with an ID they will be fully registered and can be called "Customers"

In the CRM when you identify a user, either soft or full, they become a contact. The type of the contact depends on whether they were fully identified, "Leads" are soft and "Customers" are full.

Debugging and Dev

When setting up Saasco analytics you probably want to exclude your local environment.

To do so simply turn on dev mode.

export const analytics = new Analytics({
    projectId: 'YOUR-PROJECT-ID',

    // use an env to only set enabled to true on production
    enabled: process.env['NODE_ENV'] === 'production',
});

Debugging

You can turn on debugging when you initiate the repo or by running analytics.debug(true) in your code or the browser.

export const analytics = new Analytics({
    projectId: 'YOUR-PROJECT-ID',
    enabled: process.env['NODE_ENV'] === 'production',
    // Set to true to console log analytics events.
    // This works even when enabled is false - it just wont send the data
    debug: true,
});

You can also enable debug mode by calling analytics.debug(true) anywhere in your code.

analytics.debug(true);
// will console log "debug mode activated"

Reserved Properties

Saasco has reserved some properties that have semantic meanings for contacts and, and will handle them in special ways. For example, Saasco always expects email to be a string of the user’s email address, this is important for when sending emails using the marketing app.

Reserved Contact Properties

PROPTERTYTYPEDESCRIPTION
ageNumberAge of a user
avatarStringURL to an avatar image for the user
birthdayDateUser’s birthday
createdAtDateDate the user’s account was first created. We recomend recommend using ISO-8601 date strings.
descriptionStringDescription of the user
emailStringEmail address of a user
firstNameStringFirst name of a user
displayNameStringThe prefered users display name, will default to "firstName lastName"
genderStringGender of a user
idStringThe ID of the user from your database, coerced to a string. eg 1 becomes "1"
lastNameStringLast name of a user
nameStringFull name of a user. If you only pass a first and last name Segment automatically fills in the full name for you.
phoneStringPhone number of a user
titleStringTitle of a user, usually related to their position at a specific company. Example: “VP of Engineering”
usernameStringUser’s username. This should be unique to each user, like the usernames of Twitter or GitHub.
websiteStringWebsite of a user

Default Contact Properties

Our SDKs automatically collect certain properties on every event or user profile. Any property that starts with $ is a property that has been generated by the SDK or ingestion.

PropertyDisplay NameDescription
$cityCityThe city of the user parsed from the IP.
$regionRegionThe region of the user parsed from the IP
$countryCodeCountry CodeThe country of the user parsed from the IP property.
$latitudeLatitudeLatitude of the user's IP location.
$longitudeLongitudeLongitude of the user's IP location.
$timezoneTimezoneTimezone of the user parsed from the IP.
$screenHeightScreen HeightThe most recent height of the device screen in pixels
$screenWidthScreen WidthThe most recent width of the device screen in pixels
$screenDpiScreen DPIThe most recent Pixel density of the device screen.
$lastSeenUpdated atThe last time a user profile property was set or updated
$osOperating SystemThe most recent OS of the user.
$browserBrowserThe most recent browser of the user.
$browserVersionBrowser VersionThe most recent bowser version of the user.
$initialReferrerInitial ReferrerReferring URL when the user first arrived on your site. Defaults to "direct"
$referrerLast Touch ReferrerReferring URL when the user last interacted with your site. Defaults to "direct"
$initialReferringDomainInitial Referring DomainReferring domain at first arrival. Defaults to "direct"
$referringDomainLast Touch Referring DomainReferring domain at the user's last interaction. Defaults to "direct"
$initialUtmSourceInitial UTM SourceThe initial UTM source tag from the URL a customer clicked to arrive at your domain.
$utmSourceLast Touch UTM SourceThe UTM source tag from the URL a customer clicked during their last interaction.
$initialUtmMediumInitial UTM MediumThe initial UTM medium tag from the URL a customer clicked to arrive at your domain.
$utmMediumLast Touch UTM MediumThe UTM medium tag from the URL a customer clicked during their last interaction.
$initialUtmCampaignInitial UTM CampaignThe initial UTM campaign tag from the URL a customer clicked to arrive at your domain.
$utmCampaignLast Touch UTM CampaignThe UTM campaign tag from the URL a customer clicked during their last interaction.
$initialUtmTermInitial UTM TermThe initial UTM term tag from the URL a customer clicked to arrive at your domain.
$utmTermLast Touch UTM TermThe UTM term tag from the URL a customer clicked during their last interaction.
$initialUtmContentInitial UTM ContentThe initial UTM content tag from the URL a customer clicked to arrive at your domain.
$utmContentLast Touch UTM ContentThe UTM content tag from the URL a customer clicked during their last interaction.
$unsubscribedUnsubscribedWhether the user has unsubscribed from all notifications

Reserved event properties

Properties used to calculate revenue for different traffic sources and LTV for users.

PROPERTYTYPEDESCRIPTION
revenueNumberAmount of revenue an event resulted in. This should be a decimal value
currencyStringCurrency of the revenue an event resulted in. This should be sent in the ISO 4127 format.
valueNumberAn abstract numerical value used internally to score eventsm such as lead scoring.

Default Event Properties

Our SDKs automatically collect certain properties on every event or user profile. The default properties begin with a $ and can be overwritten with your own identify calls, so we recomend avoiding leading $ in your identify call properties to avoid conflicts.

PropertyDisplay NameDescription
$cityCityThe city of the user parsed from the IP.
$regionRegionThe region of the user parsed from the IP
$countryCodeCountry CodeThe country of the user parsed from the IP property.
$latitudeLatitudeLatitude of the user's IP location.
$longitudeLongitudeLongitude of the user's IP location.
$timezoneTimezoneTimezone of the user parsed from the IP.
$screenHeightScreen HeightThe height of the device screen in pixels
$screenWidthScreen WidthThe width of the device screen in pixels
$screenDpiScreen DPIPixel density of the device screen.
$currentUrlCurrent URLThe URL of the page on which the event was tracked.
$osOperating SystemThe most recent OS of the user.
$browserBrowserThe most recent browser of the user.
$browserVersionBrowser VersionThe most recent bowser version of the user.
$deviceDevice TypeThe most recent bowser version of the user. eg Mobile, Tablet, Desktop
$referrerLast Touch ReferrerReferring URL when the user last interacted with your site. Defaults to "direct"
$referringDomainLast Touch Referring DomainReferring domain at the user's last interaction. Defaults to "direct"
$utmSourceUTM SourceThe UTM source tag from the URL a customer clicked to arrive at your domain.
$utmMediumUTM MediumThe UTM medium tag from the URL a customer clicked to arrive at your domain.
$utmCampaignUTM CampaignThe UTM campaign tag from the URL a customer clicked to arrive at your domain.
$utmTermUTM TermThe UTM term tag from the URL a customer clicked to arrive at your domain.
$utmContentUTM ContentThe UTM content tag from the URL a customer clicked to arrive at your domain.

Reserved Events with Optional Properties

⚠️ The event schema described below is not yet implemented in the UI. However, if you wish to future-proof your implementation, you can start using this schema in anticipation of its integration.

Reserved events are common events that happen during the lifecycle of a user, with optional properties to capture more detailed information, including revenue data where appropriate.

Signed Up

Event triggered when a user signs up. | Property | Description | |----------|----------------------------------| | source | How the user found your site. | | value | Track an estimated value of the signup|

Example:

analytics.track('Signed Up', {
  source: 'Referral by friend',
});

Signed In

Event triggered when a user signs in. | Property | Description | |----------|--------------------------------------------------| | method | The method used for signing in (e.g., email, social media). |

Example:

analytics.track('Signed In', {
  method: 'email',
});

Signed Out

Event triggered when a user signs out. No optional properties.

Example:

analytics.track('Signed Out');

Trial Started

Event triggered when a user starts a trial. | Property | Description | |-------------------|---------------------------------------------------------------------| | duration | The curation in days of the trial| | type| Values can be optIn for then the user didn't provide a cc or optOut when the user provided a cc and it will automatically start and the end of the trial period|

Example:

analytics.track('Trial Started', { duration: 14, type: 'optOut' });

Trial Completed

Event triggered when a user successfully completes a trial. | Property | Description | |-------------------|---------------------------------------------------------------------| | daysLeftInTrial| If a user manual upgrades before the end of the trial you can record this here|

Example:

analytics.track('Trial Completed', { daysLeftInTrial: 4 });

Payment Completed

Event triggered when a payment is completed. This is may be called on the server side after a confirmation webhook. This is helpful for recording ongoing subscription payments.

PropertyDescription
revenueThe initial payment amount.
currencyThe currency of the payment, otherwise assumed USD.

Example:

analytics.track('Payment Completed', { revenue: 29.99, currency: 'GBP' });

Subscription Started

Event triggered when a user starts a subscription. If you have integrated with stripe for revenue tracking or are doing server side revenue tracking with webhooks you should skip the revenue and currency properties to prevent duplicate revenue tracking.

PropertyDescription
planThe name or ID of the subscription plan.
revenueThe initial payment amount. Exclude if triggering Payment Completed to avoid double counting.
currencyThe currency of the payment, otherwise assumed USD. Exclude if triggering Payment Completed to avoid double counting.

Example:

analytics.track('Subscription Started', {
  plan: 'Monthly',
});

Subscription Cancelled

Event triggered when a subscription is cancelled.

PropertyDescription
reasonThe reason for cancellation. This can be used in the feedback and analysis of cancellation reasons

Example:

analytics.track('Subscription Cancelled', {
  reason: 'Not using it any more',
});

Subscription Upgraded

Event triggered when a subscription is upgraded. | Property | Description | |-----------------|-----------------------------------------------------------------------------------------------| | fromPlan | The previous plan. | | toPlan | The new plan. | | previousRevenue | The revenue from the previous plan. | | newRevenue | The revenue from the new plan. | | revenue | If the customer is charged immediately then include a revenue number here | | currency | The currency of the payment, assumed to be USD unless otherwise specified. |

Example:

analytics.track('Subscription Cancelled', {
  fromPlan: 'Monthly',
  toPlan: 'Annual',
  previousRevenue: 29,
  newRevenue: 129,
});

Subscription Downgraded

Event triggered when a subscription is downgraded. | Property | Description | |------------|-------------------| | fromPlan | The previous plan. | | toPlan | The new plan. | | previousRevenue | The revenue from the previous plan. | | newRevenue | The revenue from the new plan. | | revenue | If the customer is refunded immediately then include a revenue number here, in the case of a downgrade this will be a negtive value. Only include the revenue here if it's not tracked on your backend or with a webhook | | currency | The currency of the payment, assumed to be USD unless otherwise specified. |

Example:

analytics.track('Subscription Cancelled', {
  fromPlan: 'Annual',
  toPlan: 'Monthly',
  previousRevenue: 129,
  newRevenue: 29,
  revenue: -36,
  currency: 'USD',
});
0.0.23

1 month ago

0.0.24

1 month ago

0.0.22

2 months ago

0.0.21

3 months ago

0.0.20

3 months ago

0.0.19

3 months ago

0.0.18

3 months ago

0.0.17

3 months ago

0.0.14

3 months ago

0.0.15

3 months ago

0.0.16

3 months ago

0.0.13

4 months ago