nova-hooks
v2.2.0
Published
Highly-optimized, zero-configuration React event tracking and telemetry utility supporting Socket.IO, native WebSockets, and stateless HTTP Beacon streams.
Maintainers
Readme
nova-hooks
A highly-optimized, zero-configuration event tracking utility for capturing user interactions and page visits in React applications. Built with a custom, lightweight EventBus and socket.io-client.
✨ Features
- Zero-Config Tracking: Automatically captures clicks on buttons, links, and interactive elements without needing manual attributes!
- True Page Dwell Time: Uses the native Page Visibility API to calculate the actual active time spent on a page (pauses when the user switches tabs).
- Network Optimized: Employs a built-in 1-second debouncing and click-batching mechanism to minimize network overhead.
- Ultra-Lightweight: Zero dependencies (other than
socket.io-client). Fully framework-agnostic core logic. - Auto-Enriched Context: Automatically attaches
PageUrl,PageTitle,Project, andCreatedDateto every single event payload. - SSR Safe: Fully compatible with Next.js and Remix.
🚀 Getting Started
1. Install
yarn add nova-hooksnpm i nova-hooks2. Initialization (Choose Your Transport!)
nova-hooks features a flexible Multi-Transport Pipeline supporting three robust telemetry protocols. Choose the transport that best fits your infrastructure (for a complete working implementation, see our App.tsx playground):
Option A: Socket.IO (Default)
Perfect for existing socket-enabled backends requiring connection recovery out-of-the-box.
import { connectSocket } from "nova-hooks"
import { useEffect } from "react"
const App = () => {
useEffect(() => {
connectSocket("http://localhost:3000/socket/client", "App Name")
}, [])
// app code...
}Option B: Native WebSockets
Eliminates all third-party client dependency overhead. A lightweight, full-duplex pipeline with automatic offline queuing.
import { connectWebSocket } from "nova-hooks"
import { useEffect } from "react"
const App = () => {
useEffect(() => {
connectWebSocket("ws://localhost:5000", "App Name")
}, [])
// app code...
}Option C: HTTP POST / Beacon (Stateless)
Ideal for serverless endpoints, REST ingestion APIs, or high-traffic setups. Automatically leverages the native browser navigator.sendBeacon API during page unmounts to guarantee dwell-time metrics delivery, with a silent, asynchronous fetch fallback.
import { connectHttp } from "nova-hooks"
import { useEffect } from "react"
const App = () => {
useEffect(() => {
connectHttp("https://api.analytics.com/events", "App Name", {
transportOptions: {
useBeacon: true,
headers: {
Authorization: "Bearer your-token-key-123" //Optional
}
}
})
}, [])
// app code...
}🛠️ Usage Examples
1. Zero-Config Global Click Tracking
Place useGlobalClickTracker in your authenticated layout. It will automatically listen to the DOM and seamlessly track clicks on any <button>, <a>, or cursor: pointer element!
import { useGlobalClickTracker } from "nova-hooks"
const ProtectedLayout = ({ children }) => {
const { user } = useAuth()
// Magic happens here! Tracks all UI clicks across the entire app.
useGlobalClickTracker(user?.empId, user?.roleId)
return <>{children}</>
}Note: It will intelligently extract labels from innerText, title, aria-label, or auto-generate a fallback CSS Path!
2. Explicit Tracking (Optional Overrides)
If you want to override the auto-detected name for a specific button, just attach the data-nova-* attributes (you can use standard ActionTypes or pass any custom string):
<button data-nova-track-id="Custom Task Action" data-nova-track-type="Button">
Track Me Specifically
</button>3. Accurate Page Dwell Time
Track exactly how long a user actively stares at a specific page/component. The timer pauses if they switch tabs or minimize the browser!
import { usePageTimeTracker } from "nova-hooks"
export const Dashboard = () => {
const { user } = useAuth()
// Tracks active dwell time and emits it automatically when the user leaves the page
usePageTimeTracker("Home Dashboard", user?.empId, user?.roleId)
return <div>Welcome to the Dashboard</div>
}4. Manual / Imperative Tracking
If you need to track events programmatically (like inside an API success callback), use the withEvent method. You can also pass any custom dynamic properties you need!
import { withEvent } from "nova-hooks"
const doLogin = () => {
api.login().then(() => {
withEvent({
Action: "Login Success",
ActionType: "Login",
EmpId: "EMP-123",
EmpRole: "Admin",
Count: 1,
// Dynamic custom payload:
AuthenticationMethod: "SSO",
LoginDurationMs: 430
})
})
}📦 Exports & Types
| Name | Type | Description |
| ----------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| ActionType | object | Predefined enum-like values: "Button", "Menu", "Login", "Link" |
| PageVisitAction | string | Constant string "Page Visit" used for tracking page visits |
| connectSocket | (socketUrl: string, project: string, options?: ConnectionOptions) => void | Connects generic multi-transport socket connection. |
| connectWebSocket | (url: string, project: string, options?: Omit<ConnectionOptions, "transport">) => void | Helper wrapper to connect lightweight native WebSockets. |
| connectHttp | (url: string, project: string, options?: Omit<ConnectionOptions, "transport">) => void | Helper wrapper to connect stateless HTTP POST / Beacon. |
| disconnectSocket | () => void | Disconnects and cleans up the active socket connection. |
| withEvent | (eventData: EventData, callback?: Function) => void | Emits a structured event optionally after running a callback. |
| useGlobalClickTracker | (empId?: string, roleId?: string) => void | React hook to automatically track global click events. |
| usePageTimeTracker | (action: string; empId?: string; empRole?: string) => void | React hook to track active time spent on a page via the Visibility API. |
EventData Structure
All events are automatically enriched with Project, PageUrl, PageTitle, and an ISO CreatedDate.
| Property | Type | Description |
| ------------ | ----------------------------------------------------------------- | --------------------------------------------------------------- |
| ActionType | string (Loose Autocomplete) | Type of the action (e.g. "Button", "Page Visit"). |
| Action | string | Specific action performed (extracted from DOM or manually set). |
| EmpId | string | Unique identifier of the employee. |
| EmpRole | string | Role of the employee performing the action. |
| Count | number (only when ActionType is not PageVisitAction) | Number of rapid occurrences of the action (batched). |
| Duration | number (seconds, only when ActionType is PageVisitAction) | Duration of the active visit in seconds. |
| [key: string]| any | You can attach any arbitrary custom properties to the payload! |
