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 🙏

© 2026 – Pkg Stats / Ryan Hefner

screen-time-track

v2.0.0

Published

Library to measure the screen time of a user on each page. Works with vanilla JS, React, and any framework.

Readme

Screen Time Tracker

A lightweight, framework-agnostic library to measure how long users spend on each page of your web application. Works out of the box with Vanilla JS, React (Vite), Next.js, and any other framework.

Tracking pauses automatically when the tab loses focus or is minimized, and resumes when the user comes back — no configuration needed.

Features

  • Automatic pause/resume on tab visibility change
  • SPA route-aware: detects pushState / replaceState navigation — each route is timed independently
  • currentPageTime — live HH:MM:SS timer that updates every second, no tab switch needed
  • Smart storage: IndexedDBlocalStoragein-memory (auto-detected)
  • Full TypeScript support with bundled .d.ts types
  • SSR-safe: does nothing on the server, no crashes in Next.js
  • React hook useScreenTime() with reactive state
  • Dual module output: ESM + CJS

Install

npm install screen-time-tracker

Storage Strategy

The library automatically selects the best available storage driver — no setup required:

| Environment | Driver used | |---|---| | Modern browser | IndexedDB | | Browser without IndexedDB | localStorage | | Server (SSR) / no window | In-memory (no persistence) |

Data structure

{
  url: "https://myapp.com/dashboard",
  durations: [
    { visit: 1, time: 3200 },   // milliseconds
    { visit: 2, time: 8500 }
  ]
}

Usage: Vanilla JS

import { ScreenTimeTracker } from 'screen-time-tracker';

const tracker = new ScreenTimeTracker();

// Start tracking the current page
tracker.startTracking();

// Stop and save when the user leaves
window.addEventListener('beforeunload', () => tracker.stopTracking());

// Get total time per page (HH:MM:SS)
const times = await tracker.calculateTotalTime();
console.log(times);
// { 'https://myapp.com/home': '00:02:30', 'https://myapp.com/about': '00:01:05' }

// Get time for a specific URL
const time = await tracker.getPageTime('https://myapp.com/home');
console.log(time); // '00:02:30'

// Export all raw data as JSON string
const json = await tracker.exportData();

// React to every save event
tracker.onSave((record) => {
  console.log('Saved:', record.url, record.durations);
});

// Clear all stored data
await tracker.reset();

// Check which storage driver is active
console.log(tracker.getStorageDriver()); // 'indexeddb' | 'localstorage' | 'memory'

Usage: React (Vite)

Import the hook from the /react subpath. Place useScreenTime() at the top level of your app so tracking covers every route.

Basic — tracking only

// App.tsx
import { useScreenTime } from 'screen-time-tracker/react';

export default function App() {
  useScreenTime(); // one line — starts and stops automatically

  return <Router />;
}

With data and controls

// Dashboard.tsx
import { useScreenTime } from 'screen-time-tracker/react';

export default function Dashboard() {
  const { data, totalTime, currentPageTime, isTracking, exportData, reset } = useScreenTime();

  return (
    <div>
      <h1>Time per page</h1>

      {/* Live timer for the current page — updates every second */}
      <p>Time on this page: {currentPageTime}</p>

      {/* Persisted totals for all visited pages */}
      <ul>
        {data.map((page) => (
          <li key={page.url}>
            <strong>{page.url}</strong> — {totalTime[page.url]}
          </li>
        ))}
      </ul>

      <p>Status: {isTracking ? 'Active' : 'Paused'}</p>

      <button onClick={exportData}>Export JSON</button>
      <button onClick={reset}>Clear data</button>
    </div>
  );
}

Note: currentPageTime shows the live elapsed time for the page currently being visited. totalTime shows the accumulated saved time from all previous sessions — it updates after each navigation or tab switch.

Hook return values

dataPageRecord[]

Direct value, no Promise. An array with one entry per visited URL. Each entry contains the URL and an array of individual visit durations in milliseconds.

const { data } = useScreenTime();

// Each PageRecord looks like:
// { url: 'https://myapp.com/home', durations: [{ visit: 1, time: 3200 }, { visit: 2, time: 8500 }] }

data.map(page => (
  <p key={page.url}>
    {page.url} — {page.durations.length} visit(s)
  </p>
));

totalTimeRecord<string, string>

Direct value, no Promise. An object where each key is a URL and each value is the total accumulated time in HH:MM:SS. This value is persisted — it updates after each navigation or tab switch, not in real time.

const { totalTime } = useScreenTime();

// Read time for a specific page
const homeTime = totalTime['https://myapp.com/home']; // e.g. '00:02:30'

// Render all pages
Object.entries(totalTime).map(([url, time]) => (
  <p key={url}>{url}: {time}</p>
));

currentPageTimestring

Direct value, no Promise. A live HH:MM:SS string that updates every second while the user is on the current page. It reflects the active session that has not been saved yet — it resets to '00:00:00' on each route change.

const { currentPageTime } = useScreenTime();

// Use it as a live ticker
<p>Time on this page: {currentPageTime}</p> // '00:00:45', '00:00:46', ...

currentPageTime and totalTime complement each other: use currentPageTime for the live session and totalTime for the historical total.


isTrackingboolean

Direct value, no Promise. true when the tracker is actively counting time; false when paused (tab hidden or minimized).

const { isTracking } = useScreenTime();

<span>{isTracking ? '🟢 Active' : '🔴 Paused'}</span>

exportData() => Promise<string>

A function that returns a Promise. Calling it resolves with all stored records serialized as a formatted JSON string. Useful for debugging or sending data to an analytics endpoint.

const { exportData } = useScreenTime();

// With async/await
const json = await exportData();
console.log(json);
// [
//   { "url": "https://myapp.com/home", "durations": [...] },
//   ...
// ]

// Or with .then()
<button onClick={() => exportData().then(console.log)}>Export</button>

reset() => Promise<void>

A function that returns a Promise. Clears all stored data from IndexedDB/localStorage and resets data, totalTime and currentPageTime back to their initial empty state.

const { reset } = useScreenTime();

// With async/await
await reset();

// Or directly on a button
<button onClick={reset}>Clear all data</button>

Usage: Next.js

IndexedDB and window do not exist on the server. The library handles this automatically — it simply does nothing during SSR and activates on the client.

App Router (app/)

Add 'use client' to any component that uses the hook or the class directly.

// app/layout.tsx
import Tracker from '@/components/Tracker';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <Tracker />
        {children}
      </body>
    </html>
  );
}
// components/Tracker.tsx
'use client';

import { useScreenTime } from 'screen-time-tracker/react';

export default function Tracker() {
  useScreenTime(); // tracking starts here, safe on server
  return null;
}

Pages Router (pages/)

// pages/_app.tsx
import { useScreenTime } from 'screen-time-tracker/react';
import type { AppProps } from 'next/app';

export default function MyApp({ Component, pageProps }: AppProps) {
  useScreenTime();
  return <Component {...pageProps} />;
}

Tip: In Next.js the hook detects SSR automatically — no need to wrap it in typeof window !== 'undefined' checks.


Full API Reference — ScreenTimeTracker

| Method | Returns | Description | |---|---|---| | startTracking() | void | Starts timing the current page | | stopTracking() | Promise<void> | Stops timing and saves the duration | | getElapsedTime() | number | Milliseconds elapsed in the current running session (0 if not tracking) | | exportData() | Promise<string> | All records serialized as a JSON string | | calculateTotalTime() | Promise<Record<string, string>> | Total saved time per URL in HH:MM:SS | | getPageTime(url?) | Promise<string> | Saved time for one URL (defaults to current page) | | getAllRecords() | Promise<PageRecord[]> | Raw records for all pages | | onSave(callback) | void | Register a callback fired after each save | | deleteIndexDB() | Promise<void> | Clears all stored data | | reset() | Promise<void> | Alias for deleteIndexDB() | | getStorageDriver() | 'indexeddb' \| 'localstorage' \| 'memory' | Active storage driver | | destroy() | void | Removes event listeners (call when unmounting in SPAs) |


Tips

  • React Router / TanStack Router / Next.js App Router: place useScreenTime() in your root layout component so it mounts once and handles all route changes automatically.
  • totalTime vs currentPageTime: totalTime reflects persisted data (updated after each navigation); currentPageTime is the live ticker for the page you are on right now. Use both together for a complete picture.
  • Vanilla JS SPAs: call tracker.stopTracking() before navigating and tracker.startTracking() on the new route. Use tracker.getElapsedTime() to read the live session duration without saving it.
  • Testing: use tracker.getStorageDriver() to verify the correct driver is being used in your environment.
  • Privacy: all data is stored locally in the user's browser — nothing is sent to any server.

Contributing

Contributions are welcome! Feel free to open issues or pull requests in the repository: screen-time-tracker

License

Screen Time Tracker is released under the MIT License.

Authors ✒️

  • Jonathan Amaya - Systems Engineer - Full Stack Developer - TatanLion

⌨️ with ❤️ by TatanLion 😊