package
Postgres everywhere - your data, in sync, wherever you need it.
npm install @electric-sql/clientGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
Real-time Postgres sync for modern apps.
Electric provides an HTTP interface to Postgres to enable a massive number of clients to query and get real-time updates to subsets of the database, called Shapes. In this way, Electric turns Postgres into a real-time database.
The TypeScript client helps ease reading Shapes from the HTTP API in the browser and other JavaScript environments, such as edge functions and server-side Node/Bun/Deno applications. It supports both fine-grained and coarse-grained reactivity patterns — you can subscribe to see every row that changes, or you can just subscribe to get the whole shape whenever it changes. The client also supports dynamic options through function-based params and headers, making it easy to handle auth tokens, user context, and other runtime values.
The client is published on NPM as @electric-sql/client:
npm i @electric-sql/clientThe client exports a ShapeStream class for getting updates to shapes on a row-by-row basis as well as a Shape class for getting updates to the entire shape.
ShapeStreamimport { ShapeStream } from '@electric-sql/client'
const BASE_URL = 'http://localhost:3000'
// Passes subscribers rows as they're inserted, updated, or deleted
const stream = new ShapeStream({
url: `${BASE_URL}/v1/shape`,
params: {
table: `foo`,
},
})
// You can also add custom headers and URL parameters
const streamWithParams = new ShapeStream({
url: `${BASE_URL}/v1/shape`,
headers: {
Authorization: 'Bearer token',
},
params: {
table: `foo`,
Shapeimport { ShapeStream, Shape } from '@electric-sql/client'
const BASE_URL = 'http://localhost:3000'
const stream = new ShapeStream({
url: `${BASE_URL}/v1/shape`,
params: {
table: `foo`,
},
})
const shape = new Shape(stream)
// Returns promise that resolves with the latest shape data once it's fully loaded
await shape.rows
// passes subscribers shape data when the shape updates
shape.subscribe(({ rows }) => {
// rows is an array of the latest value of each row in a shape.
})Metro and Expo resolve the package's react-native export for native builds, so standard imports automatically wire React Native AppState into ShapeStream. If your bundler setup does not resolve the root react-native condition, use the explicit @electric-sql/client/react-native entrypoint or pass runtimeVisibility explicitly. See the TypeScript client docs for details.
The ShapeStream provides robust error handling with automatic retry support:
The onError handler gives you full control over error recovery:
import { ShapeStream, FetchError } from '@electric-sql/client'
const BASE_URL = 'http://localhost:3000'
const getRefreshedToken = () => 'refreshed-token'
const fallbackUserId = 'fallback-user-id'
const stream = new ShapeStream({
url: `${BASE_URL}/v1/shape`,
params: { table: `foo` },
onError: (error) => {
console.error('Stream error:', error)
// IMPORTANT: Return an object to keep syncing!
// Return void/undefined to stop syncing permanently.
// Note: 5xx errors and network errors are automatically retried,
// so onError is mainly for handling client errors (4xx)
Critical: The onError callback's return value controls whether syncing continues:
{}) to retry syncing:
{} - Retry with same params and headers{ params } - Retry with modified params{ headers } - Retry with modified headers{ params, headers } - Retry with both modifiedThe handler supports async operations:
import { FetchError } from '@electric-sql/client'
const refreshAuthToken = async () => 'refreshed-token'
const options = {
onError: async (error: Error) => {
if (error instanceof FetchError && error.status === 401) {
// Perform async token refresh
const newToken = await refreshAuthToken()
return {
headers: { Authorization: `Bearer ${newToken}` },
}
}
return {} // Retry other errors
},
Automatic retries: The client automatically retries 5xx server errors, network errors, and 429 rate limits with exponential backoff. The onError callback is only invoked after these retries are exhausted, or for non-retryable errors like 4xx client errors.
Without onError: If no onError handler is provided, non-retryable errors (like 4xx client errors) will be thrown and the stream will stop.
Individual subscribers can handle errors specific to their subscription:
stream.subscribe(
(messages) => {
// Handle messages
},
(error) => {
// Handle errors for this specific subscription
console.error('Subscription error:', error)
}
)Note: Subscription error callbacks cannot control retry behavior - use the stream-level onError for that.
Setup errors:
MissingShapeUrlError: Missing required URL parameterInvalidSignalError: Invalid AbortSignal instanceReservedParamError: Using reserved parameter namesRuntime errors:
FetchError: HTTP errors during shape fetching (includes status, url, headers)FetchBackoffAbortError: Fetch aborted using AbortSignalMissingShapeHandleError: Missing required shape handleParserNullValueError: NULL value in a non-nullable columnSee the TypeScript client docs for more details.
And in general, see the docs website and examples for more information.
Install the pnpm workspace at the repo root:
pnpm installBuild the package:
cd packages/typescript-client
pnpm buildIn one terminal, start the backend running:
cd ../sync-service
mix deps.get
mix stop_dev && mix compile && mix start_dev && iex -S mixThen in this folder:
pnpm testicehaunter
icehaunter@gmail.com
Estimated unpacked size across 2 packages.
2.3 MB
Includes dependencies.