instantdb-node-polyfills
v1.0.0
Published
Browser API polyfills for running InstantDB in Node.js with persistent offline storage
Maintainers
Readme
InstantDB Node.js Polyfills
Comprehensive polyfills for running InstantDB in Node.js environments with persistent storage and network monitoring.
Features
- Persistent Storage: IndexedDB and localStorage backed by LevelDB
- Network Monitoring: Automatic online/offline detection
- Browser API Polyfills: Complete window, document, navigator objects
- WebSocket Support: Automatic WebSocket polyfill for Socket.IO
- Fetch API: Node.js fetch implementation
- Event System: Proper event handling for InstantDB sync
Installation
npm install instantdb-node-polyfillsDependencies
This package requires the following peer dependencies:
npm install @instantdb/core level ws node-fetch fake-indexeddbBasic Usage
const { InstantDBNodePolyfills } = require("instantdb-node-polyfills");
const { init } = require("@instantdb/core");
// Initialize polyfills
const polyfills = new InstantDBNodePolyfills({
verbose: true,
dataPath: "./data",
autoOnlineEvents: true,
});
async function main() {
await polyfills.initialize();
const db = init({ appId: "your-app-id" });
// Use InstantDB normally
db.transact([db.tx.messages["msg1"].update({ text: "Hello!" })]);
// Query data
const { data } = db.useQuery({ messages: {} });
console.log("Messages:", data?.messages);
}
main().catch(console.error);Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| verbose | boolean | false | Enable detailed logging |
| dataPath | string | process.cwd() | Directory for persistent storage |
| autoOnlineEvents | boolean | true | Auto-trigger online events at startup |
| networkMonitoring | boolean | true | Enable network connectivity monitoring |
| networkCheckUrl | string | "api.instantdb.com" | URL to check for connectivity |
| networkCheckInterval | number | 30000 | Network check interval in ms |
Testing the Package
1. Install and run tests
# Install the package locally
npm install
# Run all tests
node test.js
# Test polyfills only (without InstantDB)
node test.js --polyfills-only
# Clean up test data
node test.js --cleanup2. Run individual examples
# Basic InstantDB setup
node examples/basic.js
# Offline/online sync test
node examples/offline-sync.js
# Persistence test (run multiple times)
node examples/persistence.js
# Clean up persistence test data
node examples/persistence.js --cleanup3. Verify persistence
The persistence test is designed to be run multiple times:
# First run - creates data
node examples/persistence.js
# Second run - verifies data persisted
node examples/persistence.js
# Third run - increments restart counter
node examples/persistence.jsAPI Reference
InstantDBNodePolyfills
Constructor
const polyfills = new InstantDBNodePolyfills(options);Methods
initialize(): Initialize all polyfills and storagecleanup(): Clean up resources and event listenersisOnline(): Check current online statustriggerSync(): Manually trigger InstantDB syncgetStorageStats(): Get storage usage statistics
Example with all options
const polyfills = new InstantDBNodePolyfills({
verbose: true,
dataPath: "./my-app-data",
autoOnlineEvents: true,
networkMonitoring: true,
networkCheckUrl: "api.instantdb.com",
networkCheckInterval: 60000, // 1 minute
});
await polyfills.initialize();
// Your InstantDB app code here...
// Clean up when done
process.on('SIGINT', () => {
polyfills.cleanup();
process.exit();
});Troubleshooting
Common Issues
Transactions not syncing: Ensure online events are firing
// Check online status console.log("Online:", polyfills.isOnline()); // Manually trigger sync polyfills.triggerSync();Data not persisting: Verify data path is writable
const stats = polyfills.getStorageStats(); console.log("Storage stats:", stats);Network monitoring issues: Check connectivity URL
// Custom network check const polyfills = new InstantDBNodePolyfills({ networkCheckUrl: "your-api-domain.com", networkCheckInterval: 30000, });
Debug Mode
Enable verbose logging to see what's happening:
const polyfills = new InstantDBNodePolyfills({
verbose: true, // This will log all operations
});Why This Package?
InstantDB is designed for browser environments, but many developers want to use it in Node.js for:
- Server-side data synchronization
- CLI tools that sync with InstantDB
- Background workers and cron jobs
- Testing environments
- Desktop applications built with Electron
This package provides the missing browser APIs and persistent storage needed to run InstantDB effectively in Node.js.
Note: This package only provides polyfills. For authentication in offline-first scenarios, you'll need to handle auth tokens at the application level using InstantDB's built-in auth methods.
Contributing
- Fork the repository
- Create a feature branch
- Add tests for your changes
- Run the test suite:
node test.js - Submit a pull request
License
MIT License - see LICENSE file for details.
