### Install dependencies and run development server Source: https://electric.ax/docs/sync/guides/installation.md Install the sync-service dependencies using Mix and start the development server. ```sh cd packages/sync-service mix deps.get ``` ```sh mix run --no-halt ``` -------------------------------- ### Start Electric Agents quickstart with npx electric-ax agents quickstart Source: https://electric.ax/docs/agents/quickstart.md Starts the Electric Agents runtime, the web UI, and a built-in Horton assistant. Requires Node.js 18+, Docker, and an Anthropic API key. The runtime server, Postgres, and Electric run as containers, and the runtime serves both the API and the web UI on http://localhost:4437. ```sh npx electric-ax agents quickstart ``` -------------------------------- ### Quickstart with built-in runtime Source: https://electric.ax/docs/agents/reference/cli.md Starts the coordinator server, prints onboarding commands, and runs the built-in agents runtime. Requires an Anthropic API key. ```bash electric agents quickstart --anthropic-api-key sk-ant-... ``` -------------------------------- ### quickstart [--anthropic-api-key ] Source: https://electric.ax/docs/agents/reference/cli.md Starts the coordinator server, prints onboarding commands, and runs the built-in agents runtime. An Anthropic API key can be provided. ```APIDOC ## quickstart [--anthropic-api-key ] ### Description Start the coordinator server, print onboarding commands, and run the built-in agents runtime. ### Command `electric agents quickstart [--anthropic-api-key ]` ### Parameters - **--anthropic-api-key ** (string) - Optional - Anthropic API key for the built-in Horton server. ### Example ```bash electric agents quickstart --anthropic-api-key sk-ant-... ``` ``` -------------------------------- ### Configure and run the playground Source: https://electric.ax/docs/agents/examples/playground.md Navigate to the playground directory, set up the environment variables, install dependencies, and start the development server. ```bash cd examples/agents-playground cp .env.example .env pnpm install pnpm dev ``` -------------------------------- ### Caddy startup success output Source: https://electric.ax/docs/agents/walkthrough Example output from running 'caddy start', confirming Caddy is running in the background. ```text Successfully started Caddy (pid=13701) - Caddy is running in the background ``` -------------------------------- ### Install Runtime SDK Source: https://electric.ax/docs/agents/quickstart.md Initialize a new project and install the required runtime SDK and development tools. ```sh mkdir my-agents-app && cd my-agents-app npm init -y npm install @electric-ax/agents-runtime npm install --save-dev tsx ``` -------------------------------- ### Set up shell completions Source: https://electric.ax/docs/agents/reference/cli.md Shows setup instructions or auto-installs completions. Manual setup for Bash, Zsh, and Fish is also shown. ```bash electric agents completion # Show setup instructions electric agents completion install # Auto-install into your shell init file ``` ```bash # Bash (~/.bashrc) or Zsh (~/.zshrc) eval "$(electric --completion)" # Fish (~/.config/fish/config.fish) electric --completion-fish | source ``` -------------------------------- ### Start development server Source: https://electric.ax/docs/sync/quickstart.md Start the development server for the application. ```shell pnpm dev ``` -------------------------------- ### Start Caddy with caddy start Source: https://electric.ax/docs/agents/walkthrough Start Caddy in the background after creating the Caddyfile. Expected output includes a line confirming successful startup with the process ID. ```sh caddy start ``` -------------------------------- ### Run runtime components independently Source: https://electric.ax/docs/agents/quickstart.md Commands to start the runtime server and built-in agents separately from the quickstart process. ```sh npx electric-ax agents start # runtime server + UI (background, Docker) npx electric-ax agents start-builtin # built-in Horton and worker (foreground) ``` -------------------------------- ### start Source: https://electric.ax/docs/agents/reference/cli.md Starts the local Electric Agents coordinator server, Postgres, Electric, and UI using Docker Compose. ```APIDOC ## start ### Description Start the local Electric Agents coordinator server, Postgres, Electric, and UI using Docker Compose. ### Command `electric agents start` ### Example ```bash electric agents start ``` ``` -------------------------------- ### Install dependencies Source: https://electric.ax/docs/sync/quickstart.md Install the required project dependencies. ```shell pnpm install ``` -------------------------------- ### Start Caddy as a reverse-proxy Source: https://electric.ax/docs/sync/guides/troubleshooting.md Run this command to start Caddy on port 3001, proxying requests to your Electric instance on port 3000. Ensure Caddy is installed and trusted on your local machine before execution. ```sh caddy run \ --config - \ --adapter caddyfile \ < { return c.text('Hello Hono!') }) serve({ fetch: app.fetch, port: 3000 }, (info) => { console.log(`Server is running on http://localhost:${info.port}`) }) ``` ```ts import { createEntityRegistry, createRuntimeHandler } from '@electric-ax/agents-runtime' ``` ```ts const PORT = 3000 const SERVE_URL = `http://localhost:${PORT}` const ELECTRIC_AGENTS_URL = 'http://localhost:4437' const MODEL = 'claude-sonnet-4-6' ``` ```ts const registry = createEntityRegistry() ``` ```ts registry.define("assistant", { description: "A general-purpose AI assistant", async handler(ctx) { ctx.useAgent({ systemPrompt: "You are a helpful assistant.", model: MODEL, tools: [], }) await ctx.agent.run() } }) ``` ```ts const runtime = createRuntimeHandler({ baseUrl: ELECTRIC_AGENTS_URL, serveEndpoint: `${SERVE_URL}/electric-agents`, registry, }) ``` ```ts app.post('/electric-agents', (c) => { return runtime.handleWebhookRequest(c.req.raw) }) ``` ```js serve({ fetch: app.fetch, port: 3000 }, (info) => { console.log(`Server is running on http://localhost:${info.port}`) runtime.registerTypes().catch(console.error) }) ``` -------------------------------- ### Configure environment variables Source: https://electric.ax/docs/sync/quickstart.md Copy the example environment file to create your local configuration. ```shell cp .env.example .env ``` -------------------------------- ### Install @electric-sql/react Source: https://electric.ax/docs/sync/integrations/react.md Install the Electric React hooks package using npm. ```shell npm i @electric-sql/react ``` -------------------------------- ### Start local coordinator stack Source: https://electric.ax/docs/agents/reference/cli.md Starts the local Electric Agents coordinator server, Postgres, Electric, and UI using Docker Compose. ```bash electric agents start ``` -------------------------------- ### Start Docker backend services Source: https://electric.ax/docs/sync/quickstart.md Start Postgres and Electric as background services using Docker Compose. ```shell pnpm backend:up ``` -------------------------------- ### Install ElectricSQL TypeScript client Source: https://electric.ax/docs/sync/guides/shapes.md Install the required package to use the TypeScript client. ```bash npm i @electric-sql/client ``` -------------------------------- ### Start Supabase and serve functions locally Source: https://electric.ax/docs/sync/integrations/supabase.md Start the local Supabase stack and serve the edge functions for development. ```shell supabase start supabase functions serve ``` -------------------------------- ### Run Hono Development Server Source: https://electric.ax/docs/agents/walkthrough Navigate to the project directory and start the development server. ```sh cd walkthrough pnpm dev ``` -------------------------------- ### Install and initialize PGlite Source: https://electric.ax/docs/sync/stacks.md Install the PGlite package and create a new in-process Postgres database instance. The npm command is the prerequisite for the TypeScript import and instantiation. ```shell npm install @electric-sql/pglite ``` ```ts import { PGlite } from '@electric-sql/pglite' const db = new PGlite() ``` -------------------------------- ### Install Requests library Source: https://electric.ax/docs/sync/guides/client-development.md Command to install the Requests HTTP client for Python. ```shell # Optionally in a virtualenv: # virtualenv .venv # source .venv/bin/activate python -m pip install requests ``` -------------------------------- ### Install Electric Agents CLI with npm Source: https://electric.ax/docs/agents/reference/cli.md Install the Electric Agents CLI globally using npm. After installation, use the `electric agents` command or run one-off commands with `npx electric-ax agents ...`. ```bash npm install -g electric-ax ``` -------------------------------- ### Install @electric-sql/react with --force Source: https://electric.ax/docs/sync/integrations/expo.md Install the React client package. The --force flag is necessary to work around a React dependency version mismatch. ```shell npm install '@electric-sql/react' --force ``` -------------------------------- ### Clone and prepare Electric source Source: https://electric.ax/docs/sync/guides/installation.md Clone the repository and install the necessary system dependencies using asdf. ```sh git clone https://github.com/electric-sql/electric.git cd electric ``` ```sh asdf plugin-add elixir asdf plugin-add erlang asdf plugin-add nodejs asdf plugin-add pnpm asdf install ``` -------------------------------- ### Start sync from now Source: https://electric.ax/docs/sync/api/http.md Use offset=now to skip historical data and receive an immediate up-to-date response. ```sh curl -i 'http://localhost:3000/v1/shape?table=foo&offset=now' ``` -------------------------------- ### Request a Shape URL Source: https://electric.ax/docs/sync/guides/client-development.md Example of a GET request to retrieve all rows from the 'items' table. ```http GET /v1/shape?table=items ``` -------------------------------- ### Implementation with Cookie-based Auth Source: https://electric.ax/docs/sync/guides/auth.md Example of adding a Vary header for cookie-based auth in a GET handler. ```tsx export async function GET(request: Request) { // ... auth logic ... const response = await fetch(originUrl) const headers = new Headers(response.headers) // Add Vary header for cookie-based auth headers.set('Vary', 'Cookie') return new Response(response.body, { status: response.status, statusText: response.statusText, headers, }) } ``` -------------------------------- ### Implementation with Authorization Headers Source: https://electric.ax/docs/sync/guides/auth.md Example of adding a Vary header for Authorization-based auth in a GET handler. ```tsx export async function GET(request: Request) { // ... auth logic ... const response = await fetch(originUrl) const headers = new Headers(response.headers) // Add Vary header for Authorization-based auth headers.set('Vary', 'Authorization') return new Response(response.body, { status: response.status, statusText: response.statusText, headers, }) } ``` -------------------------------- ### Initialize Docker-based starter app Source: https://electric.ax/docs/sync/quickstart.md Clone the starter template and navigate into the project directory. ```shell npx gitpick electric-sql/electric/tree/main/examples/tanstack-db-web-starter my-electric-app cd my-electric-app ``` -------------------------------- ### Initialize Cloud-based starter app Source: https://electric.ax/docs/sync/quickstart.md Run the starter script to initialize a new Electric app using the default Cloud configuration. ```shell npx @electric-sql/start my-electric-app ``` -------------------------------- ### Request Subsequent Shape Data Source: https://electric.ax/docs/sync/guides/client-development.md Example of a follow-up GET request using a specific handle and offset to continue accumulating messages. ```http GET /v1/shape?table=items&handle=38083685-1729874417404&offset=0_0 ``` -------------------------------- ### Docker Compose Shared Storage Setup Source: https://electric.ax/docs/sync/guides/upgrading.md Example configuration for running Electric with a shared volume, including the mandatory ELECTRIC_SHAPE_DB_EXCLUSIVE_MODE setting for network filesystems. ```yaml services: electric: image: electricsql/electric:0.9 # pin to a specific version environment: DATABASE_URL: ${DATABASE_URL} ELECTRIC_STORAGE_DIR: /var/lib/electric/data ELECTRIC_SHAPE_DB_EXCLUSIVE_MODE: "true" ELECTRIC_SECRET: ${ELECTRIC_SECRET} volumes: - electric_data:/var/lib/electric/data healthcheck: test: ["CMD", "curl", "-sf", "http://localhost:3000/v1/health"] interval: 10s timeout: 2s retries: 3 # ...ports, networks, etc. volumes: electric_data: ``` -------------------------------- ### Initial sync request with curl Source: https://electric.ax/docs/sync/api/http.md Makes an initial sync request to get the current data for a shape. Uses offset=-1 to request the whole log from the start. ```sh curl -i 'http://localhost:3000/v1/shape?table=foo&offset=-1' ``` -------------------------------- ### Initialize Python client project Source: https://electric.ax/docs/sync/guides/client-development.md Commands to create a new folder and initialize it as a Python package. ```shell mkdir example-client cd example-client touch __init__.py ``` -------------------------------- ### Get and list context entries Source: https://electric.ax/docs/agents/usage/context-composition.md Shows how to retrieve a single context entry by id and list all entries. The getContext example shows the returned object shape with id, name, content, and insertedAt. ```TypeScript const entry = ctx.getContext("user-prefs") // { id: "user-prefs", name: "User preferences", content: "...", insertedAt: 1234 } const all = ctx.listContext() // Array ``` -------------------------------- ### Start local agents infrastructure Source: https://electric.ax/docs/agents/examples/playground.md Run this command from the monorepo root to initialize the local agents infrastructure. ```bash npx electric-ax agents start ``` -------------------------------- ### Initialize Supabase project and create edge function Source: https://electric.ax/docs/sync/integrations/supabase.md Install the Supabase CLI and run these commands to initialize a new project and create an edge function named 'hello-electric'. ```shell supabase init supabase functions new hello-electric ``` -------------------------------- ### Launch Electric with Docker Compose Source: https://electric.ax/docs/sync/integrations/digital-ocean.md Run the deployment command and verify the output shows the service starting successfully. ```console $ docker compose up [+] Running 8/8 ✔ electric 7 layers [⣿⣿⣿⣿⣿⣿⣿] 0B/0B Pulled 8.2s ✔ efc2b5ad9eec Pull complete 3.4s ✔ 2cb0d575dcef Pull complete 4.5s ✔ c1b251d76665 Pull complete 4.6s ✔ c82981779fd9 Pull complete 4.7s ✔ 65b429e477c5 Pull complete 4.8s ✔ 1fd7ee9efb04 Pull complete 6.0s ✔ 87053f06541e Pull complete 6.1s [+] Running 2/2 ✔ Network electric-sync-droplet_default Created 0.2s ✔ Container electric-sync-droplet-electric-1 Created 0.2s Attaching to electric-sync-droplet-electric-1 electric-sync-droplet-electric-1 | =INFO REPORT==== 23-Oct-2024::13:16:01.777082 === electric-sync-droplet-electric-1 | Loading 140 CA(s) from otp store electric-sync-droplet-electric-1 | 13:16:01.832 [info] Running Electric.Plug.Router with Bandit 1.5.5 at 0.0.0.0:3000 (http) electric-sync-droplet-electric-1 | 13:16:01.935 [info] Acquiring lock from postgres with name electric_slot_default electric-sync-droplet-electric-1 | 13:16:01.937 [info] Lock acquired from postgres with name electric_slot_default electric-sync-droplet-electric-1 | 13:16:02.006 [info] Postgres server version = 160004, system identifier = 7428958789530034185, timeline_id = 1 electric-sync-droplet-electric-1 | 13:16:02.145 [info] No previous timeline detected. electric-sync-droplet-electric-1 | 13:16:02.146 [info] Connected to Postgres and timeline electric-sync-droplet-electric-1 | 13:16:02.147 [info] Starting shape replication pipeline electric-sync-droplet-electric-1 | 13:16:02.150 [info] Starting replication from postgres ``` -------------------------------- ### Install Caddy root certificate Source: https://electric.ax/docs/sync/quickstart.md Install the Caddy root certificate to enable HTTP/2 in local development. ```sh caddy trust # may require sudo ``` -------------------------------- ### Apply database migrations Source: https://electric.ax/docs/sync/quickstart.md Run database migrations to set up the schema. ```shell pnpm migrate ``` -------------------------------- ### Deploy the application Source: https://electric.ax/docs/sync/quickstart.md Deploy the application to a hosting provider like Netlify. ```shell pnpm deploy ``` -------------------------------- ### Scaffold a new Electric Agents project Source: https://electric.ax/docs/agents/reference/cli.md Initializes a new project from the bundled starter template. Optionally provide a project name. ```bash electric agents init electric agents init my-agents-app ``` -------------------------------- ### Start Electric Agents Dev Server Source: https://electric.ax/docs/agents/walkthrough Launch the Electric Agents development environment using Docker. ```sh pnpx electric-ax@latest agents start ``` -------------------------------- ### run(argv?) Source: https://electric.ax/docs/agents/reference/cli.md Runs the CLI entrypoint. ```APIDOC ## run(argv?) ### Description Runs the Electric Agents CLI entrypoint. ### Parameters - `argv` (string[], optional) - The arguments to pass to the CLI. ### Example ```ts await run(["node", "electric", "agents", "types"]) ``` ``` -------------------------------- ### Proxy handler with GET and POST support Source: https://electric.ax/docs/sync/guides/auth.md Implements a proxy endpoint that accepts both GET and POST requests. For POST, it forwards the client body (subset params) to Electric; for GET, it sends WHERE as URL query parameters. It sets shape definition server-side (table, queryable_columns, columns, where) and removes content-encoding and content-length headers from the response. ```tsx import { ELECTRIC_PROTOCOL_QUERY_PARAMS } from '@electric-sql/client' export async function handler(request: Request) { const url = new URL(request.url) const method = request.method // Construct the upstream Electric URL const originUrl = new URL(`http://localhost:3000/v1/shape`) // Pass through Electric protocol parameters (offset, handle, live, etc.) url.searchParams.forEach((value, key) => { if (ELECTRIC_PROTOCOL_QUERY_PARAMS.includes(key)) { originUrl.searchParams.set(key, value) } }) // Authentication const user = await loadUser(request.headers.get(`authorization`)) if (!user) { return new Response(`unauthorized`, { status: 401 }) } // Set shape definition server-side (this is your authorization layer) originUrl.searchParams.set(`table`, `items`) originUrl.searchParams.set(`queryable_columns`, `id,title,created_at`) originUrl.searchParams.set(`columns`, `id,title`) originUrl.searchParams.set(`where`, `"organization_id" = '${user.org_id}'`) originUrl.searchParams.set(`secret`, process.env.ELECTRIC_SECRET) // Forward request to Electric let response: Response if (method === 'POST') { // POST: Forward client body (subset params can only narrow results) const clientBody = await request.text() response = await fetch(originUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: clientBody, // Client subset params (where, limit, order_by, etc.) }) } else { // GET: Simple proxy response = await fetch(originUrl) } // Forward response to client (remove problematic headers) const headers = new Headers(response.headers) headers.delete(`content-encoding`) headers.delete(`content-length`) return new Response(response.body, { status: response.status, statusText: response.statusText, headers, }) } ``` -------------------------------- ### Start built-in runtime Source: https://electric.ax/docs/agents/reference/cli.md Starts the built-in Horton and worker runtime, registers built-in agent types, and runs a pull-wake runner. Requires an Anthropic API key. ```bash electric agents start-builtin --anthropic-api-key sk-ant-... ```