DEV Community

Alex Spinov
Alex Spinov

Posted on

ElectricSQL Has a Free API: Sync PostgreSQL to the Browser in Real-Time

What if your frontend could read directly from PostgreSQL — and data synced in real-time, even offline?

What Is ElectricSQL?

ElectricSQL syncs data between PostgreSQL and local databases (SQLite, PGlite) in the browser or mobile app. Real-time, offline-capable, conflict-free.

import { ElectricDatabase } from 'electric-sql/browser'
import { electrify } from 'electric-sql'

// Local SQLite in the browser
const conn = await ElectricDatabase.init('my-app.db')
const electric = await electrify(conn, schema)

// Sync a table from Postgres
await electric.db.items.sync()

// Query locally (instant, offline-capable)
const items = await electric.db.items.findMany({
  where: { status: 'active' },
  orderBy: { createdAt: 'desc' }
})

// Write locally — syncs to Postgres automatically
await electric.db.items.create({
  data: { title: 'New item', status: 'active' }
})
Enter fullscreen mode Exit fullscreen mode

How It Works

PostgreSQL ←→ Electric sync service ←→ SQLite (browser/mobile)
     ↑                                        ↑
  Source of truth              Local-first reads/writes
Enter fullscreen mode Exit fullscreen mode
  1. You define which tables/rows to sync
  2. Electric replicates Postgres data to local SQLite
  3. Local writes sync back to Postgres
  4. Conflicts resolved automatically (LWW or custom)

Why ElectricSQL

  • Instant queries — read from local SQLite, not over the network
  • Offline-first — app works without internet, syncs when reconnected
  • Real-time — changes in Postgres appear locally within milliseconds
  • Standard SQL — no new query language, it's just Postgres + SQLite
  • Conflict resolution — automatic last-writer-wins or custom strategies

React Integration

import { useLiveQuery } from 'electric-sql/react'

function ItemList() {
  const { results: items } = useLiveQuery(
    electric.db.items.liveMany({
      where: { status: 'active' },
      orderBy: { createdAt: 'desc' }
    })
  )

  // Automatically re-renders when data changes (local or remote)
  return <ul>{items?.map(item => <li key={item.id}>{item.title}</li>)}</ul>
}
Enter fullscreen mode Exit fullscreen mode

Building local-first apps? Check out my developer tools or email spinov001@gmail.com.

Top comments (0)