Skip to content
NordBaseDocs

Search the docs

Find a page or a section of the NordBase docs

Connect

Node library

The nordbase package for Node: client, tagged-template SQL, the builder, Consistency, Document Databases and errors.

The nordbase package wraps a proven PostgreSQL driver and the official MongoDB driver. It adds what NordBase needs: reading NORDBASE_URL, choosing a Region, Consistency, parameter-only SQL and the Document guard.

Install

bash
npm i nordbase

Create a client

ts
import { createClient } from 'nordbase'

const db = createClient()

createClient() reads NORDBASE_URL, or the key file at NORDBASE_KEY_FILE when the URL is not set. On first use it picks the Region to serve Reads from, using NORDBASE_REGION or the fastest Endpoint. See Connection URL.

Options:

OptionDefaultWhat it does
consistency'nearest''strong' sends every Read from this client to the Primary
stickyAfterWriteMs2000After a Write, this client's Reads go to the Primary for this many milliseconds
ts
const primary = createClient(process.env.NORDBASE_URL, { consistency: 'strong', stickyAfterWriteMs: 2000 })

Create one client per process and reuse it. It holds a connection pool.

SQL

db.sql is a tagged template. Every ${value} becomes a bind parameter, never SQL text.

ts
import { createClient, sql } from 'nordbase'

const db = createClient()

const customerId = 1042
const orders = await db.sql`
  select id, total, status
  from orders
  where customer_id = ${customerId}
  order by created_at desc
  limit 20
`
NeedWrite
A value${value}
A table or column name from a variable${sql.id(name)}
A list of values${sql.join(ids)}
An optional piece of SQLA nested template, sql`and status = ${status}`
Raw text you wrote, with $1…$ndb.unsafe(text, params)
A multi-statement migration filedb.unsafeScript(text)

A plain string passed to db.sql, including db.sql(`...${x}`) with parentheses, is refused before sending, with an error that shows the safe form. See Safe SQL.

The builder

ts
const latest = await db
  .from('orders')
  .select('id, total, status')
  .eq('customer_id', 1042)
  .order('created_at', { desc: true })
  .limit(20)

const [created] = await db.from('orders').insert({ customer_id: 1042, total: '3480.00', status: 'pending' }).returning('id')
await db.from('orders').update({ status: 'paid' }).eq('id', created.id)
await db.from('customers').upsert(rows, { onConflict: 'email' })

Rows are validated before sending. Any Standard Schema library works, such as Zod or Valibot, and npx nordbase gen types writes the schemas from your live Database. See The builder.

Transactions

How a transaction behaves on NordBase is fixed:

  • A transaction that contains a Write runs on the Primary as a whole.
  • A transaction started read-only may use a Replica.
  • On port 5432, session state lasts for one transaction: use set local, not set.

The transaction function in the Node library is coming soon. Until it is documented here, run a transaction with any PostgreSQL driver or ORM over the same NORDBASE_URL; the Router applies the same rules.

Consistency

ts
const db = createClient()                               // Reads from the nearest Instance
const primary = createClient(process.env.NORDBASE_URL, { consistency: 'strong' }) // Reads from the Primary

const [account] = await primary.sql`select balance from accounts where id = ${accountId}`

After a Write, a client's own Reads go to the Primary for stickyAfterWriteMs. Choosing Consistency for a single call is part of the library contract; its exact form is coming soon. See Replicas and Consistency.

Document Databases

The library wraps the official mongodb driver and adds the operator-injection guard: a value that arrives as a plain object with a $ key is refused with UnsafeFilterError, and operators are written with helpers.

ts
import { op } from 'nordbase'

const filter = { status: 'paid', total: op.gt(100), region: op.in(['fi-hel', 'de-fsn']) }

How you create the Document client is coming soon. Until then, connect with the official driver and check the types of request fields yourself before they reach a filter:

ts
import { MongoClient } from 'mongodb'

const client = new MongoClient(process.env.NORDBASE_URL!)
const orders = client.db('shop').collection('orders')

const number = String(request.body.number) // a string, never an object
const order = await orders.findOne({ number })

See Document Databases.

Errors

ts
import { ReadOnlyLockError, PermissionError, ConnectionError } from 'nordbase'

try {
  await db.sql`insert into orders (number, customer_id, total) values (${number}, ${customerId}, ${total})`
} catch (err) {
  if (err instanceof ReadOnlyLockError) {
    // Storage is full: show the order form as read-only and alert the team
  } else if (err instanceof PermissionError) {
    // The Credential may not write here: check nordbase.whoami()
  } else if (err instanceof ConnectionError) {
    // The Endpoint was unreachable after retries; the message says if the Write may have been applied
  }
  throw err
}
ErrorWhen
AuthenticationErrorWrong, revoked or expired Credential
PermissionErrorNot allowed by the Permission set
ReadOnlyLockErrorStorage is full; Writes are refused
TooManyConnectionsErrorEvery connection your Plan allows is in use
TimeoutErrorA statement ran over 30 seconds on port 5432
ConnectionErrorUnreachable after retries
UnsafeFilterErrorA Document filter or update contained an operator as data

Reads and transactions that never reached the Database are retried for up to 30 seconds. A Write whose outcome is unknown is never retried. See Errors.