# Real-time Sync

For Postgres databases, you can enable real-time data synchronization. This enables building real-time and local-first applications.

Sync is powered by Electric, a sync engine that streams changes from Postgres to clients using a plain HTTP API. It uses a proxy-based architecture where your backend proxies requests after handling authentication and authorization.

## Enabling sync

Reference `sync.url` and `sync.secret` in your service env:

```hcl
postgres "main" {}

service "api" {
  command = "node index.js"

  endpoint {
    public = true
  }

  env = {
    DATABASE_URL         = postgres.main.url
    DATABASE_SYNC_URL    = postgres.main.sync.url
    DATABASE_SYNC_SECRET = postgres.main.sync.secret
  }
}
```

When these references are present, Specific automatically starts a sync engine connected to your Postgres database during `specific dev`.

## Available sync attributes

- `sync.url` - Sync engine HTTP endpoint URL (e.g., `http://127.0.0.1:5133`)
- `sync.secret` - Secret for authenticating requests to the sync engine. This should be passed as the `secret` query parameter from the backend to the Electric API.

## How sync works

The sync engine streams "shapes" of data from Postgres to clients:

1. Your backend proxies shape requests to the sync engine (handles auth/authz)
2. The sync engine streams the initial data and subsequent changes
3. Clients receive real-time updates over HTTP

For implementation details, see the Electric documentation:

- Authentication and proxying: https://electric-sql.com/docs/guides/auth
- Shapes and client usage: https://electric-sql.com/docs/guides/shapes
- Handling writes: https://electric-sql.com/docs/guides/writes

## Using the Electric TypeScript SDK

When using `ShapeStream` from the Electric TypeScript SDK, a full URL is required (not a relative URL). In browsers, derive the full URL from `window.location.origin` instead of using a relative one:

```typescript
import { ShapeStream } from "@electric-sql/client";

const stream = new ShapeStream({
  url: `${window.location.origin}/api/sync/items`,
});
```

This ensures the client works correctly regardless of the deployment environment.

---

Run `specific docs postgres` for database configuration.
