# TypeScript and Node.js

Connect to ParticleDB from TypeScript and Node.js, run parameterized queries, handle transactions and errors.

Source: https://particledb.ai/sdks/typescript/

Use the configured address for your client. See [connection addresses](/installation/ports/) and [security](/guides/security/). The ParticleDB SDK examples use the database port, 7173; the other examples use the SQL client address.

TypeScript and Node.js applications can use the ParticleDB SDK over the native client protocol
(port 7173) or node-postgres over the SQL client interface (port 5432).

## ParticleDB SDK

The [`@particledb/sdk`](https://www.npmjs.com/package/@particledb/sdk) package on npm, MIT
licensed from version `0.2.0`; the current version is `0.2.1`. It requires Node.js 20
or newer and server `1.1.19-rc.13` or later. TypeScript type declarations are included.

```bash
npm install @particledb/sdk
```

The example connects as `app`, with the password in `PARTICLEDB_PASSWORD`. Start the server
with the [local start command](/getting-started/quickstart/#2-start-locally), replacing
`--no-auth` with `--auth-method scram-sha-256 --pg-username app --pg-password-file ./pdb-password`.
The password file holds only the password. The SDK connects to `localhost:7173` by default.

Save this as `app.mjs`, or set `"type": "module"` in `package.json`, so Node.js runs it as an
ES module with top-level `await`:

```javascript
import { ParticleDB } from '@particledb/sdk';

const db = await ParticleDB.connect({
  user: 'app',
  password: process.env.PARTICLEDB_PASSWORD ?? '',
});
try {
  await db.execute('CREATE TABLE posts (id BIGINT PRIMARY KEY, title TEXT)');
  await db.execute('INSERT INTO posts VALUES ($1, $2)', [1, 'first']);

  await db.transaction(async tx => {
    await tx.execute('UPDATE posts SET title = $1 WHERE id = $2', ['updated', 1]);
  });

  console.log(await db.queryOne('SELECT id, title FROM posts WHERE id = $1', [1]));

  await db.kv.set('session:123', 'active');
  console.log(await db.kv.get('session:123'));
} finally {
  await db.close();
}
```

Output:

```
{ id: 1, title: 'updated' }
active
```

Keep one client per application; it pools connections. The transaction callback runs on one
connection, and a thrown error rolls it back.

With CommonJS, load the package with `require()` and run the calls inside an `async` function.
This form also sets the address explicitly; `localhost` and port `7173` are the defaults:

```javascript
const { ParticleDB } = require('@particledb/sdk');

async function main() {
  const db = await ParticleDB.connect({
    host: 'localhost',
    port: 7173,
    user: 'app',
    password: process.env.PARTICLEDB_PASSWORD ?? '',
  });
  try {
    console.log(await db.queryOne('SELECT 42 AS answer'));
  } finally {
    await db.close();
  }
}

main().catch(err => {
  console.error(err);
  process.exitCode = 1;
});
```

Output:

```
{ answer: 42 }
```

A wrong user or password fails `ParticleDB.connect` with a `ConnectionError` naming
`password authentication failed`.

## SQL client interface with node-postgres

Use [node-postgres](https://node-postgres.com/) (`pg`) over the SQL client interface (port 5432):
pooling, bind parameters and transactions are shown below.

### Install

```bash
npm install pg
npm install --save-dev @types/pg   # TypeScript types
```

The examples connect as `postgres` with the password `secret`, for a server started with
`particledb start --auth-method scram-sha-256 --pg-password secret`. With the server's default
`--auth-method password`, every SQL client login must use TLS: pass `ssl` options to the
pool. See [TLS and authentication](/connectivity/tls/#authentication).

### Quick start

```typescript
import { Pool } from 'pg';

const pool = new Pool({
  host: 'localhost',
  port: 5432,
  user: 'postgres',
  password: 'secret',
  database: 'particledb',
  max: 10,
});

async function main() {
  await pool.query('CREATE TABLE users (id BIGINT PRIMARY KEY, name TEXT, active BOOLEAN)');
  await pool.query('INSERT INTO users VALUES ($1, $2, $3)', [42, 'alice', false]);

  const { rows } = await pool.query<{ id: string; name: string }>(
    'SELECT id, name FROM users WHERE id = $1',
    [42],
  );
  console.log(rows); // [ { id: '42', name: 'alice' } ]

  const res = await pool.query('UPDATE users SET active = true WHERE id = $1', [42]);
  console.log(res.rowCount); // 1

  // Transaction: use one client for every statement in it
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    await client.query('INSERT INTO users VALUES ($1, $2, $3)', [43, 'bob', true]);
    await client.query('UPDATE users SET name = $1 WHERE id = $2', ['alicia', 42]);
    await client.query('COMMIT');
  } catch (e) {
    await client.query('ROLLBACK');
    throw e;
  } finally {
    client.release();
  }

  const all = await pool.query('SELECT id, name, active FROM users ORDER BY id');
  console.log(all.rows);
  await pool.end();
}

main().catch((e) => { console.error(e); process.exit(1); });
```

Output:

```
[ { id: '42', name: 'alice' } ]
1
[
  { id: '42', name: 'alicia', active: true },
  { id: '43', name: 'bob', active: true }
]
```

`BIGINT` and `count(*)` values arrive as strings (`'42'`), which is the `pg` driver's default
for 64-bit integers. Convert them with `Number()` or `BigInt()`, or register a type parser.

### Key-value and vector search

Key-value operations and vector search are SQL, so you call them with `pool.query()` like any
other statement, for example `SELECT KV_GET($1)` or
`ORDER BY embedding  '[0.1,0.2,0.3]' LIMIT 5`. Key-value data is also reachable over the
[Redis protocol](/connectivity/redis-commands/) with any Redis client. See
[Vector Search](/sql/vector-search/).

## Next steps

- [Browser](/sdks/web/). calling ParticleDB from browser code
- [SQL Reference](/sql/overview/). SQL syntax and examples
- [ORM compatibility](/connectivity/orm-compatibility/). Prisma, Drizzle, TypeORM, and other ORMs
