Electric SQL syncs data between Postgres and local SQLite databases in real-time. Build offline-first apps that feel instant.
Setup: Electrify Your Database
import { electrify } from "electric-sql/wa-sqlite";
import { schema } from "./generated/client";
const electric = await electrify("local.db", schema, {
url: "https://my-electric-server.com",
auth: { token: authToken },
});
const db = electric.db;
Shapes: Subscribe to Data
// Sync specific data to local device
const shape = await db.products.sync({
where: { category: "electronics" },
include: { reviews: true },
});
// Wait for initial sync
await shape.synced;
// Now query locally — instant!
const products = await db.products.findMany({
where: { price: { lt: 50 } },
orderBy: { createdAt: "desc" },
});
Live Queries: Auto-Updating UI
import { useLiveQuery } from "electric-sql/react";
function ProductList() {
const { results: products } = useLiveQuery(
db.products.liveMany({
where: { category: "electronics" },
orderBy: { price: "asc" },
})
);
// products automatically updates when data changes — locally OR from server!
return products?.map(p => <ProductCard key={p.id} product={p} />);
}
Write Locally, Sync Automatically
// Write to local DB — syncs to Postgres automatically
await db.products.create({
data: {
id: crypto.randomUUID(),
title: "New Widget",
price: 29.99,
url: "https://example.com/widget",
category: "electronics",
},
});
// Works offline! Syncs when connection restored.
await db.products.update({
where: { id: productId },
data: { price: 24.99 },
});
Conflict Resolution
Electric uses CRDTs (Conflict-free Replicated Data Types) for automatic conflict resolution. Multiple users can edit the same data simultaneously — no merge conflicts.
Postgres Side: DDLX
-- Enable Electric on a table
ALTER TABLE products ENABLE ELECTRIC;
-- Set permissions
ELECTRIC ASSIGN 'products:owner' TO products.user_id;
ELECTRIC GRANT ALL ON products TO 'products:owner';
ELECTRIC GRANT SELECT ON products TO ANYONE;
Build offline-first data apps? My Apify tools + Electric = data that works everywhere.
Custom sync solution? Email spinov001@gmail.com
Top comments (0)