Security News
Bun 1.2 Released with 90% Node.js Compatibility and Built-in S3 Object Support
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
@piwikpro/next-piwik-pro
Advanced tools
Dedicated Piwik PRO library that helps with implementing Piwik PRO Tag Manager and the Piwik PRO tracking client in Next.js applications.
To use this package in your project, run the following command.
npm install @piwikpro/next-piwik-pro
yarn add @piwikpro/next-piwik-pro
In your Next.js Project, include the default PiwikProProvider
in the layout.tsx
file. To set up the Piwik PRO Tag
Manager container in the app.
In the arguments, pass your container id and your container url as parameters (marked container-id
and container-url
in the example below).
'use client'
import PiwikProProvider from '@piwikpro/next-piwik-pro'
export default function RootLayout({children}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<PiwikProProvider
containerId="container-id"
containerUrl="container-url"
>
{children}
</PiwikProProvider>
</body>
</html>
)
}
If you plan to use environmental variables to config your Piwik account you can do it with adding them to your .env
file. Remember that variables to be visible in component need to be named with NEXT_PUBLIC_
prefix, in other cases
they will be visible only in Node context but not in Next.
NEXT_PUBLIC_CONTAINER_ID=0a0b8661-8c10-4d59-e8fg-1h926ijkl184
NEXT_PUBLIC_CONTAINER_URL=https://example.piwik.pro
'use client'
import PiwikProProvider from '@piwikpro/next-piwik-pro'
export default function RootLayout({children}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<PiwikProProvider
containerUrl = {process.env.NEXT_PUBLIC_CONTAINER_URL}
containerId = {process.env.NEXT_PUBLIC_CONTAINER_ID}
>
{children}
</PiwikProProvider>
</body>
</html>
)
}
> Previously, we used 'accountName' to configure PiwikProProvider. The parameter has now been replaced by 'container-url'. The 'accountName' parameter is deprecated and will be removed in the future.
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.
'use client'
import PiwikProProvider from '@piwikpro/next-piwik-pro'
export default function RootLayout({children}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<PiwikProProvider
containerId="container-id"
containerUrl="container-url"
nonce="nonce-string"
>
{children}
</PiwikProProvider>
</body>
</html>
)
}
To use methods in your page you need to include usePiwikPro
from the library.
Make sure to use usePiwikPro
in client components only, otherwise you will get an error.
To make it work You need to use it in separated client component (use component
)
import {usePiwikPro} from '@piwikpro/next-piwik-pro'
Then you need to define modules you want to use and initialize it from previously included usePiwikPro
context. In
example below you can see the initialization of the PageViews
module.
const {PageViews} = usePiwikPro()
You can use those methods in all hooks and props for ex. useEffect
or onClick
.
useEffect(() => {
PageViews.trackPageView('optional title')
}, [])
<button onClick = {() => {
CustomEvent.trackEvent('Post', pageData.title)
}}>
CustomEvent.trackEvent
button
</button>
Below you can view the sample usage of the available methods from modules.
const {PageViews} = usePiwikPro()
PageViews.trackPageView('optional title')
Collection of methods to handle users and visitors data through the Piwik PRO API.
UserManagement.setUserId(userID)
- Sets user ID, which will help identify a user of your application across many
devices and browsers.
userID
(string) – Required Non-empty, unique ID of a user in applicationUserManagement.resetUserId()
- Clears previously set userID
, e.g. when visitor logs out.UserManagement.getUserId()
- Returns currently used userID
value (set with setUserId()
).UserManagement.getVisitorId()
- Returns 16-character hex ID of the visitor.UserManagement.getVisitorInfo()
- Returns visitor information. Return type string[]
. String array with the
following visitor info:
[0]
- new visitor flag indicating new, ("1") or returning ("0") visitor[1]
- visitor ID (16-character hex number)[2]
- first visit timestamp (UNIX epoch time)[3]
- previous visit count ("0" for first visit)[4]
- current visit timestamp (UNIX epoch time)[5]
- last visit timestamp (UNIX epoch time or "" if N/A)[6]
- last e-commerce order timestamp (UNIX epoch time or "" if N/A)const {UserManagement} = usePiwikPro()
UserManagement.setUserId('UserId')
UserManagement.resetUserId()
Some of the methods are getting data from the API and they need to be called asynchronously. They provide data that can be shown on the page. This need to be done with defining async function in your hook body and setting the state of the variable. Like on example below.
const {UserManagement} = usePiwikPro()
const [userId, setUserId] = useState<string>('')
const [visitorId, setVisitorId] = useState<string>('')
const [visitorInfo, setVisitorInfo] = useState<any>('')
const callAsyncMethods = async () => {
const uId = await UserManagement.getUserId()
setUserId(uId)
const vId = await UserManagement.getVisitorId()
setVisitorId(vId)
const vInfo = await UserManagement.getVisitorInfo()
setVisitorInfo(vInfo)
}
callAsyncMethods()
You have access to those variables in you page body. Example access below.
<p><code>UserManagement.getUserId()</code> - {userId}</p>
<p><code>UserManagement.getVisitorId()</code> - {visitorId}</p>
<p>
<code>UserManagement.getVisitorInfo()</code> -{' '}
{JSON.stringify(visitorInfo)}
</p>
Collection of methods to handle custom events, not described in the other categories.
CustomEvent.trackEvent(category, action[, name[, value[, dimensions]]])
- Tracks custom event, e.g. when visitor
interacts with the page.
category (string)
– Required Event categoryaction (string)
– Required Event actionname (string)
– Optional Event namevalue (number)
– Optional Event valueconst {CustomEvent} = usePiwikPro()
CustomEvent.trackEvent('Post', pageData.title)
Collection of methods to track site search data, through the Piwik PRO API.
SiteSearch.trackSiteSearch(keyword[, category[, resultCount[, dimensions]]])
- Tracks search requests on a website.
keyword (string)
– Required What keyword the visitor entered into the search boxcategory (string|Array<string>)
– Optional Category selected in the search enginesearchCount (number)
– Optional The number of search results showndimensions (object)
– Optional Custom dimensions to pass along with the site search eventconst {SiteSearch} = usePiwikPro()
SiteSearch.trackSiteSearch('keyword', 'category', 5)
Collection of methods to handle e-commerce events through the Piwik PRO API.
ecommerceAddToCart(products: Product[])
- Tracks action of adding products to a cart.ecommerceRemoveFromCart(products: Product[])
- Tracks action of removing a products from a cart.ecommerceOrder(products: Product[], paymentInformation: PaymentInformation)
- Tracks conversion (including products and payment details).ecommerceCartUpdate(products: Product[], grandTotal: PaymentInformation['grandTotal'])
- Tracks current state of a cart.ecommerceProductDetailView(products: Product[])
- Tracks product or category view. Must be followed by a page view.discount amountconst { eCommerce } = usePiwikPro()
const products = [{
sku: 'sku-4',
name: 'Product 4',
category: ['product-category', 'product-category-4'],
brand: 'Brand 4',
variant: 'Variant 4',
price: 39.96,
customDimensions: {
dimension1: 'value1',
dimension2: 'value2'
}
}]
const subTotal = products.reduce((acc, product) => {
if (product.price) {
return acc + product.price
}
return acc
}, 0)
const tax = 10
const shipping = 4
const discount = 5
const paymentInformation: PaymentInformation = {
orderId: 'order-123',
grandTotal: subTotal + tax + shipping - discount,
subTotal,
tax,
shipping,
discount
}
eCommerce.ecommerceAddToCart(products)
eCommerce.ecommerceRemoveFromCart(products)
ecommerce.ecommerceOrder(products, paymentInformation)
eCommerce.ecommerceCartUpdate(products, paymentInformation.grandTotal)
eCommerce.ecommerceProductDetailView(products)
Collection of methods to track impressions through the Piwik PRO API.
ContentTracking.trackContentImpression(contentName, contentPiece, contentTarget)
- Tracks manual content impression
event.
contentName (string)
– Required Name of a content blockcontentPiece (string)
– Required Name of the content that was displayed (e.g. link to an image)contentTarget (string)
– Required Where the content leads to (e.g. URL of some external website)ContentTracking.trackContentInteraction(contentInteraction, contentName, contentPiece, contentTarget)
- Tracks
manual content interaction event.
contentInteraction (string)
– Required Type of interaction (e.g. "click")contentName (string)
– Required Name of a content blockcontentPiece
(string) – Required Name of the content that was displayed (e.g. link to an image)contentTarget (string)
– Required Where the content leads to (e.g. URL of some external website)const {ContentTracking} = usePiwikPro()
ContentTracking.trackContentImpression(
'contentName',
'contentPiece',
'contentTarget'
)
ContentTracking.trackContentInteraction(
'contentInteraction',
'contentName',
'contentPiece',
'contentTarget'
)
Collection of methods to manually tracks outlink or download events through the Piwik PRO API.
DownloadAndOutlink.trackLink(linkAddress, linkType[, dimensions[, callback]])
- Manually tracks outlink or download
event with provided values.
linkAddress (string)
– Required URL address of the linklinkType (string)
– Required Type of the link, "link" for outlink, "download" for downloaddimensions (object)
– Optional Custom dimensions to pass along with the link eventcallback (function)
– Optional Function that should be called after tracking the linkDownloadAndOutlink.enableLinkTracking([trackMiddleAndRightClicks])
- Enables automatic link tracking. By default,
left, right and middle clicks on links will be treated as opening a link. Opening a link to an external site (
different domain) creates an outlink event. Opening a link to a downloadable file creates a download event.
trackMiddleAndRightClicks (boolean)
– Optional Whether to treat middle and right clicks as opening a link. The
default value is true.DownloadAndOutlink.setLinkClasses(classes)
- Sets a list of class names that indicate whether a link is an outlink
and not download.
classes (Array<string>)
– Required CSS class name or an array of class namesDownloadAndOutlink.setDownloadClasses(classes)
- Sets a list of class names that indicate whether a list is a
download and not an outlink.
classes (Array<string>)
– Required CSS class name or an array of class namesDownloadAndOutlink.addDownloadExtensions(extensions)
Adds new extensions to the download extensions list.
extensions (Array<string>)
– Required List of extensions to be added as an array, e.g. ["7z","apk","mp4"]
.DownloadAndOutlink.removeDownloadExtensions(extensions)
- Removes extensions from the download extensions list.
extensions (Array<string>)
– Required List of extensions to remove as an array, e.g. ["zip", "rar"].DownloadAndOutlink.setLinkTrackingTimer(milliseconds)
- 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. setLinkTrackingTimer
allows to change the
default lock/wait time of 500ms.
milliseconds (number)
– Required How many milliseconds a request needs to reach the Collecting & Processing
Pipeline.DownloadAndOutlink.setIgnoreClasses(classes)
- Set a list of class names that indicate a link should not be tracked.
classes (Array<string>)
– Required CSS class name or an array of class namesconst {DownloadAndOutlink} = usePiwikPro()
DownloadAndOutlink.trackLink('http://localhost:3000', 'link')
DownloadAndOutlink.enableLinkTracking(true)
DownloadAndOutlink.setLinkClasses(['this-is-an-outlink'])
DownloadAndOutlink.setDownloadClasses(['this-is-a-download'])
DownloadAndOutlink.addDownloadExtensions(['zip', 'rar'])
DownloadAndOutlink.removeDownloadExtensions(['doc', 'xls'])
DownloadAndOutlink.setLinkTrackingTimer(10)
DownloadAndOutlink.setIgnoreClasses(['do-not-track'])
Some of the methods are getting data from the API and they need to be called asynchronously. They provide data that can be shown no the page. This need to be done with defining async function in your hook body and setting the state of the variable. Like on example below.
const {DownloadAndOutlink} = usePiwikPro()
const [linkTrackingTimer, setLinkTrackingTimer] = useState<string>('')
const callAsyncMethods = async () => {
const lTrackingTimer = await DownloadAndOutlink.getLinkTrackingTimer()
setLinkTrackingTimer(lTrackingTimer)
}
You have access to those variables in you page body. Example below.
<p>
<code>DownloadAndOutlink.getLinkTrackingTimer()</code> -{' '}
{linkTrackingTimer}
</p>
Collection of methods to manually tracks goal conversions through the Piwik PRO API.
GoalConversions.trackGoal(goalID[, conversionValue[, dimensions]])
- Tracks manual goal
conversion. goalID (number|string)
– Required Goal ID (integer or UUID), conversionValue (number)
– Optional
Conversion value (revenue), dimensions (object)
– Optional Custom dimensions to pass along with the conversionconst {GoalConversions} = usePiwikPro()
// function trackGoal(goalId: string | number, conversionValue: number, dimensions?: Object | undefined): void
GoalConversions.trackGoal(1, 30)
Collection of methods to manage custom dimensions through the Piwik PRO API.
CustomDimensions.setCustomDimensionValue(customDimensionID, customDimensionValue
- Sets a custom dimension to be
used later.
customDimensionID (number)
– Required ID of a custom dimension, customDimensionValue (string)
– Required Value
of a custom dimensionCustomDimensions.deleteCustomDimension(customDimensionID)
- Removes a custom dimension with the specified ID.
customDimensionID (number)
– Required ID of a custom dimensionCustomDimensions.getCustomDimensionValue(customDimensionID)
- Returns the value of a custom dimension with the
specified ID. Returns: Value set with setCustomDimensionValue
(e.g. loginStatus
). Return type: string
customDimensionID (number)
– Required ID of a custom dimension.const {CustomDimensions} = usePiwikPro()
CustomDimensions.setCustomDimensionValue('customDimensionId', 'value')
CustomDimensions.getCustomDimensionValue('customDimensionId')
CustomDimensions.deleteCustomDimension('customDimensionId')
Some of the methods are getting data from the API and they need to be called asynchronously. They provide data that can be shown on the page. This need to be done with defining async function in your hook body and setting the state of the variable. Like on example below.
const {UserManagement} = usePiwikPro()
const [customDimValue, setCustomDimValue] = useState<string>('')
const callAsyncMethods = async () => {
const cDimValue = await CustomDimensions.getCustomDimensionValue(12)
setCustomDimValue(cDimValue)
}
callAsyncMethods()
You have access to those variables in you page body. Example access below.
<p>
<code>CustomDimensions.getCustomDimensionValue()</code> - {customDimValue}
</p>
A data layer is a data structure on your site or app where you can store data and access it with tools like Tag Manager. You can include any data you want in your data layer.
DataLayer.push(data)
- Adds an event to a data layer.
data
- Required data value without type.const {DataLayer} = usePiwikPro()
DataLayer.push('data')
2.1.1
FAQs
Piwik PRO tracking library for Next.js
We found that @piwikpro/next-piwik-pro demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
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.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.