Router WASM
WebAssembly bindings for intelligent neural routing and vector search in the browser.
Bring powerful vector database capabilities to the client-side. Run sub-millisecond vector search entirely in the browser with zero server dependencies. Perfect for edge computing, offline AI, and privacy-first applications.
π Why Router WASM?
Traditional vector databases require backend infrastructure and constant network connectivity. Router WASM changes that.
The Browser-First Advantage
- β‘ Zero Latency: No network roundtripsβsearch happens entirely in the browser
- π Privacy First: User data never leaves the device
- π Offline Capable: Full functionality without internet connection
- π° Cost Effective: Eliminate backend infrastructure and API costs
- π Edge Computing: Deploy intelligent routing to CDN edge nodes
- π¦ Small Bundle: Optimized WASM binary for fast page loads
π Features
Core Capabilities
- Client-Side Vector Search: Sub-millisecond similarity search in the browser
- Neural Routing: Intelligent request routing and pattern matching
- Multiple Distance Metrics: Euclidean, Cosine, Dot Product, Manhattan
- HNSW Indexing: Fast approximate nearest neighbor search
- Memory Efficient: Optimized for browser memory constraints
- TypeScript Support: Full type definitions included
- Framework Agnostic: Works with React, Vue, Svelte, vanilla JS
- Web Worker Ready: Run computations off the main thread
Browser-Specific Optimizations
- SIMD Acceleration: Hardware-accelerated vector operations where available
- Progressive Loading: Load and initialize asynchronously
- Lazy Initialization: Initialize only when needed
- Small Footprint: <100KB gzipped WASM binary
- Memory Pooling: Efficient memory management for long-running sessions
- IndexedDB Integration: Persist vector data locally
π¦ Installation
NPM/Yarn
# Using npm
# Using yarn
# Using pnpm
CDN (Unpkg)
β‘ Quick Start
Basic Usage (ES Modules)
import init from 'router-wasm';
// Initialize WASM module (only once)
await ;
// Create a vector database with 128 dimensions
const db = ;
// Insert vectors
db.;
db.;
db.;
// Search for similar vectors
const query = ;
const results = db.; // Top 5 results
// Process results
// Get collection size
console.log;
// Delete a vector
db.;
TypeScript Support
import init, { VectorDB, DistanceMetric } from 'router-wasm';
interface SearchResult {
id: string;
score: number;
}
async function initializeVectorSearch(): Promise<VectorDB> {
// Initialize WASM
await init();
// Create database with 384 dimensions (e.g., for sentence embeddings)
const db = new VectorDB(384);
return db;
}
async function semanticSearch(
db: VectorDB,
queryEmbedding: Float32Array,
topK: number = 10
): Promise<SearchResult[]> {
const results = db.search(queryEmbedding, topK);
return results;
}
React Integration
import React from 'react';
import init from 'router-wasm';
export default VectorSearchApp;
Vue 3 Integration
<template>
<div>
<h1>Vector Search</h1>
<input v-model="searchQuery" @input="handleSearch" placeholder="Search..." />
<ul>
<li v-for="result in results" :key="result.id">
{{ result.id }}: {{ result.score.toFixed(4) }}
</li>
</ul>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import init, { VectorDB } from 'router-wasm';
const db = ref(null);
const searchQuery = ref('');
const results = ref([]);
onMounted(async () => {
await init();
db.value = new VectorDB(128);
// Populate database
db.value.insert('doc1', new Float32Array(128).fill(0.1));
db.value.insert('doc2', new Float32Array(128).fill(0.5));
});
const handleSearch = () => {
if (!db.value || !searchQuery.value) return;
// Convert query to embedding (simplified example)
const queryVector = new Float32Array(128).fill(parseFloat(searchQuery.value) || 0);
results.value = db.value.search(queryVector, 5);
};
</script>
π― Use Cases
Client-Side AI Applications
Semantic Search in the Browser
// RAG (Retrieval Augmented Generation) in the browser
import init from 'router-wasm';
import from './embeddings'; // Your embedding model
await ;
const knowledgeBase = ;
// Index documents
const docs = ;
// Query with natural language
const queryEmbedding = await ;
const relevantDocs = knowledgeBase.;
Offline Recommender System
// Product recommendations without backend
const productDb = ;
// Index product features
products.;
// Get recommendations based on user preferences
const userPreferences = ;
const recommendations = productDb.;
Privacy-First Search
// Search user data without sending to server
const privateDb = ;
// User data stays in browser
userDocuments.;
// All searches happen locally
const results = privateDb.;
Edge Computing & CDN
Cloudflare Workers
// Deploy to Cloudflare Workers
import init from 'router-wasm';
export default ;
Deno Deploy
// Edge function with vector search
import init, { VectorDB } from 'https://esm.sh/router-wasm';
Deno.serve(async (req) => {
await init();
const db = new VectorDB(256);
// Your edge routing logic
return new Response('OK');
});
Web Workers
// worker.js - Run vector search off main thread
import init from 'router-wasm';
let db = null;
self.;
// main.js - Use the worker
const worker = ;
worker.;
worker.;
π§ Advanced Features
Persistent Storage (IndexedDB)
import init from 'router-wasm';
// Initialize with persistent storage path
await ;
const db = ;
// Data persists across sessions
db.;
// Reload in future session
const db2 = ;
console.log; // Previously inserted data is available
Distance Metrics
import from 'router-wasm';
const db = ;
// Different similarity measures available:
// - DistanceMetric.Euclidean (L2 distance)
// - DistanceMetric.Cosine (cosine similarity)
// - DistanceMetric.DotProduct (dot product)
// - DistanceMetric.Manhattan (L1 distance)
// Note: Distance metric is set at index build time in router-core
Batch Operations
// Efficient bulk insertion
const vectors = ;
vectors.;
// Batch search (multiple queries)
const queries = ;
const allResults = queries.;
Memory Management
// Check collection size
const count = db.;
console.log;
// Clean up when done (especially important in SPAs)
// Note: Drop the reference and let garbage collector handle it
db = null;
// For explicit cleanup in long-running apps
π Performance Optimization
Bundle Size Optimization
Tree Shaking
// Import only what you need
import init from 'router-wasm';
// Don't import unused distance metrics or types
Code Splitting
// Lazy load WASM module
const ;
// Use when needed
button.;
Webpack Configuration
// webpack.config.js
module.exports = ;
Runtime Performance
Pre-compute Embeddings
// Generate embeddings server-side or during build
// Ship pre-computed vectors to reduce client computation
const precomputedVectors = await .;
await ;
const db = ;
Dimension Reduction
// Use lower dimensions for faster search
// 128 or 256 dimensions often sufficient for many use cases
const db = ; // Instead of 384 or 768
// Consider PCA or other dimensionality reduction techniques
Limit Result Sets
// Request only what you need
const results = db.; // Top 10, not 100
// Implement pagination if needed
π¨ Building from Source
Prerequisites
- Rust: 1.77 or higher
- wasm-pack:
cargo install wasm-pack - Node.js: 18.0 or higher (for testing)
Build Commands
# Clone repository
# Build for web (ES modules)
# Build for Node.js
# Build for bundlers (webpack, etc.)
# Build with optimizations
# Run tests
Build Output
After building, the pkg/ directory contains:
pkg/
βββ router_wasm.js # JavaScript bindings
βββ router_wasm.d.ts # TypeScript definitions
βββ router_wasm_bg.wasm # WebAssembly binary
βββ router_wasm_bg.wasm.d.ts
βββ package.json # NPM package metadata
Custom Build Profiles
# Cargo.toml - Already optimized for size
[]
= "z" # Optimize for size
= true # Link-time optimization
= 1 # Better optimization
= "abort" # Smaller binary
π Browser Compatibility
| Browser | Version | WASM | SIMD | Notes |
|---|---|---|---|---|
| Chrome | 87+ | β | β | Full support |
| Firefox | 89+ | β | β | Full support |
| Safari | 15+ | β | β οΈ | WASM SIMD in 16.4+ |
| Edge | 87+ | β | β | Full support |
| Opera | 73+ | β | β | Full support |
| Mobile Safari | 15+ | β | β οΈ | Limited SIMD |
| Mobile Chrome | 87+ | β | β | Full support |
Notes:
- β Full support
- β οΈ Partial support (SIMD acceleration may not be available)
- All modern browsers support WebAssembly
- SIMD provides 2-4x performance boost where available
π Integration with Ruvector Ecosystem
With ruvector-wasm
import initRouter from 'router-wasm';
import initRuvector from 'ruvector-wasm';
// Initialize both modules
await Promise.;
// Router WASM: Intelligent routing and pattern matching
const router = ;
// Ruvector WASM: Full-featured vector database
const vectorDb = ;
// Use together for advanced use cases
With Node.js Backend
// Frontend (router-wasm)
import init from 'router-wasm';
await ;
const clientDb = ;
// Backend (ruvector Node.js bindings)
const = require;
const serverDb = ;
// Hybrid architecture: Local search + server sync
π API Reference
VectorDB
class VectorDB {
/**
* Create a new vector database
* @param dimensions - Vector dimensionality (e.g., 128, 256, 384, 768)
* @param storage_path - Optional persistent storage path
*/
constructor(dimensions: number, storage_path?: string);
/**
* Insert a vector into the database
* @param id - Unique identifier
* @param vector - Float32Array of specified dimensions
* @returns The inserted ID
*/
insert(id: string, vector: Float32Array): string;
/**
* Search for similar vectors
* @param vector - Query vector
* @param k - Number of results to return
* @returns Array of search results with id and score
*/
search(vector: Float32Array, k: number): SearchResult[];
/**
* Delete a vector by ID
* @param id - ID to delete
* @returns true if deleted, false if not found
*/
delete(id: string): boolean;
/**
* Get total number of vectors
* @returns Vector count
*/
count(): number;
}
Types
interface SearchResult {
id: string;
score: number;
}
enum DistanceMetric {
Euclidean,
Cosine,
DotProduct,
Manhattan
}
π Examples
Complete RAG Application
See examples/browser-rag for a full-featured Retrieval Augmented Generation application running entirely in the browser.
Product Search
See examples/product-search for an offline product recommendation system.
Edge Routing
See examples/edge-routing for Cloudflare Workers integration.
π Troubleshooting
WASM Module Not Loading
// Ensure init() is called before creating VectorDB
import init from 'router-wasm';
// β Wrong
const db = ; // Error: WASM not initialized
// β
Correct
await ;
const db = ;
Large Bundle Size
// Use dynamic imports for code splitting
const = await import;
await ;
Memory Errors in Browser
// Reduce dimensions or limit database size
const db = ; // Instead of 768
// Clear vectors periodically in long-running apps
if
TypeScript Errors
// Ensure TypeScript can find declarations
// tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"types": ["router-wasm"]
}
}
π Documentation
- Quick Start Guide - Get started in 5 minutes
- WASM API Reference - Complete API documentation
- Performance Tuning - Optimization strategies
- Main README - Ruvector ecosystem overview
π€ Contributing
Contributions are welcome! See Contributing Guidelines.
Development Setup
# Clone and setup
# Build
# Test
# Format
# Lint
π License
MIT License - see LICENSE for details.
π Acknowledgments
Built with:
- wasm-bindgen: Rust/JavaScript interop
- router-core: High-performance vector routing engine
- HNSW: Fast approximate nearest neighbor search
- SIMD: Hardware-accelerated vector operations
π Links
- GitHub: github.com/ruvnet/ruvector
- NPM: npmjs.com/package/router-wasm
- Documentation: ruvector docs
- Discord: Join community
- Website: ruv.io
Built by rUv β’ Part of Ruvector β’ MIT Licensed
Browser-First Vector Search | Zero Backend Required | Privacy First
Get Started β’ Documentation β’ Examples