DEV Community

Alex Spinov
Alex Spinov

Posted on

Electric SQL Has a Free API — Sync PostgreSQL to Local-First Apps

Electric SQL syncs data between PostgreSQL and local-first apps. Your app works offline with a local database — Electric handles bidirectional sync when connectivity returns.

Why Electric SQL?

  • Local-first — app works offline, syncs when online
  • PostgreSQL — your source of truth stays in Postgres
  • Real-time — changes sync instantly across clients
  • Conflict resolution — CRDT-based, automatic

Quick Start

npm install electric-sql
Enter fullscreen mode Exit fullscreen mode
import { electrify } from 'electric-sql';
import { schema } from './generated/client';

const electric = await electrify(db, schema, {
  url: 'https://your-electric-server.com',
});

// Sync a table
await electric.db.posts.sync();

// Query locally (instant!)
const posts = await electric.db.posts.findMany({
  where: { status: 'published' },
  orderBy: { created_at: 'desc' },
});

// Write locally (syncs to Postgres automatically)
await electric.db.posts.create({
  data: {
    title: 'New Post',
    content: 'Written offline!',
    status: 'draft',
  },
});
Enter fullscreen mode Exit fullscreen mode

React Integration

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

function PostList() {
  const { results: posts } = useLiveQuery(
    electric.db.posts.liveMany({
      where: { status: 'published' },
      orderBy: { created_at: 'desc' },
    })
  );

  // posts updates in real-time when data changes!
  return (
    <ul>
      {posts?.map(post => <li key={post.id}>{post.title}</li>)}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

Shape-Based Sync

// Only sync what you need
await electric.db.posts.sync({
  where: { author_id: currentUserId },
  include: { comments: true },
});

// Sync stops when you unsubscribe
const { unsubscribe } = await electric.db.posts.sync();
unsubscribe();
Enter fullscreen mode Exit fullscreen mode

Offline Support

// Works completely offline
const post = await electric.db.posts.create({
  data: { title: 'Written on a plane', content: '...' },
});

// When back online, Electric syncs automatically
// No code needed — it just works
Enter fullscreen mode Exit fullscreen mode

Building offline-capable data apps? Check out my Apify actors for web data collection, or email spinov001@gmail.com for local-first solutions.

Electric SQL, PowerSync, or CRDTs from scratch — how do you handle offline? Share below!

Top comments (0)