agentleFS
revealui-studiorevealui-studio/revskills/skills/electric-sync/SKILL.md

electric-sync

Skill2 starsChanged 40 days agoMITView on GitHub

ElectricSQL v1.x real-time sync patterns for PostgreSQL. Use when setting up shape subscriptions, authenticated proxy routes, mutation endpoints, offline-first sync, or connecting Electric to Neon. Covers read-only sync, row-level filtering, write-through-API, and conflict resolution.

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 3 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Always validate and sanitize WHERE clause inputs (alphanumeric, UUID regex)

    line 48
  2. Very specific:

    Use force-dynamic to prevent Next.js from caching the proxy response

    line 50
  3. Distinctive:

    All filtering happens server-side in the proxy route.

    line 121
  4. Distinctive:

    Server-wins: Always accept server state on 409

    line 142
  5. Very specific:

    Optimistic: Use If-Match / ETag headers for version checks

    line 143

≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

ElectricSQL Sync Patterns

Architecture

Electric v1.x is read-only sync: Postgres WAL -> Electric -> clients via HTTP. Writes go through your own API. Electric picks up WAL changes and pushes to shape subscribers.

Postgres (Neon/Supabase) --> Electric (sync service) --> Clients (HTTP shapes)
         ^                                                    |
         |                                                    v
         +--- Your API <--- REST mutations <--- Client writes

Shape Proxy Route (Next.js)

Authenticated proxy that adds row-level filtering before forwarding to Electric:

import { prepareElectricUrl, proxyElectricRequest } from '@/lib/api/electric-proxy';

export async function GET(request: NextRequest): Promise<NextResponse> {
  const session = await getSession(request.headers);
  if (!session) return unauthorized();

  const scopeId = new URL(request.url).searchParams.get('scope_id');
  if (!scopeId || !/^[a-zA-Z0-9_-]+$/.test(scopeId)) return validationError();

  const originUrl = prepareElectricUrl(request.url);
  originUrl.searchParams.set('table', 'your_table');
  originUrl.searchParams.set('where', `scope_id = '${scopeId}'`);

  return proxyElectricRequest(originUrl);
}

Key points:

  • Always validate and sanitize WHERE clause inputs (alphanumeric, UUID regex)
  • Set export const dynamic = 'force-dynamic' and export const runtime = 'nodejs'
  • Use force-dynamic to prevent Next.js from caching the proxy response

Mutation Route (Write Path)

Writes go through REST, then Electric picks up the WAL change:

export async function POST(request: NextRequest): Promise<NextResponse> {
  const session = await getSession(request.headers);
  if (!session) return unauthorized();

  const body = await request.json();
  // Validate body fields

  const db = getClient();
  const [created] = await db.insert(table).values({ ... }).returning();

  // Electric automatically syncs this to all shape subscribers
  return NextResponse.json(created, { status: 201 });
}

Client Hook (React)

import { useShape } from '@electric-sql/react';

function useMyData(scopeId: string) {
  const { proxyBaseUrl } = useElectricConfig();

  const { data, isLoading, error } = useShape({
    url: `${proxyBaseUrl}/api/shapes/my-table`,
    params: { scope_id: scopeId },
  });

  return { data, isLoading, error };
}

Database Requirements

  • PostgreSQL 14+ with wal_level = logical
  • Direct connection (not pooled) for replication
  • Neon: logical replication available on all plans
  • Supabase: logical replication enabled by default

Electric Configuration

DATABASE_URL=postgresql://user:pass@host:5432/db?sslmode=require
ELECTRIC_SECRET=your-secret-key

Health check: GET /v1/health returns {"status":"active"}

Offline-First Pattern

import { useShape } from '@electric-sql/react';

// Shape data is cached locally. When reconnecting,
// Electric resumes from the last sync position.
const { data, isLoading } = useShape({
  url: `${proxyBaseUrl}/api/shapes/my-table`,
  params: { scope_id: id },
  fetchClient: fetchWithTimeout, // 10s timeout
});

Row-Level Security

All filtering happens server-side in the proxy route. Never trust client-provided WHERE clauses:

// Good: server derives the filter from the authenticated session.
// The id is allowlisted before it is interpolated. A quote in the id
// must not break out of the Electric where clause.
const userId = session.user.id;
if (!/^[a-zA-Z0-9_-]+$/.test(userId)) {
  throw new Error('invalid session user id');
}
originUrl.searchParams.set('where', `user_id = '${userId}'`);

// Bad: client controls the filter
originUrl.searchParams.set('where', request.searchParams.get('filter'));

Conflict Resolution

Electric is read-only sync. Conflicts happen at the write API level:

  • Last-write-wins: Compare timestamps, keep latest
  • Server-wins: Always accept server state on 409
  • Optimistic: Use If-Match / ETag headers for version checks
  • Queue: Buffer offline mutations, replay on reconnect with coalescing

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.