jpskill.com
🛠️ 開発・MCP コミュニティ

electric-sql

ElectricSQLは、Postgresデータベースのデータをリアルタイムにクライアント端末へ同期させ、オフライン環境でも動作するローカルファーストなアプリケーションを構築するSkill。

📜 元の英語説明(参考)

Build local-first applications with ElectricSQL — sync Postgres data to client devices in real-time. Use when someone asks to "sync database to client", "local-first app", "ElectricSQL", "offline-first sync", "real-time Postgres sync", "sync Postgres to SQLite", or "build an app that works offline". Covers shape-based sync, real-time subscriptions, offline support, and conflict resolution.

🇯🇵 日本人クリエイター向け解説

一言でいうと

ElectricSQLは、Postgresデータベースのデータをリアルタイムにクライアント端末へ同期させ、オフライン環境でも動作するローカルファーストなアプリケーションを構築するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o electric-sql.zip https://jpskill.com/download/14859.zip && unzip -o electric-sql.zip && rm electric-sql.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/14859.zip -OutFile "$d\electric-sql.zip"; Expand-Archive "$d\electric-sql.zip" -DestinationPath $d -Force; ri "$d\electric-sql.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して electric-sql.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → electric-sql フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

ElectricSQL

概要

ElectricSQLは、Postgresのデータをクライアントアプリケーションにリアルタイムで同期します。APIからデータを取得する代わりに、データはデバイス上にローカルに存在します。クエリは瞬時に実行され、アプリはオフラインで動作し、接続が回復すると変更は自動的に同期されます。「ブラウザへのPostgresレプリケーション」と考えてください。シェイプ(データのサブセット)を定義すると、Electricがそれらを同期し続けます。

どのような時に使うか

  • オフラインで動作する必要があるアプリ(フィールドサービス、モバイル、旅行)
  • リアルタイムのコラボレーション機能(共有リスト、ダッシュボード)
  • 低レイテンシの読み取り - ローカルデータのクエリは瞬時
  • API呼び出しの削減 - データはすでにクライアント上にある
  • 複数デバイスの同期(電話、タブレット、デスクトップで同じデータを確認)

手順

セットアップ

# Server: Electric sync service
docker run -e DATABASE_URL=postgresql://... -p 3000:3000 electricsql/electric

# Client
npm install @electric-sql/react

シェイプの定義(同期するもの)

// shapes.ts — クライアントに同期するデータを定義
/**
 * シェイプは「ライブクエリ」です — Postgresデータのサブセットであり、
 * クライアント上で同期された状態を維持します。ユーザーが必要とするものだけを同期します。
 */
import { ShapeStream } from "@electric-sql/client";

// 特定のユーザーのすべてのtodoを同期
const stream = new ShapeStream({
  url: "http://localhost:3000/v1/shape",
  params: {
    table: "todos",
    where: `user_id = '${userId}'`,
  },
});

// ストリームは初期データとリアルタイムの更新を提供します
stream.subscribe((messages) => {
  for (const msg of messages) {
    if (msg.headers.operation === "insert") {
      console.log("New todo:", msg.value);
    }
  }
});

Reactとの統合

// components/TodoList.tsx — リアルタイムで同期されたtodoリスト
import { useShape } from "@electric-sql/react";

interface Todo {
  id: string;
  title: string;
  completed: boolean;
  created_at: string;
}

export function TodoList({ userId }: { userId: string }) {
  // データは自動的に同期されます — 読み取りのためのローディング状態はありません
  const { data: todos, isLoading } = useShape<Todo>({
    url: "http://localhost:3000/v1/shape",
    params: {
      table: "todos",
      where: `user_id = '${userId}'`,
      columns: ["id", "title", "completed", "created_at"],
    },
  });

  if (isLoading) return <div>Loading initial sync...</div>;

  // 読み取りは瞬時です — データはローカルにあります
  const active = todos.filter((t) => !t.completed);
  const done = todos.filter((t) => t.completed);

  return (
    <div>
      <h2>Active ({active.length})</h2>
      {active.map((todo) => (
        <div key={todo.id}>
          <input
            type="checkbox"
            onChange={() => toggleTodo(todo.id)}
          />
          {todo.title}
        </div>
      ))}

      <h2>Completed ({done.length})</h2>
      {done.map((todo) => (
        <div key={todo.id} style={{ textDecoration: "line-through" }}>
          {todo.title}
        </div>
      ))}
    </div>
  );
}

// 書き込みはAPIを介して行われます(Electricが結果を同期して戻します)
async function toggleTodo(id: string) {
  await fetch(`/api/todos/${id}/toggle`, { method: "PATCH" });
  // 再フェッチする必要はありません — Electricが更新を自動的に同期します
}

オフラインサポート

// offline.ts — Electricはオフラインを自動的に処理します
/**
 * デバイスがオフラインになると、読み取りは引き続き機能します(データはローカルにあります)。
 * 接続が回復すると、Electricは未完了の変更を同期します。
 *
 * オフライン中の書き込みについては、それらをキューに入れ、再接続時に再生します。
 */
const writeQueue: Array<() => Promise<void>> = [];

async function createTodo(title: string) {
  const action = () => fetch("/api/todos", {
    method: "POST",
    body: JSON.stringify({ title }),
  });

  if (navigator.onLine) {
    await action();
  } else {
    writeQueue.push(action);  // 後で使用するためにキューに入れる
  }
}

// オンラインに戻ったときにキューに入れられた書き込みを再生します
window.addEventListener("online", async () => {
  while (writeQueue.length > 0) {
    const action = writeQueue.shift()!;
    await action();
  }
});

例1:オフライン対応のタスクマネージャーを構築する

ユーザープロンプト: 「インターネットなしで動作し、オンラインに戻ると同期するタスクマネージャーを構築してください。」

エージェントは、ユーザータスクのシェイプ、Reactフックを使用したローカル読み取り、オフラインミューテーションの書き込みキュー、および再接続時の自動同期を使用してElectricをセットアップします。

例2:リアルタイムダッシュボード

ユーザープロンプト: 「ポーリングせずにPostgresデータベースからのライブデータを表示するダッシュボードを構築してください。」

エージェントは、ダッシュボードメトリクスのElectricシェイプを構成し、リアルタイムの更新をサブスクライブし、データベースの変更に応じて瞬時に更新されるチャートをレンダリングします。

ガイドライン

  • シェイプは同期するものを定義します — テーブル全体ではなく、データのサブセットを同期します
  • 読み取りは瞬時です — データはローカルにあり、ネットワークラウンドトリップはありません
  • 書き込みはAPIを介して行われます — Electricが結果をすべてのクライアントに同期して戻します
  • フィルタリングにはwhereを使用します — ユーザーが表示する必要があるデータのみを同期します
  • 射影にはcolumnsを使用します — 必要なフィールドに同期ペイロードを削減します
  • Postgresが信頼できる情報源です — ElectricはWAL(Write-Ahead Log)を読み取ります
  • スキーマの変更は不要です — 既存のPostgresスキーマで動作します
  • シェイプストリームは再開可能です — 中断した場所から同期を再接続します
  • オフライン書き込みの場合は、ローカルにキューに入れます — 接続が回復したら再生します
  • 任意のフレームワークで使用します — Reactフックは便利ですが、コアクライアントはどこでも動作します
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

ElectricSQL

Overview

ElectricSQL syncs Postgres data to client applications in real-time. Instead of fetching data from an API, the data lives locally on the device — queries are instant, the app works offline, and changes sync automatically when connectivity returns. Think "Postgres replication to the browser." Define shapes (subsets of your data) and Electric keeps them in sync.

When to Use

  • Apps that must work offline (field service, mobile, travel)
  • Real-time collaborative features (shared lists, dashboards)
  • Low-latency reads — querying local data is instant
  • Reducing API calls — data is already on the client
  • Multi-device sync (phone, tablet, desktop see same data)

Instructions

Setup

# Server: Electric sync service
docker run -e DATABASE_URL=postgresql://... -p 3000:3000 electricsql/electric

# Client
npm install @electric-sql/react

Define Shapes (What to Sync)

// shapes.ts — Define what data to sync to the client
/**
 * Shapes are "live queries" — subsets of your Postgres data
 * that stay in sync on the client. Only sync what the user needs.
 */
import { ShapeStream } from "@electric-sql/client";

// Sync all todos for a specific user
const stream = new ShapeStream({
  url: "http://localhost:3000/v1/shape",
  params: {
    table: "todos",
    where: `user_id = '${userId}'`,
  },
});

// Stream delivers initial data + real-time updates
stream.subscribe((messages) => {
  for (const msg of messages) {
    if (msg.headers.operation === "insert") {
      console.log("New todo:", msg.value);
    }
  }
});

React Integration

// components/TodoList.tsx — Real-time synced todo list
import { useShape } from "@electric-sql/react";

interface Todo {
  id: string;
  title: string;
  completed: boolean;
  created_at: string;
}

export function TodoList({ userId }: { userId: string }) {
  // Data syncs automatically — no loading states for reads
  const { data: todos, isLoading } = useShape<Todo>({
    url: "http://localhost:3000/v1/shape",
    params: {
      table: "todos",
      where: `user_id = '${userId}'`,
      columns: ["id", "title", "completed", "created_at"],
    },
  });

  if (isLoading) return <div>Loading initial sync...</div>;

  // Reads are instant — data is local
  const active = todos.filter((t) => !t.completed);
  const done = todos.filter((t) => t.completed);

  return (
    <div>
      <h2>Active ({active.length})</h2>
      {active.map((todo) => (
        <div key={todo.id}>
          <input
            type="checkbox"
            onChange={() => toggleTodo(todo.id)}
          />
          {todo.title}
        </div>
      ))}

      <h2>Completed ({done.length})</h2>
      {done.map((todo) => (
        <div key={todo.id} style={{ textDecoration: "line-through" }}>
          {todo.title}
        </div>
      ))}
    </div>
  );
}

// Writes go through your API (Electric syncs the result back)
async function toggleTodo(id: string) {
  await fetch(`/api/todos/${id}/toggle`, { method: "PATCH" });
  // No need to refetch — Electric syncs the update automatically
}

Offline Support

// offline.ts — Electric handles offline automatically
/**
 * When the device goes offline, reads still work (data is local).
 * When connectivity returns, Electric syncs missed changes.
 * 
 * For writes during offline, queue them and replay on reconnect:
 */
const writeQueue: Array<() => Promise<void>> = [];

async function createTodo(title: string) {
  const action = () => fetch("/api/todos", {
    method: "POST",
    body: JSON.stringify({ title }),
  });

  if (navigator.onLine) {
    await action();
  } else {
    writeQueue.push(action);  // Queue for later
  }
}

// Replay queued writes when back online
window.addEventListener("online", async () => {
  while (writeQueue.length > 0) {
    const action = writeQueue.shift()!;
    await action();
  }
});

Examples

Example 1: Build an offline-capable task manager

User prompt: "Build a task manager that works without internet and syncs when back online."

The agent will set up Electric with shapes for user tasks, local reads with React hooks, write queue for offline mutations, and automatic sync on reconnect.

Example 2: Real-time dashboard

User prompt: "Build a dashboard that shows live data from our Postgres database without polling."

The agent will configure Electric shapes for dashboard metrics, subscribe to real-time updates, and render charts that update instantly as the database changes.

Guidelines

  • Shapes define what syncs — sync subsets of data, not entire tables
  • Reads are instant — data is local, no network round-trip
  • Writes go through your API — Electric syncs the result back to all clients
  • where for filtering — only sync data the user should see
  • columns for projection — reduce sync payload to needed fields
  • Postgres is the source of truth — Electric reads the WAL (Write-Ahead Log)
  • No schema changes needed — works with your existing Postgres schema
  • Shape streams are resumable — reconnects sync from where they left off
  • For offline writes, queue locally — replay when connectivity returns
  • Use with any framework — React hook is convenient, but the core client works anywhere