react-audit-tracker

Simple, powerful audit tracking for React applications

🚀 TypeScript đŸ”Ĩ Firebase 💾 Local Storage 🌐 REST API
Get Started View on npm

đŸŽ¯ Try Live Demos

Experience react-audit-tracker instantly in your browser - no installation required!

🚀 Basic Demo

Zero backend setup. Works with localStorage out of the box.

Open Demo →

đŸ”Ĩ Firebase Demo

Cloud Firestore integration for serverless apps.

Open Demo →

🌐 API Demo

REST API backend integration example.

Open Demo →

💡 All demos include full source code - fork, edit, and experiment!

⚡ Quick Start

Install Package

npm install react-audit-tracker

Run Setup Wizard (Optional)

npx audit-tracker-setup

Interactive CLI wizard guides you through configuration with your preferred storage mode.

Wrap Your App

import { AuditProvider } from 'react-audit-tracker';

function App() {
  return (
    <AuditProvider mode="local">
      {/* Your app components */}
    </AuditProvider>
  );
}

Track Events

import { useAudit } from 'react-audit-tracker';

function MyComponent() {
  const { track } = useAudit();

  const handleAction = async () => {
    await track({
      action: 'BUTTON_CLICKED',
      entity: 'Button',
      entityId: 'submit-btn',
      description: 'User clicked submit button'
    });
  };

  return <button onClick={handleAction}>Submit</button>;
}
✅ That's it! You're now tracking user actions in your React app.

✨ Features

đŸŽ¯ Simple API

Clean, intuitive API with TypeScript support. Track events with just one function call.

🔄 Multiple Storage

Local Storage, Firebase Firestore, or your own REST API backend.

📊 Built-in UI

AuditTable component to display logs with pagination, sorting, and filtering.

⚡ Zero Config

Works out of the box with local storage. No setup required to get started.

🔒 Type Safe

Full TypeScript support with comprehensive type definitions.

🎨 Customizable

Custom columns, formatters, and filters for the audit table.

đŸ› ī¸ Setup Guide

Using the CLI Wizard

npx audit-tracker-setup

The wizard will:

Manual Setup

If you prefer to configure manually, follow these steps:

1. Install the package

npm install react-audit-tracker

2. Add AuditProvider to your app

Choose your storage mode and wrap your app:

import { AuditProvider } from 'react-audit-tracker';

function App() {
  return (
    <AuditProvider mode="local">
      <YourApp />
    </AuditProvider>
  );
}
â„šī¸ Local Storage
Perfect for development and small projects. No external setup required.
import { AuditProvider } from 'react-audit-tracker';

const firebaseConfig = {
  config: {
    apiKey: "your-api-key",
    authDomain: "your-project.firebaseapp.com",
    projectId: "your-project-id",
    storageBucket: "your-project.appspot.com",
    messagingSenderId: "123456789",
    appId: "your-app-id"
  },
  collectionName: 'audit_events'
};

function App() {
  return (
    <AuditProvider mode="firebase" firebaseConfig={firebaseConfig}>
      <YourApp />
    </AuditProvider>
  );
}
âš ī¸ Firebase Setup Required
1. Install Firebase SDK: npm install firebase
2. Create a Firebase project at console.firebase.google.com
3. Enable Firestore Database
4. Configure security rules (see documentation)
import { AuditProvider } from 'react-audit-tracker';

const apiConfig = {
  baseUrl: 'https://api.example.com'
};

function App() {
  return (
    <AuditProvider mode="api" apiConfig={apiConfig}>
      <YourApp />
    </AuditProvider>
  );
}
â„šī¸ API Requirements
Your API should implement:
â€ĸ POST /audit-logs - Create new audit event
â€ĸ GET /audit-logs - Fetch audit events with pagination

💾 Storage Modes

Local Storage

Browser-based storage. Perfect for development and small applications.

<AuditProvider mode="local">

Pros: No setup, instant, works offline
Cons: Limited to ~5MB, browser-specific, lost on clear cache

Firebase Firestore

Cloud-based NoSQL database. Ideal for production applications.

<AuditProvider mode="firebase" firebaseConfig={config}>

Pros: Scalable, real-time, cross-device, persistent
Cons: Requires Firebase account, costs at scale

REST API

Your own backend API. Full control over storage and logic.

<AuditProvider mode="api" apiConfig={{baseUrl: '...'}}>

Pros: Full control, custom logic, any database
Cons: Requires backend development

📚 Examples

Basic Event Tracking

import { useAudit } from 'react-audit-tracker';

function UserProfile() {
  const { track } = useAudit();

  const handleProfileUpdate = async (data) => {
    // Update profile logic...
    
    await track({
      action: 'PROFILE_UPDATED',
      entity: 'User',
      entityId: userId,
      userId: currentUser.id,
      userName: currentUser.name,
      description: 'User updated their profile',
      metadata: {
        fields: ['name', 'email'],
        previousValues: { name: 'John', email: 'old@email.com' }
      }
    });
  };
}

Tracking with Metadata

await track({
  action: 'DOCUMENT_CREATED',
  entity: 'Document',
  entityId: doc.id,
  description: 'Created new document',
  metadata: {
    fileName: doc.name,
    fileSize: doc.size,
    fileType: doc.type,
    category: doc.category,
    changes: [
      { field: 'status', oldValue: null, newValue: 'draft' }
    ]
  }
});

Display Audit Logs

import { AuditTable } from 'react-audit-tracker';

function AuditLogsPage() {
  return (
    <div>
      <h1>Audit Logs</h1>
      <AuditTable 
        pageSize={20}
        showFilters={true}
      />
    </div>
  );
}

Custom Columns

import { AuditTable } from 'react-audit-tracker';

const customColumns = [
  {
    key: 'timestamp',
    label: 'Date',
    width: '180px',
    sortable: true,
    render: (value) => new Date(value).toLocaleString()
  },
  {
    key: 'action',
    label: 'Action',
    render: (value) => (
      <span className={`badge ${getActionColor(value)}`}>
        {value}
      </span>
    )
  }
];

function CustomAuditLogs() {
  return <AuditTable columns={customColumns} />;
}

📖 API Reference

AuditProvider Props

interface AuditProviderProps {
  mode: 'local' | 'firebase' | 'api';
  firebaseConfig?: FirebaseConfig;  // Required if mode='firebase'
  apiConfig?: ApiConfig;             // Required if mode='api'
  children: ReactNode;
}

useAudit Hook

const { track, loading, error } = useAudit();

// track function
await track({
  action: string;           // Required: Action type (e.g., 'USER_LOGIN')
  entity: string;           // Required: Entity type (e.g., 'User')
  entityId: string;         // Required: Entity identifier
  userId?: string;          // Optional: User who performed action
  userName?: string;        // Optional: User's display name
  description?: string;     // Optional: Human-readable description
  metadata?: any;           // Optional: Additional data
});

AuditTable Props

interface AuditTableProps {
  columns?: ColumnConfig[];  // Custom column definitions
  pageSize?: number;         // Items per page (default: 10)
  showFilters?: boolean;     // Enable filtering (default: false)
  className?: string;        // Custom CSS class
}

🔧 Troubleshooting

Error: useAudit must be used within an AuditProvider

Solution: Make sure your component is wrapped with AuditProvider:
<AuditProvider mode="local">
  <YourComponent />  {/* This component can use useAudit */}
</AuditProvider>

Firebase: Permission Denied

Solution: Update Firestore security rules:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /audit_events/{document} {
      allow read, write: if request.auth != null;  // Authenticated users
      // OR for development:
      allow read, write: if true;  // Warning: Open access
    }
  }
}

TypeScript Errors

Solution: Package includes full TypeScript definitions. Make sure you're using TypeScript 4.0+

đŸ’Ŧ Support & Resources

📖 Documentation

GitHub Pages npm Package GitHub Repository

📧 Need Help?

For bug reports, feature requests, or any questions, contact us:

Email: ai.rohanv@gmail.com

We typically respond within 24-48 hours