Dedicated Piwik PRO library that helps with implementing Piwik PRO Tag Manager, Piwik PRO Consent Manager and Piwik PRO tracking client in Nuxt applications.
To use this package in your project, run the following command.
npm install @piwikpro/nuxt-piwik-pro
In your Nuxt Project, include @piwikpro/nuxt-piwik-pro
as a nuxt module in nuxt.config.ts
file. To set up the Piwik PRO Tag Manager container in the app, pass configuration object as a module inline-options. Configuration options can be found below.
// nuxt.config.ts
export default defineNuxtConfig({
//...
modules: [
[
"@piwikpro/nuxt-piwik-pro",
{
containerId: process.env.PIWIK_PRO_CONTAINER_ID,
containerUrl: process.env.PIWIK_PRO_CONTAINER_URL,
},
],
],
//...
});
type ConfigOptions {
containerId: string;
containerUrl: string;
dataLayerName?: string;
nonce?: string;
}
The nonce attribute is useful to allow-list specific elements, such as a particular inline script or style elements. It can help you to avoid using the CSP unsafe-inline directive, which would allow-list all inline scripts or styles.
If you want your nonce to be passed to the script, pass it as the third argument when calling the script initialization method.
Piwik PRO container will be initialized under the hood by @piwikpro/nuxt-piwik-pro
module itself. Module also inject client-only plugin to Nuxt application instance which allow you to use all Piwik PRO services globally as a part of Nuxt context returned from useNuxtApp()
composable as a $piwikPRO
.
Remember that Piwik PRO is a client-only library. This means you won't have access to any of its services on the server side.
// In any component or other part of application code
const { $piwikPRO } = useNuxtApp();
// $piwikPRO won't be available on server-side code!
if (module.meta.client) {
$piwikPRO.PageViews.trackPageView();
$piwikPRO.GoalConversions.trackGoal(1, 100);
}
To use Piwik PRO services safety, you can import usePiwikPro()
from '@piwikpro/nuxt-piwik-pro/composables'
.
// In any component or other part of application code
import { usePiwikPro } from "@piwikpro/nuxt-piwik-pro/composables";
// callback can be sync or async function
const userId = await usePiwikPro(
({ PageViews, GoalConversions, UserManagement }) => {
PageViews.trackPageView();
GoalConversions.trackGoal(1, 100);
return UserManagement.getUserId();
}
);
To make this composable globally available, create .ts
file in /composables
directory and export usePiwikPro()
from '@piwikpro/nuxt-piwik-pro/composables'
.
// composables/usePiwikPro.ts
export { usePiwikPro } from "@piwikpro/nuxt-piwik-pro/composables";
// In any component or other part of application code
const userId = await usePiwikPro(
({ PageViews, GoalConversions, UserManagement }) => {
PageViews.trackPageView();
GoalConversions.trackGoal(1, 100);
return UserManagement.getUserId();
}
);
Alternatively, you can wrap Component with Piwik PRO usage by <ClientOnly/>
nuxt component.
// In client-only <WithPiwikPROUsage/> component
const { $piwikPRO } = useNuxtApp();
$piwikPRO.PageViews.trackPageView();
$piwikPRO.GoalConversions.trackGoal(1, 100);
// Server-side code
<template>
<ClientOnly fallback-tag="span" fallback="Loading comments...">
<WithPiwikPROUsage/>
</ClientOnly>
</template>
Or if you want use PiwikPRO services directly in Page component, you can add client
to its file name.
// In piwik-pro.client.ts page component
const { $piwikPRO } = useNuxtApp();
$piwikPRO.PageViews.trackPageView();
$piwikPRO.GoalConversions.trackGoal(1, 100);
Please explore the ./example
directory to get to know how to use this package with a specific examples and it's various methods.
- ClientConfiguration
- ContentTracking
- CookieManagement
- CrossDomainTracking
- CustomDimensions
- CustomEvent
- DataLayer
- DownloadAndOutlink
- ErrorTracking
- GoalConversions
- Heartbeat
- PageViews
- SiteSearch
- UserManagement
- eCommerce
Ƭ Dimensions: Record
<`dimension${number}`, string
>
Ƭ InitOptions: Object
Name | Type | Description |
---|---|---|
dataLayerName? |
string |
Defaults to 'dataLayer' |
nonce? |
string |
- |
Ƭ PaymentInformation: Object
Name | Type |
---|---|
discount? |
number | string |
grandTotal |
number | string |
orderId |
string |
shipping? |
number | string |
subTotal? |
number | string |
tax? |
number | string |
Ƭ PiwikPROHandler<T
>: (piwikPRO
: PiwikPROServicesType
) => T
| Promise
<T
>
Name | Type |
---|---|
T |
unknown |
▸ (piwikPRO
): T
| Promise
<T
>
Name | Type |
---|---|
piwikPRO |
PiwikPROServicesType |
T
| Promise
<T
>
Ƭ PiwikPROServicesType: typeof PiwikPROServices
Ƭ Product: Object
Name | Type |
---|---|
brand? |
string |
category? |
LimitedArrayFiveStrings |
customDimensions? |
Record <number , string > |
name? |
string |
price? |
number |
quantity? |
number |
sku |
string |
variant? |
string |
Ƭ VisitorInfo: [isNew: "0" | "1", visitorId: string, firstVisitTS: number, previousVisitCount: string | number, currentVisitTS: number, lastVisitTS: number | "", lastEcommerceOrderTS: number | ""]
• Const
PiwikPRO: Object
Name | Type |
---|---|
getInitScript |
typeof PiwikPro.getInitScript |
initialize |
typeof PiwikPro.init |
▸ default(this
, inlineOptions
, nuxt
): _ModuleSetupReturn
Name | Type |
---|---|
this |
void |
inlineOptions |
PluginArgs |
nuxt |
Nuxt |
_ModuleSetupReturn
▸ getDomains(): Promise
<string
[]>
Returns list of internal domains (set with "setDomains" function and used in outlink tracking).
Promise
<string
[]>
▸ setDomains(domains
): void
Allows to define a list of internal domains or mobile app URIs. Used in outlink tracking for determining whether a link is an outlink and in cross domain linking for determining which links should have visitor ID parameter injected.
Name | Type |
---|---|
domains |
string [] |
void
- logAllContentBlocksOnPage
- trackAllContentImpressions
- trackContentImpression
- trackContentImpressionsWithinNode
- trackContentInteraction
- trackContentInteractionNode
- trackVisibleContentImpressions
▸ logAllContentBlocksOnPage(): void
Print all content blocks to the console for debugging purposes
void
▸ trackAllContentImpressions(): void
Scans the entire DOM for content blocks and tracks impressions after all page elements load. It does not send duplicates on repeated calls unless trackPageView was called in between trackAllContentImpressions invocations
void
▸ trackContentImpression(contentName
, contentPiece
, contentTarget
): void
Name | Type |
---|---|
contentName |
string |
contentPiece |
string |
contentTarget |
string |
void
▸ trackContentImpressionsWithinNode(domNode
): void
Name | Type |
---|---|
domNode |
Node |
void
▸ trackContentInteraction(contentInteraction
, contentName
, contentPiece
, contentTarget
): void
Tracks manual content interaction event
Name | Type | Description |
---|---|---|
contentInteraction |
string |
Type of interaction (e.g. "click") |
contentName |
string |
Name of a content block |
contentPiece |
string |
Name of the content that was displayed (e.g. link to an image) |
contentTarget |
string |
Where the content leads to (e.g. URL of some external website) |
void
▸ trackContentInteractionNode(domNode
, contentInteraction?
): void
Tracks interaction with a block in domNode. Can be called from code placed in onclick attribute
Name | Type | Description |
---|---|---|
domNode |
Node |
Node marked as content block or containing content blocks. If content block can’t be found, nothing will tracked. |
contentInteraction? |
string |
Name of interaction (e.g. "click") |
void
▸ trackVisibleContentImpressions(checkOnScroll?
, watchInterval?
): void
Scans DOM for all visible content blocks and tracks impressions
Name | Type | Description |
---|---|---|
checkOnScroll? |
boolean |
Whether to scan for visible content on scroll event |
watchInterval? |
number |
Delay, in milliseconds, between scans for new visible content. Periodic checks can be disabled by passing 0 |
void
- deleteCookies
- disableCookies
- enableCookies
- getConfigVisitorCookieTimeout
- getCookieDomain
- getCookiePath
- getSessionCookieTimeout
- hasCookies
- setCookieDomain
- setCookieNamePrefix
- setCookiePath
- setReferralCookieTimeout
- setSecureCookie
- setSessionCookieTimeout
- setVisitorCookieTimeout
- setVisitorIdCookie
▸ deleteCookies(): void
Deletes existing tracking cookies on the next page view
void
▸ disableCookies(): void
Disables all first party cookies. Existing cookies will be deleted in the next page view
void
▸ enableCookies(): void
Enables all first party cookies. Cookies will be created on the next tracking request
void
▸ getConfigVisitorCookieTimeout(): Promise
<number
>
Returns expiration time of visitor cookies (in milliseconds)
Promise
<number
>
▸ getCookieDomain(): Promise
<string
>
Returns domain of the analytics tracking cookies (set with setCookieDomain()).
Promise
<string
>
▸ getCookiePath(): Promise
<string
>
Returns the analytics tracking cookies path
Promise
<string
>
▸ getSessionCookieTimeout(): Promise
<number
>
Returns expiration time of session cookies
Promise
<number
>
▸ hasCookies(): Promise
<boolean
>
Returns true if cookies are enabled in this browser
Promise
<boolean
>
▸ setCookieDomain(domain
): void
Sets the domain for the analytics tracking cookies
Name | Type |
---|---|
domain |
string |
void
▸ setCookieNamePrefix(prefix
): void
Sets the prefix for analytics tracking cookies. Default is "pk".
Name | Type |
---|---|
prefix |
string |
void
▸ setCookiePath(path
): void
Sets the analytics tracking cookies path
Name | Type |
---|---|
path |
string |
void
▸ setReferralCookieTimeout(seconds
): void
Sets the expiration time of referral cookies
Name | Type |
---|---|
seconds |
number |
void
▸ setSecureCookie(secure
): void
Toggles the secure cookie flag on all first party cookies (if you are using HTTPS)
Name | Type |
---|---|
secure |
boolean |
void
▸ setSessionCookieTimeout(seconds
): void
Sets the expiration time of session cookies
Name | Type |
---|---|
seconds |
number |
void
▸ setVisitorCookieTimeout(seconds
): void
Sets the expiration time of visitor cookies
Name | Type |
---|---|
seconds |
number |
void
▸ setVisitorIdCookie(): void
Sets cookie containing analytics ID in browser
void
Ƭ LinkDecorator: (url
: string
, value
: string
, name
: string
) => string
| null
▸ (url
, value
, name
): string
| null
Name | Type |
---|---|
url |
string |
value |
string |
name |
string |
string
| null
Ƭ VisitorIdGetter: (url
: string
, name
: string
) => string
▸ (url
, name
): string
Name | Type |
---|---|
url |
string |
name |
string |
string
▸ customCrossDomainLinkDecorator(decorator
): void
Sets custom cross domains URL decorator for injecting visitor ID into URLs. Used when cross domain linking is enabled.
Name | Type |
---|---|
decorator |
LinkDecorator |
void
▸ customCrossDomainLinkVisitorIdGetter(getter
): void
Sets custom cross domain URL parser for extracting visitor ID from URLs. Should extract data injected by URL decorator. The getter should return visitor ID extracted from page URL.
Name | Type |
---|---|
getter |
VisitorIdGetter |
void
▸ disableCrossDomainLinking(): void
Disables cross domain linking.
void
▸ enableCrossDomainLinking(): void
Enables cross domain linking. Visitors across domains configured with "setDomains" function will be linked by passing visitor ID parameter in links.
void
▸ getCrossDomainLinkingUrlParameter(): Promise
<string
>
Returns the name of a cross domain URL parameter (query parameter by default) holding visitor ID. This is "pk_vid" by default.
Promise
<string
>
▸ isCrossDomainLinkingEnabled(): Promise
<boolean
>
Returns boolean telling whether cross domain linking is enabled.
Promise
<boolean
>
▸ setCrossDomainLinkingTimeout(timeout
): void
Changes the time in which two visits across domains will be linked. The default timeout is 180 seconds (3 minutes).
Name | Type |
---|---|
timeout |
number |
void
▸ deleteCustomDimension(customDimensionId
): void
Removes a custom dimension with the specified ID.
Name | Type |
---|---|
customDimensionId |
string | number |
void
▸ getCustomDimensionValue(customDimensionId
): Promise
<string
| undefined
>
Returns the value of a custom dimension with the specified ID.
Name | Type |
---|---|
customDimensionId |
string | number |
Promise
<string
| undefined
>
▸ setCustomDimensionValue(customDimensionId
, customDimensionValue
): void
Sets a custom dimension value to be used later.
Name | Type |
---|---|
customDimensionId |
string | number |
customDimensionValue |
string |
void
▸ trackEvent(category
, action
, name?
, value?
, dimensions?
): void
Tracks a custom event, e.g. when a visitor interacts with the page
Name | Type |
---|---|
category |
string |
action |
string |
name? |
string |
value? |
number |
dimensions? |
Dimensions |
void
Ƭ DataLayerEntry: Record
<string
, AnyData
>
▸ push(data
): number
Adds entry to a data layer
Name | Type |
---|---|
data |
DataLayerEntry |
number
▸ setDataLayerName(name
): void
Name | Type |
---|---|
name |
string |
void
- addDownloadExtensions
- enableLinkTracking
- getLinkTrackingTimer
- removeDownloadExtensions
- setDownloadClasses
- setDownloadExtensions
- setIgnoreClasses
- setLinkClasses
- setLinkTrackingTimer
- trackLink
▸ addDownloadExtensions(extensions
): void
Adds new extensions to the download extensions list
Name | Type |
---|---|
extensions |
string [] |
void
▸ enableLinkTracking(trackAlsoMiddleAndRightClicks?
): void
Enables automatic link tracking. If called with true
, left, right and
middle clicks on links will be treated as opening a link. Opening a links to
an external site (different domain) creates an outlink event. Opening a link
to a downloadable file creates a download event
Name | Type |
---|---|
trackAlsoMiddleAndRightClicks? |
boolean |
void
▸ getLinkTrackingTimer(): Promise
<number
>
Returns lock/wait time after a request set by setLinkTrackingTimer
Promise
<number
>
▸ removeDownloadExtensions(extensions
): void
Removes extensions from the download extensions list
Name | Type |
---|---|
extensions |
string [] |
void
▸ setDownloadClasses(classes
): void
Sets a list of class names that indicate whether a list is a download and not an outlink
Name | Type |
---|---|
classes |
string [] |
void
▸ setDownloadExtensions(extensions
): void
Overwrites the list of file extensions indicating that a link is a download
Name | Type |
---|---|
extensions |
string [] |
void
▸ setIgnoreClasses(classes
): void
Set a list of class names that indicate a link should not be tracked
Name | Type |
---|---|
classes |
string [] |
void
▸ setLinkClasses(classes
): void
Sets a list of class names that indicate whether a link is an outlink and not download
Name | Type |
---|---|
classes |
string [] |
void
▸ setLinkTrackingTimer(time
): void
When a visitor produces an events and closes the page immediately afterwards, e.g. when opening a link, the request might get cancelled. To avoid loosing the last event this way, JavaScript Tracking Client will lock the page for a fraction of a second (if wait time hasn’t passed), giving the request time to reach the Collecting & Processing Pipeline
Name | Type |
---|---|
time |
number |
void
▸ trackLink(url
, linkType
, dimensions?
, callback?
): void
Manually tracks outlink or download event with provided values
Name | Type |
---|---|
url |
string |
linkType |
string |
dimensions? |
Dimensions |
callback? |
() => void |
void
▸ enableJSErrorTracking(unique?
): void
Enables tracking of unhandled JavaScript errors.
Name | Type | Description |
---|---|---|
unique? |
boolean |
track only unique errors |
void
▸ trackError(error
): void
Attempts to send error tracking request using same format as native errors caught by enableJSErrorTracking(). Such error request will still follow rules set for tracker, so it will be sent only when JS error tracking is enabled (enableJSErrorTracking function was called before this attempt). It will also respect rules for tracking only unique errors.
Name | Type |
---|---|
error |
Error |
void
▸ trackGoal(goalId
, conversionValue
, dimensions?
): void
Tracks manual goal conversion
Name | Type |
---|---|
goalId |
string | number |
conversionValue |
number |
dimensions? |
Dimensions |
void
▸ disableHeartBeatTimer(): void
Disables sending heartbeats if they were previously enabled by "enableHeartBeatTimer" function.
void
▸ enableHeartBeatTimer(delays?
): void
When a visitor is not producing any events (e.g. because they are reading an article or watching a video), we don’t know if they are still on the page. This might skew page statistics, e.g. time on page value. Heartbeat timer allows us to determine how much time visitors spend on a page by sending heartbeats to the Tracker as long as the page is in focus.
Name | Type |
---|---|
delays? |
number [] |
void
▸ trackPageView(customPageTitle?
): void
Tracks a visit on the page that the function was run on
Name | Type |
---|---|
customPageTitle? |
string |
void
▸ trackSiteSearch(keyword
, category?
, searchCount?
, dimensions?
): void
Tracks search requests on a website
Name | Type |
---|---|
keyword |
string |
category? |
string |
searchCount? |
number |
dimensions? |
Dimensions |
void
▸ deanonymizeUser(): void
Disables anonymous tracking and sends deanonymization event to the Tracker. Recommended method for disabling anonymous tracking.
void
▸ getUserId(): Promise
<string
>
The function that will return user ID
Promise
<string
>
▸ getVisitorId(): Promise
<string
>
Returns 16-character hex ID of the visitor
Promise
<string
>
▸ getVisitorInfo(): Promise
<VisitorInfo
>
Returns visitor information in an array
Promise
<VisitorInfo
>
▸ resetUserId(): void
Clears previously set userID, e.g. when visitor logs out
void
▸ setUserId(userId
): void
User ID is an additional parameter that allows you to aggregate data. When set up, you will be able to search through sessions by this parameter, filter reports through it or create Multi attribution reports using User ID
Name | Type |
---|---|
userId |
string |
void
▸ setUserIsAnonymous(isAnonymous
): void
Enables or disables anonymous tracking (anonymous = without consent). The next emitted event will have anonymous mode set accordingly.
Name | Type |
---|---|
isAnonymous |
boolean |
void
- addEcommerceItem
- clearEcommerceCart
- ecommerceAddToCart
- ecommerceCartUpdate
- ecommerceOrder
- ecommerceProductDetailView
- ecommerceRemoveFromCart
- getEcommerceItems
- removeEcommerceItem
- setEcommerceView
- trackEcommerceCartUpdate
- trackEcommerceOrder
▸ addEcommerceItem(productSKU
, productName
, productCategory
, productPrice
, productQuantity
): void
Name | Type |
---|---|
productSKU |
string |
productName |
string |
productCategory |
string | string [] |
productPrice |
number |
productQuantity |
number |
void
Deprecated
Please use the ecommerceAddToCart instead.
▸ clearEcommerceCart(): void
void
Deprecated
▸ ecommerceAddToCart(products
): void
Tracks action of adding products to a cart
Name | Type |
---|---|
products |
Product [] |
void
▸ ecommerceCartUpdate(products
, grandTotal
): void
Tracks current state of a cart
Name | Type |
---|---|
products |
Product [] |
grandTotal |
string | number |
void
▸ ecommerceOrder(products
, paymentInformation
): void
Tracks conversion, including products and payment details
Name | Type |
---|---|
products |
Product [] |
paymentInformation |
PaymentInformation |
void
▸ ecommerceProductDetailView(products
): void
Tracks action of viewing product page
Name | Type |
---|---|
products |
Product [] |
void
▸ ecommerceRemoveFromCart(products
): void
Tracks action of removing a products from a cart
Name | Type |
---|---|
products |
Product [] |
void
▸ getEcommerceItems(): Promise
<object
>
Promise
<object
>
Deprecated
▸ removeEcommerceItem(productSKU
): void
Name | Type |
---|---|
productSKU |
string |
void
Deprecated
Please use the ecommerceRemoveFromCart instead.
▸ setEcommerceView(productSKU
, productName?
, productCategory?
, productPrice?
): void
Name | Type |
---|---|
productSKU |
string |
productName? |
string |
productCategory? |
string [] |
productPrice? |
string |
void
Deprecated
▸ trackEcommerceCartUpdate(cartAmount
): void
Name | Type |
---|---|
cartAmount |
number |
void
Deprecated
Please use the ecommerceCartUpdate instead.
▸ trackEcommerceOrder(orderId
, orderGrandTotal
, orderSubTotal?
, orderTax?
, orderShipping?
, orderDiscount?
): void
Name | Type |
---|---|
orderId |
string |
orderGrandTotal |
number |
orderSubTotal? |
number |
orderTax? |
number |
orderShipping? |
number |
orderDiscount? |
number |
void
Deprecated
Please use the ecommerceOrder instead.