Skip to content

๐Ÿš€ Production-ready TypeScript library for offline-first request queuing with automatic sync, priority handling, and smart retry logic. Perfect for PWAs and mobile apps.

License

Notifications You must be signed in to change notification settings

Sakil9051/offline-queue-engine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

4 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Offline Queue Engine ๐Ÿš€

npm version License: MIT

Reliable offline-first request queue for web & Node.js apps

๐ŸŽฎ Live Interactive Demo | ๐Ÿ“ฆ npm Package | ๐Ÿ’ป Demo Source

Queue HTTP requests when offline and automatically sync them when the network reconnects. Perfect for PWAs, mobile apps, fintech, delivery apps, and any application requiring reliable data persistence.

โœจ Features

  • ๐Ÿ”„ Automatic Sync - Detects network changes and syncs queued requests
  • ๐Ÿ“ฆ Persistent Storage - IndexedDB (50MB+), LocalStorage, or Memory adapters
  • ๐ŸŽฏ Priority Queue - High, normal, low priority levels
  • โ™ป๏ธ Smart Retry Logic - Exponential backoff with configurable max retries
  • ๐Ÿช Lifecycle Hooks - onSuccess, onFailure, onRetry callbacks
  • ๐ŸŒ Universal - Works in browser and Node.js environments
  • ๐ŸŽจ Framework Agnostic - Use with React, Vue, Angular, or vanilla JS
  • ๐Ÿ“˜ TypeScript First - Full type definitions included
  • ๐Ÿชถ Lightweight - Minimal dependencies

๐Ÿ“ฆ Installation

npm install offline-queue-engine

๐Ÿš€ Quick Start

Try it live: Interactive Demo

import { OfflineQueueEngine } from 'offline-queue-engine';

// Create queue instance
const queue = new OfflineQueueEngine({
  hooks: {
    onSuccess: (item) => console.log('โœ… Synced:', item),
    onFailure: (item, error) => console.error('โŒ Failed:', error),
    onRetry: (item, count) => console.log('๐Ÿ” Retry attempt:', count)
  }
});

// Add requests to queue
await queue.add({
  url: '/api/orders',
  method: 'POST',
  body: { item: 'Pizza', quantity: 2 },
  priority: 'high'
});

That's it! Requests are automatically:

  • โœ… Persisted to IndexedDB
  • โœ… Sent when online
  • โœ… Retried on failure
  • โœ… Synced on reconnect

๐Ÿ“– API Reference

Constructor

new OfflineQueueEngine(config?: QueueConfig)

Options:

Option Type Default Description
storage StorageAdapter IndexedDBStore Storage adapter (IndexedDB, LocalStorage, Memory)
hooks Hooks {} Lifecycle callbacks
autoSync boolean true Auto-sync on network reconnect
maxRetries number 5 Maximum retry attempts

Methods

add(request: CreateRequestInput): Promise<void>

Add a request to the queue.

await queue.add({
  url: '/api/save',
  method: 'POST',
  body: { name: 'John' },
  headers: { 'Authorization': 'Bearer token' },
  priority: 'high' // 'high' | 'normal' | 'low'
});

sync(): Promise<void>

Manually trigger queue processing.

await queue.sync();

size(): number

Get current queue size.

const pending = queue.size();
console.log(`${pending} requests pending`);

clear(): Promise<void>

Clear all queued requests.

await queue.clear();

isOnline(): boolean

Check network status.

if (queue.isOnline()) {
  console.log('Connected');
}

destroy(): void

Cleanup and remove event listeners.

queue.destroy();

๐ŸŽฏ Use Cases

Payment Apps

// Ensure payment requests are never lost
await queue.add({
  url: '/api/payments',
  method: 'POST',
  body: { amount: 99.99, userId: '123' },
  priority: 'high'
});

Form Submissions

// Save form data offline
await queue.add({
  url: '/api/leads',
  method: 'POST',
  body: formData,
  priority: 'normal'
});

Chat Applications

// Queue messages when offline
await queue.add({
  url: '/api/messages',
  method: 'POST',
  body: { text: 'Hello!', chatId: '456' },
  priority: 'high'
});

๐Ÿ”ง Advanced Configuration

Custom Storage Adapter

import { OfflineQueueEngine, LocalStorageStore } from 'offline-queue-engine';

const queue = new OfflineQueueEngine({
  storage: new LocalStorageStore()
});

All Lifecycle Hooks

const queue = new OfflineQueueEngine({
  hooks: {
    onSuccess: (item) => {
      console.log('Request succeeded:', item.url);
      // Update UI, show notification, etc.
    },
    onFailure: (item, error) => {
      console.error('Request failed permanently:', error);
      // Log to error tracking service
    },
    onRetry: (item, retryCount) => {
      console.log(`Retry ${retryCount} for ${item.url}`);
      // Show retry indicator in UI
    }
  },
  maxRetries: 3,
  autoSync: true
});

Custom Retry Strategy

import { shouldRetry, calculateBackoff } from 'offline-queue-engine';

// Check if request should retry
const retry = shouldRetry(500, 2, 5); // status, retryCount, maxRetries

// Calculate exponential backoff
const delay = calculateBackoff(2, 1000); // retryCount, baseDelay (ms)
// Returns: 4000ms (1s * 2^2)

๐ŸŒ Framework Examples

React

import { useEffect, useState } from 'react';
import { OfflineQueueEngine } from 'offline-queue-engine';

function App() {
  const [queue] = useState(() => new OfflineQueueEngine({
    hooks: {
      onSuccess: () => console.log('Synced!')
    }
  }));

  const handleSubmit = async (data) => {
    await queue.add({
      url: '/api/data',
      method: 'POST',
      body: data
    });
  };

  useEffect(() => {
    return () => queue.destroy();
  }, []);

  return <form onSubmit={handleSubmit}>...</form>;
}

Vue

import { OfflineQueueEngine } from 'offline-queue-engine';

export default {
  data() {
    return {
      queue: new OfflineQueueEngine()
    };
  },
  methods: {
    async submitForm(data) {
      await this.queue.add({
        url: '/api/data',
        method: 'POST',
        body: data
      });
    }
  },
  beforeUnmount() {
    this.queue.destroy();
  }
};

๐Ÿงช Testing

For testing, use the MemoryStore adapter:

import { OfflineQueueEngine, MemoryStore } from 'offline-queue-engine';

const queue = new OfflineQueueEngine({
  storage: new MemoryStore() // Non-persistent, fast
});

๐Ÿ“Š Storage Adapters Comparison

Adapter Capacity Persistent Async Best For
IndexedDBStore 50MB+ โœ… Yes โœ… Yes Production apps (default)
LocalStorageStore ~5-10MB โœ… Yes โŒ No Simple apps, small queues
MemoryStore RAM only โŒ No โœ… Yes Testing, development

๐Ÿ”’ Retry Strategy

The engine uses smart retry logic:

  • โœ… Retries: Network errors, 5xx server errors
  • โŒ No retry: 4xx client errors (bad request, auth, etc.)
  • ๐Ÿ“ˆ Exponential backoff: 1s โ†’ 2s โ†’ 4s โ†’ 8s โ†’ 16s (max 30s)
  • ๐Ÿ›‘ Max retries: 5 attempts by default (configurable)

๐ŸŒŸ Why This Library?

Most offline queue solutions are:

  • โŒ Framework-specific
  • โŒ Heavyweight
  • โŒ Complex to configure
  • โŒ Poor TypeScript support

offline-queue-engine is:

  • โœ… Universal (browser + Node.js)
  • โœ… Lightweight (~5KB gzipped)
  • โœ… Simple API
  • โœ… Full TypeScript support
  • โœ… Production-tested

๐Ÿ“ License

MIT ยฉ Sahil Laskar

๐Ÿค Contributing

Contributions welcome! Please open an issue or PR.

๐Ÿ“š Live Demo & Examples

๐ŸŽฎ Try the Interactive Demo

The live demo includes 6 comprehensive examples:

  • ๐Ÿš€ Basic Usage - Simple queuing and offline handling
  • ๐ŸŽฏ Priority Queue - High/Normal/Low priority demonstration
  • โ™ป๏ธ Retry Logic - Smart retry with exponential backoff
  • ๐Ÿ’พ Storage Adapters - Memory/LocalStorage/IndexedDB comparison
  • ๐Ÿช Lifecycle Hooks - Event tracking and callbacks
  • โšก Advanced Features - Batch operations, custom headers, manual sync

Demo Source Code: github.com/Sakil9051/demo-offline-queue


Built with โค๏ธ for offline-first applications

About

๐Ÿš€ Production-ready TypeScript library for offline-first request queuing with automatic sync, priority handling, and smart retry logic. Perfect for PWAs and mobile apps.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published