npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-tracking

v0.2.3

Published

Use Tracking is a custom React hook with a configurable Tracking component designed to enable simple and effective analytics and event tracking in all your Next.js applications.

Downloads

1,417

Readme

Use Tracking

npm version npm downloads

Use Tracking is a custom React hook with a configurable Tracking component designed to enable simple and effective analytics and event tracking within your Next.js applications.

If you find this package useful, please consider starring it on GitHub! Your support motivates further development and improvements.

Table of Contents

Features

  • Track page views with a unique session ID
  • Record click events on customizable HTML tags
  • Send event data to any specified action handler, including logging to the console during development
  • Customize tracking attributes to ignore or include as needed

Installation

Install via Bun:

bun add use-tracking

Or using npm:

npm install use-tracking

Usage

Below is a basic example of how to use the useTracking hook in a React component:

'use client'

import { useTracking } from 'use-tracking'

export default function Page() {
  useTracking()

  return (
    <button className="text-xs" data-action="test-button">
      Click Me!
    </button>
  )
}

Output:

// Event: pageview on initial render
Event: {
  url: '/example',
  event: 'pageview',
  timestamp: '2024-12-05T15:21:45.609Z',
  sessionId: '2b61fb421f81d84dbfc161f677906eba'
}

// Event: button click
Event: {
  url: '/example',
  event: 'buttonclick',
  timestamp: '2024-12-05T15:21:45.609Z',
  sessionId: '2b61fb421f81d84dbfc161f677906eba',
  // stringified attributes object
  attributes: {
    class: 'text-xs',
    'data-action': 'test-button',
  },
}

Recommended: Usage with Tracking Component

It is recommended to use the TrackingProvider in a layout component that is rendered on every page. This enables you to track page views and click events across your entire application.

Step 1: Create a Next.js Provider Component

Path: src/components/tracking-provider.tsx

'use client'

import { TrackingClientProvider } from 'use-tracking'

export default function TrackingProvider({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <TrackingClientProvider
      config={{
        action: (event) =>
          fetch('/api/analytics', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(event),
          }),
      }}
    >
      {children}
    </TrackingClientProvider>
  )
}

Step 2: Add the TrackingProvider to Your Layout Component

Path: src/app/layout.tsx

import TrackingProvider from '../components/tracking-provider'

export default function Layout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
    <html lang="en">
      <body>
        <TrackingProvider>{children}</TrackingProvider>
      </body>
    </html>
  )
}

Step 3: Make Sure to Set Up an API Route

Path: src/app/api/analytics/route.ts

export async function POST(request: Request) {
  const event = await request.json()

  // Add your logic here, such as updating the database

  console.log(event)

  return Response.json({ success: true })
}

Usage for Specific Pages

If you only want to track events on specific pages, you can use the useTracking hook directly in those components.

Step 1: Create a Next.js Client Hook

Path: src/app/dashboard/page.tsx

'use client'

import { useTracking } from 'use-tracking'

export default function Page() {
  useTracking({
    action: (event) => {
      fetch('/api/analytics/dashboard', {
        method: 'POST',
        body: JSON.stringify(event),
      })
    },
  })

  return (
    <button className="text-xs" data-action="test-button">
      Click Me!
    </button>
  )
}

Step 2: Make Sure to Set Up an API Route

Path: src/app/api/analytics/dashboard/route.ts

export async function POST(request: Request) {
  const event = await request.json()

  // Add your logic here, such as updating the database

  console.log(event)

  return Response.json({ success: true })
}

Configuration Options

The useTracking hook accepts an options object with the following properties:

  • prefix: (string)

    A string used to filter attributes by prefix. Only attributes that start with this prefix will be tracked.

useTracking({
  prefix: 'data-',
})
  • ignore: (string[])

    An array of attribute name patterns to ignore. Useful for excluding irrelevant attributes.

useTracking({
  ignore: ['aria-'],
})

This will ignore all attributes that start with aria-.

  • meaningfulTags: (string[])

    An array of HTML tags considered meaningful for click events. For example, ['A', 'BUTTON'] to track link clicks and button presses.

useTracking({
  meaningfulTags: ['A', 'BUTTON'],
})
  • action: (function)

    A callback function called with the event data when tracking occurs. If not provided, events are logged to the console in development mode.

useTracking({
  action: (data) => {
    console.log('Event:', data)
  },
})

Contributions

Contributions to use-tracking are welcome! Please fork the project and submit a pull request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Created by Neeraj Dalal. For queries, you can reach out at [email protected].