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

nanolytics

v1.0.0

Published

Tiny analytics library which can sync with a remote server periodically

Downloads

86

Readme

wakatime Node.js CI GitHub License GitHub Release GitHub stars

codecov Size typescript npm npm GitHub issues 0 dependencies!

Code Smells Coverage Lines of Code Quality Gate Status Bugs Reliability Rating Security Rating Technical Debt Maintainability Rating Vulnerabilities

nanolytics

Nanolytics is a minimalistic, 0-dependency lightweight client-side analytics tracking library. It allows you to capture events, store them locally, and submit them to a server after a predefined threshold. The library focuses on simplicity and efficiency, allowing developers to easily integrate event tracking into their applications with minimal overhead.

Features

  • 🟢 Tiny and minimal: Lightweight library focused on keeping things simple.
  • ⏳ Event batching: Stores events in localStorage and submits them periodically or based on event count.
  • 🔌 Flexible submission: Client provides custom event submission logic through a callback.
  • 🧩 Easy integration: Simple API to start tracking events immediately.

Installation

To install nanolytics, use npm or yarn:

npm install nanolytics
# or
yarn add nanolytics
# or
pnpm i nanolytics

Requirements

Node.js >= 20.0.0

Usage

1. Initialize the library

To start using Nanolytics, you need to initialize the library with your custom submission logic. This is done via the init() function, where you provide a callback that will handle the submission of analytics data to your server.

import { init, record } from 'nanolytics';

// Example submission function that sends data to your API
const submitAnalytics = async (userInfo, events) => {
    const response = await post('analytics', { state: userInfo, data: events });
    return response; // Ensure the response is properly handled on the client side, a 200 OK will cause the library to flush its store
};

// Initialize the library with your submit function
init(submitAnalytics, { maxEventsLimitUntilSubmit: 150 });

By default the library will automatically trigger a submission after 100 events are queued up if you do not explicitly set the maxEventsLimitUntilSubmit value.

The submitAnalytics function will be called when it’s time to flush stored events to the server. It receives two arguments:

  • userInfo: Your custom user information (retrieved using getUserInfo() in the library).
  • events: An array of event objects to be submitted.

2. Record events

Use the record() function to capture user interactions or any event you want to track.

// Record a simple event
record('ButtonClicked');

// Record an event with context
record('FormatByRule', 'ruleName', { from: 'Freewrite' });

Each event consists of a name, a timestamp, and optional context data. These events are stored in localStorage until they are submitted to your server based on the configured threshold.

3. Event submission and storage

  • Events are stored in localStorage under the key events.
  • Once the number of stored events exceeds the threshold (100 by default), they will be submitted automatically.
  • The events will also be submitted when the user closes the page or switches browser tabs (tracked by visibility changes).

Customizing the submission logic

You can implement your own submission logic using any API interaction library, such as axios, fetch, or another HTTP client.

Here’s an example using axios:

import axios from 'axios';

const submitAnalytics = async (userInfo, events) => {
    try {
        const response = await axios.put('/analytics-endpoint', { state: userInfo, data: events });
        return response.data;
    } catch (error) {
        console.error('Analytics submission failed:', error);
    }
};

init(submitAnalytics);

Example Integration

You can use Nanolytics to track user actions throughout your application. For example:

// Track when a user starts a new session
record('StartSession');

// Track when a user interacts with a button
const handleButtonClick = () => {
    record('ButtonClicked', 'HomePage');
};

// Track form submission with additional context
record('FormSubmitted', 'SignUpForm', { referrer: 'Homepage' });

Commit Events

You can use the commit() function to store and save events to localStorage when the user leaves the page or closes the window.

window.onbeforeunload = () => {
    commit(); // Commit and store events before the user navigates away
};

API Reference

init(submitFn: SubmitAnalyticsCallback, options: InitOptions)

Initializes the Nanolytics library and sets up event listeners.

  • submitFn: A function to handle the submission of analytics data.
  • options: Configuration options for initialization.
  • options.maxEventsLimitUntilSubmit: The maximum number of events before triggering a submission (default: 100).

record(event: string, context?: string, moreContext?: Record<string, any>)

Records a new event with a timestamp.

  • event: The name of the event to be tracked (e.g., 'ButtonClick').
  • context: (Optional) A string representing additional context for the event (e.g., a screen or component name).
  • moreContext: (Optional) A key-value map for additional context data.

commit()

Commits all current session events to localStorage and ends the session by recording an EndSession event.

clearEvents()

Clears all current session events in memory.

getSavedEvents()

Retrieves all events saved in localStorage.

deleteSavedEvents()

Deletes all events stored in localStorage.

getEvents()

Retrieves the current session's events from memory.

getUserInfo()

Retrieves user information such as language, platform, and user agent.

Contributing

If you'd like to contribute to the SDK, feel free to fork the repository and submit a pull request. Contributions are welcome!

License

This SDK is licensed under the MIT License.