由 Amir T. 出售

Electric is a read-path sync engine that streams subsets of Postgres data to web, mobile, and edge environments via a low-level HTTP API with CDN-scalable fan-out and partial replication via Shapes.
This block provides a curated set of ElectricSQL integration examples demonstrating real-time Postgres sync across multiple frameworks and patterns. It targets backend and full-stack developers who want working reference implementations for wiring ElectricSQL's HTTP shape API into React, Next.js, Remix, TanStack, Phoenix LiveView, and other stacks.
.shared/ - Shared database migrations, infra helpers, and Playwright/SST config reused across examplesbash/ - Minimal shell client demonstrating raw HTTP shape API consumptionburn/ - Full-stack Elixir/Phoenix + React chat app using TanStack DB collections and live queriesencryption/ - Example showing client-side field encryption over synced shapesgatekeeper-auth/ - JWT-based auth gatekeeper pattern with a proxy that issues scoped shape tokenslinearlite/ - Linear-clone issue tracker using PGlite + live queries, board and list viewslinearlite-read-only/ - Read-only variant of the LinearLite examplenextjs/ - Next.js app demonstrating useShape integration with server-side shape preloadingphoenix-liveview/ - Phoenix LiveView integration consuming Electric shape streams server-sideproxy-auth/ - Reverse-proxy auth pattern enforcing row-level access before forwarding to Electricreact/ - Minimal React example using useShape hookredis/ - Shape consumer that materializes synced data into Redisremix/ - Remix app with Electric shape loader integrationtanstack/ - TanStack Query + Electric shape subscription exampletanstack-db-expo-starter/ - TanStack DB starter for Expo (React Native) with Electric synctanstack-db-web-starter/ - TanStack DB starter for web with Electric synctodo-app/ - Classic todo app wiring Electric shapes to a local SQLite storewrite-patterns/ - Demonstrates optimistic, shared-pending, and through-the-server write patternsyjs/ - CRDT-based collaborative editing using Yjs synced via Electric shapesnpm install @electric-sql/client
npm install @electric-sql/react
npm install @electric-sql/pglite @electric-sql/pglite-react
npm install @tanstack/react-db
npm install @tanstack/react-router
npm install jsonwebtoken
npm install dotenv-cli
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript, Elixir cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 5dc45e9caa57391a…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
For the burn/ Elixir example, Elixir/Mix and the Phoenix framework are required:
mix deps.get
mix ecto.migrate
For the tanstack-db-expo-starter/ example, React Native / Expo native build steps are required:
npx expo prebuild
npx pod-install # iOS only
Copy the source/ directory into your project root, e.g. ./electric-examples/.
Set the following environment variables (create a .env file or export them):
ELECTRIC_URL=http://localhost:3000 # URL of your running Electric instance
DATABASE_URL=postgresql://user:pass@localhost/mydb
API_URL=http://localhost:4000 # Your backend API URL (gatekeeper/proxy examples)
AUTH_SECRET=your-jwt-secret # Required for gatekeeper-auth and proxy-auth
Wire TypeScript paths in tsconfig.json if importing shared utilities:
{
"compilerOptions": {
"paths": {
"@shared/*": ["./electric-examples/.shared/lib/*"]
}
}
}
Install dependencies per example. Each subdirectory has its own package.json. Run:
cd electric-examples/react && npm install
Run migrations before starting any example that connects to Postgres:
cd electric-examples/.shared
npx dotenv-cli -e ../../.env -- psql $DATABASE_URL -f db/migrations/01-create_items_table.sql
Start Electric (Docker):
docker run -e DATABASE_URL=$DATABASE_URL -p 3000:3000 electricsql/electric
import { ShapeStream, FetchError } from '@electric-sql/client'
const stream = new ShapeStream({
url: string, // Electric /v1/shape endpoint URL
headers?: Headers, // Optional auth headers (e.g. from gatekeeper)
onError?: (error: Error) => Promise<Partial<ShapeStreamOptions> | void>
})
ShapeStream opens a long-poll HTTP connection to Electric and emits change messages. Use it directly when you need low-level control, custom error handling (such as refreshing JWT tokens on 401), or when consuming shapes outside React. The onError callback can return new options (e.g. updated headers) to resume the stream without interruption.
import { Shape } from '@electric-sql/client'
const shape = new Shape(stream: ShapeStream)
shape.subscribe(({ rows }: { rows: Record<string, unknown>[] }) => void)
Shape materializes a ShapeStream into an in-memory row set and fires a subscriber callback on every change. Use it when you need a simple, framework-agnostic snapshot of synced rows and want to react to incremental updates without managing offset state yourself.
import { useLiveQuery, eq } from '@tanstack/react-db'
const { data } = useLiveQuery(
(query) =>
query
.from({ entity: collection })
.where(({ entity }) => eq(entity.field, value))
.orderBy(({ entity }) => entity.inserted_at, { direction: 'desc' })
.select(({ entity }) => ({ id: entity.id })),
[dependency]
)
useLiveQuery is a React hook from @tanstack/react-db that subscribes to a TanStack DB collection (backed by an Electric shape) and returns a reactive data array. Use it inside components that need to display or react to live-synced data. Queries re-run automatically when the underlying collection changes or when the dependency array changes.
A backend script that connects to the Electric HTTP API, materializes the items table into memory, and logs the count whenever rows change.
import { FetchError, Shape, ShapeStream } from '@electric-sql/client'
const ELECTRIC_URL = process.env.ELECTRIC_URL ?? 'http://localhost:3000'
const stream = new ShapeStream({
url: `${ELECTRIC_URL}/v1/shape`,
params: { table: 'items', offset: '-1' },
onError: async (error) => {
if (error instanceof FetchError && (error.status === 401 || error.status === 403)) {
console.error('Auth error - aborting')
return // stop stream
}
return {} // retry with same config
},
})
const shape = new Shape(stream)
shape.subscribe(({ rows }) => {
console.log(`items count: ${rows?.length ?? 0}`)
})
Mirrors the gatekeeper-auth/client/index.ts pattern. The client first fetches a signed config from your API, then opens a shape stream using the returned URL and headers.
import { FetchError, Shape, ShapeStream } from '@electric-sql/client'
const API_URL = process.env.API_URL ?? 'http://localhost:4000'
async function fetchConfig(): Promise<{ url: string; headers: Record<string, string> }> {
const resp = await fetch(`${API_URL}/gatekeeper/items`, { method: 'POST' })
return resp.json()
}
const config = await fetchConfig()
const stream = new ShapeStream({
...config,
onError: async (error) => {
if (error instanceof FetchError && (error.status === 401 || error.status === 403)) {
return await fetchConfig() // refresh token and resume
}
if (error instanceof FetchError && error.status >= 400 && error.status < 500) {
return // fatal client error, stop
}
return {}
},
})
const shape = new Shape(stream)
shape.subscribe(({ rows }) => console.log('rows:', rows?.length))
Demonstrates the useLiveQuery + collection preload pattern used in burn/assets/src/routes/index.tsx.
import React, { useEffect } from 'react'
import { useLiveQuery, eq } from '@tanstack/react-db'
import { useNavigate } from '@tanstack/react-router'
import { threadCollection, membershipCollection } from './db/collections'
const CURRENT_USER_ID = 'user-123'
export function ThreadRedirect() {
const navigate = useNavigate()
const { data: threads } = useLiveQuery(
(query) =>
query
.from({ thread: threadCollection })
.innerJoin(
{ membership: membershipCollection },
({ thread, membership }) => eq(thread.id, membership.thread_id)
)
.where(({ membership }) => eq(membership.user_id, CURRENT_USER_ID))
.orderBy(({ thread }) => thread.inserted_at, { direction: 'desc', nulls: 'first' })
.limit(1)
.select(({ thread }) => ({ id: thread.id })),
[CURRENT_USER_ID]
)
const latestId = threads[0]?.id
useEffect(() => {
if (latestId) navigate({ to: `/threads/$threadId`, params: { threadId: latestId } })
}, [latestId, navigate])
return null
}
// Preload collections in your route loader:
export async function loader() {
await Promise.all([threadCollection.preload(), membershipCollection.preload()])
}
.shared/ - Cross-example shared code: Postgres migration SQL, Neon/Infra helpers, SST config, and a shared Playwright test config.bash/ - Single client.bash script that curls the Electric shape endpoint; useful for smoke-testing a running Electric instance.burn/ - Full Elixir+React application with TanStack Router/DB, multi-user chat backed by Electric shapes, and a Phoenix backend.encryption/ - Shows how to encrypt field values client-side before writing and decrypt after syncing, keeping Electric shape data opaque.gatekeeper-auth/ - Two-part example: an edge function (edge/index.ts) that validates JWTs and forwards to Electric, and a client (client/index.ts) that fetches scoped tokens.linearlite/ - Issue tracker with board and list views powered by PGlite in-browser SQLite and Electric live queries.linearlite-read-only/ - Same as linearlite but with all write paths removed, suitable as a read-only demo.nextjs/ - Next.js pages/app router example integrating useShape for real-time data with SSR-friendly preloading.phoenix-liveview/ - Elixir Phoenix LiveView consuming Electric shape streams server-side and pushing diffs to the browser.proxy-auth/ - Node proxy that checks authorization before forwarding shape requests to Electric, enforcing per-user row filters.react/ - Minimal React + Vite app using the useShape hook, the canonical starting point for React integration.redis/ - Node script that subscribes to a shape and upserts rows into Redis, demonstrating a non-browser consumer.remix/ - Remix app with a loader that fetches initial shape data server-side and hydrates client-side sync on mount.tanstack/ - TanStack Query integration where shape subscriptions feed query cache invalidation.tanstack-db-expo-starter/ - Expo React Native starter wiring TanStack DB collections to Electric for offline-capable mobile apps.tanstack-db-web-starter/ - Web version of the TanStack DB starter, minimal boilerplate to fork.todo-app/ - Classic todo CRUD app showing optimistic local writes reconciled against Electric-synced state.write-patterns/ - Side-by-side comparison of optimistic, shared-pending, and server-confirmed write strategies.yjs/ - Collaborative text editing using Yjs CRDT with Electric as the persistence and distribution layer.ELECTRIC_URL not set or wrong port: Electric defaults to 3000; if you change it in Docker, update ELECTRIC_URL in every example's .env or the stream will silently fail to connect.wal_level = logical; set it in postgresql.conf and restart Postgres, or use the provided Docker Compose which sets it automatically.AUTH_SECRET mismatch between gatekeeper edge function and your API: The JWT must be signed with the same secret on both sides; hardcoded defaults differ per example, so always set AUTH_SECRET explicitly in production.useLiveQuery before collection.preload() resolves returns an empty array with no error; always await preload() in your route loader as shown in the burn example.jsonwebtoken in Deno edge functions: The gatekeeper-auth/edge example targets Deno; importing jsonwebtoken via npm specifier (npm:jsonwebtoken) is required; bare imports will fail.tanstack-db-expo-starter: TanStack DB's Expo package may include native SQLite bindings; run npx expo prebuild and npx pod-install (iOS) before expo run:ios, otherwise the JS bundle loads but the native module throws at runtime.I have a set of ElectricSQL integration examples located in `./electric-examples/` (from the AVCP block `sqlite-go-server`, source root `examples`). The USAGE.md is at `./electric-examples/USAGE.md`.
Please help me integrate ElectricSQL real-time sync into my existing project step by step:
1. Read USAGE.md and the relevant example subdirectory for my stack (e.g. `react/`, `nextjs/`, `tanstack-db-web-starter/`).
2. Install the required npm packages listed in USAGE.md "Required dependencies".
3. Configure environment variables: ELECTRIC_URL, DATABASE_URL, API_URL, AUTH_SECRET.
4. Wire the ShapeStream and Shape (or useShape / useLiveQuery) into my existing components, following the real signatures from USAGE.md "Public API".
5. If I need JWT gatekeeper auth, adapt `electric-examples/gatekeeper-auth/client/index.ts` to my API endpoint.
6. If I am using TanStack DB, adapt `electric-examples/burn/assets/src/routes/index.tsx` showing collection preload in a route loader and useLiveQuery in the component.
7. Show me only real imports from `@electric-sql/client`, `@electric-sql/react`, `@tanstack/react-db` - do not invent APIs.
8. Point out any pitfalls from USAGE.md "Common pitfalls" relevant to my stack.
My stack is: [FILL IN - e.g. Next.js 14 App Router + TypeScript + PostgreSQL on Railway]
My Electric instance URL is: [FILL IN]
The upstream project is licensed under Apache 2.0 (see the LICENSE badge in the README and source/LICENSE if present). Source: ElectricSQL on GitHub, examples directory. Upstream package identifier: user@example.com (monorepo examples, not published to npm independently).
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费