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

dhis2-cache-busting

v1.1.0

Published

Cache-busting solution for DHIS2 React applications

Readme

DHIS2 Cache Busting

npm version Publish to npm License Downloads

Cache-busting solution for DHIS2 React applications. Ensures users always see the latest version of your app by implementing automatic version checking, cache invalidation, and update notifications.

Features

Core Features

  • Automatic version increment during build
  • Runtime update detection every 5 minutes (configurable)
  • Smart cache clearing (localStorage, sessionStorage, service worker caches)
  • User notifications when updates are available
  • Build timestamp tracking for precise version detection
  • Service worker enhancement with version-based caching

DHIS2-Specific Features

  • HTML5 AppCache handling - Updates manifest version comments automatically
  • App JSON cache-busting - Adds version parameters to DHIS2 app descriptors
  • Bundle hashing - Adds content hashes to static assets without existing hashes
  • DHIS2 cache clearing - Comprehensive clearing including IndexedDB and app-specific storage
  • Zero configuration - works out of the box with intelligent defaults

Installation

npm install dhis2-cache-busting
# or
yarn add dhis2-cache-busting

Quick Start

1. Install the package

npm install dhis2-cache-busting

2. Update your HTML template

Add these meta tags to your public/index.html:

<!-- Cache-busting meta tags -->
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="app-version" content="__APP_VERSION__" />
<meta name="build-timestamp" content="__BUILD_TIMESTAMP__" />

3. Update your package.json

Replace your build script and add the cache-busting configuration:

{
  "name": "my-dhis2-app",
  "scripts": {
    "build": "dhis2-cache-bust",
    "build:standard": "d2-app-scripts build"
  },
  "cacheBusting": {
    "appName": "my-dhis2-app",
    "dhis2": {
      "handleAppCache": true,
      "handleAppJson": true,
      "bundleHashing": true
    }
  }
}

4. Initialize in your app entry point

Add to your main React component (e.g., src/App.js or src/Main.js):

import React, { useEffect } from 'react';
import { initializeCacheManager } from 'dhis2-cache-busting';

const App = () => {
  useEffect(() => {
    // Initialize cache management when app starts
    initializeCacheManager({
      appName: 'my-dhis2-app', // Must match package.json
      checkInterval: 5 * 60 * 1000, // Check every 5 minutes
    });
  }, []);

  return (
    <div>
      {/* Your app content */}
    </div>
  );
};

export default App;

5. Build and test

npm run build

The build will:

  • Auto-increment your version in package.json
  • Replace __APP_VERSION__ and __BUILD_TIMESTAMP__ in your HTML
  • Generate enhanced assets with cache-busting parameters
  • Create a version.json file with build metadata

API Reference

Core Functions

initializeCacheManager(options)

Main entry point - Initialize the cache management system. Call this once when your app starts.

Options:

  • appName (string): Unique app identifier (default: 'dhis2-app') - must match package.json
  • checkInterval (number): Update check interval in milliseconds (default: 300000 = 5 minutes)
  • customNotification (function): Custom notification handler (optional)
import { initializeCacheManager } from 'dhis2-cache-busting';

// Basic initialization
initializeCacheManager({
  appName: 'my-dhis2-app'
});

// Advanced initialization with custom notification
initializeCacheManager({
  appName: 'user-management-app',
  checkInterval: 10 * 60 * 1000, // 10 minutes
  customNotification: () => {
    // Use DHIS2 UI notifications instead of browser confirm
    showNotification('New version available!');
  }
});

Version Information

import { getAppVersion, getBuildTimestamp } from 'dhis2-cache-busting';

const version = getAppVersion();      // Returns current app version (e.g., "1.2.3")
const timestamp = getBuildTimestamp(); // Returns build timestamp

Manual Cache Management

import {
  checkForUpdates,
  clearAppCache,
  clearDHIS2Caches,
  clearDHIS2IndexedDB,
  forceReload,
  getAppVersion,
  getBuildTimestamp
} from 'dhis2-cache-busting';

// Check for updates manually
const hasUpdate = await checkForUpdates();

// Clear all app caches (including DHIS2-specific)
await clearAppCache('my-app');

// Clear only DHIS2-specific caches
await clearDHIS2Caches('my-app', {
  clearAppCache: true,    // Clear HTML5 AppCache
  clearIndexedDB: true    // Clear DHIS2 IndexedDB data
});

// Clear DHIS2 IndexedDB databases
await clearDHIS2IndexedDB('my-app');

// Force reload with cache bypass
forceReload();

// Get current version info
const version = getAppVersion();
const timestamp = getBuildTimestamp();

Configuration

Build Configuration

Configure in package.json:

{
  "cacheBusting": {
    "autoIncrementVersion": true,
    "buildCommand": "yarn build:standard",
    "indexHtmlPath": "build/app/index.html",
    "manifestPath": "build/app/manifest.json",
    "serviceWorkerPath": "build/app/service-worker.js",
    "appName": "my-dhis2-app",
    "dhis2": {
      "handleAppCache": true,
      "appCachePath": "build/app/appcache.manifest",
      "alternateAppCachePath": "build/app/cache.manifest",
      "removeAppCache": false,
      "handleAppJson": true,
      "appJsonPath": "build/app",
      "bundleHashing": true,
      "clearIndexedDB": true
    }
  }
}

DHIS2-Specific Configuration

  • handleAppCache: Enable AppCache manifest version management (default: true)
  • appCachePath: Primary AppCache manifest file path
  • alternateAppCachePath: Alternative manifest path (e.g., cache.manifest)
  • removeAppCache: Remove AppCache entirely for modern caching (default: false)
  • handleAppJson: Enable app JSON descriptor cache-busting (default: true)
  • appJsonPath: Directory containing DHIS2 app JSON files
  • bundleHashing: Add content hashes to unhashed static assets (default: true)
  • clearIndexedDB: Include IndexedDB clearing in cache management (default: true)

Runtime Configuration

// Custom notification with DHIS2 UI
import { showNotification } from '@dhis2/ui';

initializeCacheManager({
  appName: 'my-app',
  checkInterval: 5 * 60 * 1000,
  customNotification: () => {
    showNotification({
      message: 'A new version is available. Refresh to update.',
      type: 'info',
      actions: [
        { label: 'Refresh', onClick: forceReload },
        { label: 'Later', onClick: () => {} }
      ]
    });
  }
});

How It Works

Build Process

  1. Version Management: Auto-increments patch version in package.json
  2. Standard Build: Executes your configured build command (e.g., d2-app-scripts build)
  3. Template Processing: Replaces __APP_VERSION__ and __BUILD_TIMESTAMP__ placeholders
  4. Asset Enhancement: Adds cache-busting parameters to asset references
  5. Service Worker: Enhances with version-based cache keys
  6. DHIS2 AppCache: Updates manifest version comments and timestamps
  7. App JSON Enhancement: Adds cache-busting to DHIS2 app descriptors
  8. Bundle Hashing: Adds content hashes to static assets
  9. Metadata: Creates version.json with build information

Runtime Process

  1. Initialization: Checks for version changes since last visit
  2. Cache Clearing: Clears outdated cache if version changed
  3. Update Monitoring: Polls for new versions every 5 minutes
  4. User Notification: Shows update dialog when new version detected
  5. Cache Refresh: Clears cache and reloads when user accepts update

Version Detection

The system compares build timestamps in the current page vs. the server:

// Current page timestamp
const current = document.querySelector('meta[name="build-timestamp"]').content;

// Server timestamp (fetched fresh)
const response = await fetch('/index.html?t=' + Date.now());
const serverTimestamp = extractTimestampFromHTML(response);

// Update available if timestamps differ
return serverTimestamp !== current;

Integration with DHIS2 Apps

With DHIS2 UI Components

import { NoticeBox, Button } from '@dhis2/ui';

const customNotification = () => {
  return (
    <NoticeBox
      title="Update Available"
      status="info"
      actions={
        <Button onClick={forceReload}>
          Update Now
        </Button>
      }
    >
      A new version of the application is available.
    </NoticeBox>
  );
};

With App Runtime

import { useConfig } from '@dhis2/app-runtime';

const MyApp = () => {
  const { appName } = useConfig();
  
  useEffect(() => {
    initializeCacheManager({ appName });
  }, [appName]);
  
  return <div>My App</div>;
};

Troubleshooting

Common Setup Issues

Build fails with "Command not found"

Problem: dhis2-cache-bust command not found
Solution:

# Install package first
npm install dhis2-cache-busting

# Ensure your package.json has the build script
"scripts": {
  "build": "dhis2-cache-bust",
  "build:standard": "d2-app-scripts build"  // ← This must exist!
}

"build:standard script not found"

Problem: Missing the standard build command
Solution: Add your actual build command:

"scripts": {
  "build:standard": "d2-app-scripts build"  // or "webpack --mode=production", etc.
}

Meta tags not replaced in HTML

Problem: __APP_VERSION__ still shows in built HTML
Solution:

  1. Check indexHtmlPath in your config points to correct file
  2. Ensure meta tags are in your HTML template (not hardcoded values)
  3. Verify the build actually runs (check console output)

Cache not clearing / updates not detected

Problem: App doesn't detect new versions
Solution:

  1. Check meta tags are present in built HTML:
    <meta name="app-version" content="1.2.3" />
    <meta name="build-timestamp" content="1640995200000" />
  2. Verify initializeCacheManager is called:
    // In your main component
    useEffect(() => {
      initializeCacheManager({ appName: 'my-dhis2-app' });
    }, []);
  3. Check appName matches between initializeCacheManager and package.json

❌ TypeScript errors

Problem: TypeScript compilation errors
Solution: Install type definitions if needed:

npm install --save-dev @types/react

Runtime Issues

Updates Not Being Detected

  • Open browser DevTools → Network tab and refresh
  • Check if /index.html?t=... requests are being made every 5 minutes
  • Verify timestamps in meta tags change between builds
  • Check browser console for cache-busting logs

Cache Not Clearing

  • Open DevTools → Application → Storage
  • Verify localStorage has {appName}-version key
  • Check if service worker caches are being cleared
  • For DHIS2: Verify IndexedDB and AppCache are cleared

DHIS2-Specific Issues

AppCache Problems

  • Check manifest file has version comment: # v1.2.3
  • Verify manifest MIME type is text/cache-manifest
  • Consider disabling AppCache: "removeAppCache": true

App JSON Not Updating

  • Verify cache-busting parameters added to JSON files
  • Check DHIS2 server cache headers for /apps/ endpoints
  • Ensure handleAppJson: true in configuration

Getting Help

If you're still having issues:

  1. Check the build output - look for error messages
  2. Inspect the built files - verify meta tags are replaced
  3. Check browser console - look for cache-busting logs
  4. Test in incognito mode - rules out existing cache issues