Skip to main content

Client

ElectricSQL provides a schema-aware, type-safe database client from the electrified subset of your Postgres DDL schema.

Generate this TypeScript client as part of your build process, instantiate it within your local application and then use it to sync shapes, query and write data.

Generating the client

Use the generator command to generate the TypeScript client:

npx electric-sql generate

By default this outputs a ./src/generated/client folder with an index.ts file as an entrypoint for you to import into your application code when instantiating your database client.

Instantiating the client

The exact code for instantiating your database client depends on the local database driver that you're using for your target environment. However, the steps are the same across drivers:

  1. initialise a database connection (conn) using your underlying driver
  2. import your database schema (schema) from the ./generated/client folder
  3. optionally define a custom configuration config
  4. pass these to your driver's electrify function to instantiate the client
  5. connect to Electric using your authentication token

For example, for wa-sqlite in the web browser:

import { ElectricDatabase, electrify } from 'electric-sql/wa-sqlite'
import { schema } from './generated/client'

const config = {
url: "http://localhost:5133",
debug: true
}

const init = async () => {
const conn = await ElectricDatabase.init('my.db')
const electric = await electrify(conn, schema, config)
await electric.connect('your token')
return electric
}

See Integrations -> Drivers and API -> Typescript client for more information.

Using the client

The client then provides a Prisma-inspired API for syncing shapes, defining queries and making writes, as well as the ability to drop down to raw SQL when necessary.

For example:

const { db } = await init()
const results = await db.projects.findMany()

See the next pages on shapes, queries and writes and the API -> Typescript client docs for more detailed information on the specific function calls.

Note

Typically you would instantiate the client once and then pass it around via some kind of context machinery. See Integrations -> Frontend for more information.