Tauri Plugin Cache
An advanced, versatile, and performance-focused disk caching solution for Tauri applications. This plugin features powerful compression support, memory caching layer, configurable time-to-live (TTL) management, automatic cleanup, and cross-platform compatibility. It enables persistent storage of data on disk for fast access and optimizes application performance through intelligent caching strategies. Working seamlessly on both desktop and mobile platforms, it significantly enhances the data management capabilities of your Tauri applications.
Features
- Type Safety: Full TypeScript typings
- Cache Statistics: Monitor cache usage
- Cross-Platform: Works on desktop and mobile
- Optional TTL: Set expiration times for cache items
- Disk-based Cache: Persistent data storage and retrieval
- Data Compression: Enable compression for large data items
- Customizable Storage: Configure where cache files are stored
- Automatic Cleanup: Background task to remove expired items
- Smart Compression: Configurable compression levels and thresholds
- Configurable Cache Location: Customize where cache files are stored
- Memory Caching: In-memory caching layer for improved performance
- Performance Optimized: Buffered I/O and chunked processing for large datasets
Installation
Using Tauri CLI (Recommended)
The easiest way to install this plugin is using the Tauri CLI, which automatically adds both Rust and JavaScript dependencies to your project:
# Using npm
# Using pnpm
# Using yarn
This will:
- Add the
tauri-plugin-cachecrate to yourCargo.toml - Install the
tauri-plugin-cache-apinpm package - Set up the necessary configurations
Manual Installation
If you prefer to manually install the plugin, you can follow these steps:
Rust Dependencies
Add this plugin to your project using one of these methods:
# Using cargo add
Or manually add to your Cargo.toml file:
[]
= { = "2.5.1" }
= "0.1.3"
JavaScript/TypeScript API
Add the plugin API package to your project:
# or
# or
Setup
Register the plugin in your tauri.conf.json and/or in your Rust code:
// Basic setup with default configuration
// Or with custom configuration
Note: When specifying
cache_dir, it's recommended to use relative paths instead of absolute paths. The plugin will create this directory inside the app's default cache directory location. If an absolute path is provided, only the last component of the path will be used as a subdirectory name within the app's cache directory.
Permissions
By default all plugin commands are blocked and cannot be accessed. You must modify the permissions in your capabilities configuration to enable these.
See the Capabilities Overview for more information.
Example Capability Configuration
Then enable this capability in your tauri.conf.json:
Default Permission
The cache:default permission set configures which cache features are exposed by default.
Granted Permissions
This enables all cache operations including setting, getting, and removing cached data.
This default permission set includes the following:
cache:allow-setcache:allow-getcache:allow-hascache:allow-removecache:allow-clearcache:allow-stats
Permission Table
| Identifier | Description |
|---|---|
| cache:allow-set | Allows setting data in the cache |
| cache:deny-set | Denies setting data in the cache |
| cache:allow-get | Allows retrieving data from the cache |
| cache:deny-get | Denies retrieving data from the cache |
| cache:allow-has | Allows checking if data exists in the cache |
| cache:deny-has | Denies checking if data exists in the cache |
| cache:allow-remove | Allows removing data from the cache |
| cache:deny-remove | Denies removing data from the cache |
| cache:allow-clear | Allows clearing all data from the cache |
| cache:deny-clear | Denies clearing all data from the cache |
| cache:allow-stats | Allows retrieving statistics about the cache |
| cache:deny-stats | Denies retrieving statistics about the cache |
Usage
JavaScript/TypeScript Example
import { set, get, has, remove, clear, stats } from 'tauri-plugin-cache-api';
// Store a value with TTL
await set('user', { name: 'John', age: 30 }, { ttl: 60 }); // Expires in 60 seconds
// Store a large value with compression
await set('largeData', largeObject, { compress: true });
// Store a value with both TTL and compression
await set('temporaryData', data, { ttl: 300, compress: true });
// Retrieve a value (returns null if not found or expired)
const user = await get<{ name: string, age: number }>('user');
if (user) {
console.log(user.name); // "John"
}
// Check if a key exists and is not expired
const exists = await has('user');
if (exists) {
console.log('User exists in cache');
}
// Remove a value
await remove('user');
// Get cache statistics
const stats = await stats();
console.log(`Cache has ${stats.totalSize} items (${stats.activeSize} active)`);
// Clear all values
await clear();
Rust Example
use Manager;
use CacheExt;
// In a command or elsewhere with access to the app handle
async
API
JavaScript/TypeScript API
set(key: string, value: any, options?: SetItemOptions): Promise<void>
Sets an item in the cache with optional TTL and compression.
key: The key to store the value undervalue: The value to store (will be JSON serialized)options: Optional settingsttl: Time-to-live in seconds (item will be deleted after this time)compress: Whether to compress the data before storing
get<T = any>(key: string): Promise<T | null>
Gets an item from the cache.
key: The key to retrieve- Returns: The stored value (type T) or null if not found or expired
has(key: string): Promise<boolean>
Checks if an item exists in the cache and is not expired.
key: The key to check- Returns: True if the item exists and is not expired
remove(key: string): Promise<void>
Removes an item from the cache.
key: The key to remove
clear(): Promise<void>
Clears all items from the cache.
stats(): Promise<CacheStats>
Gets cache statistics.
- Returns: An object with statistics about the cache
totalSize: Total number of items in the cacheactiveSize: Number of active (non-expired) items
Compression
This plugin supports data compression to reduce the disk space used by cache items. You can enable compression for individual items or set it as the default for all cache items.
Benefits of Compression
- Reduced Disk Usage: Compresses data to save disk space
- Improved I/O Performance: Smaller data sizes mean faster read/write operations
- Network Efficiency: If you sync cache data over a network, compressed data reduces bandwidth usage
Configuration Options
You can configure the default compression behavior when initializing the plugin:
let cache_config = CacheConfig ;
Per-Item Compression
You can override the default compression setting for individual items:
// Force compression for this item regardless of default setting
await set('largeData', largeObject, { compress: true });
// Force no compression for this item
await set('smallData', smallObject, { compress: false });
Platform Compatibility
This plugin supports both desktop and mobile platforms:
- Desktop: Windows, macOS, Linux
- Mobile: Android, iOS
License
This project is released under the MIT License.