Skip to content
NewMulti-tenancy and row-level security (RLS) in TypeScript6 min read

Browser

A query can run from the browser two ways: sent to your API with uql-orm/browser, or against Postgres running in the tab with uql-orm/pglite.

createClientQuerier calls the API that uql-orm/http serves, over a transport: httpTransport for its HTTP protocol, or any other, such as a tRPC procedure. Share your entity classes with the browser and the query type-checks exactly as it does on the server:

import { createClientQuerier, httpTransport } from 'uql-orm/browser';
import { User } from './shared/models/index.js';
const querier = createClientQuerier(
httpTransport('https://api.yourdomain.com/api/v1'),
);
const users = await querier.findMany(User, {
$select: { email: true },
$populate: { profile: { $select: { picture: true } } },
$where: { email: { $endsWith: '@domain.com' } },
$limit: 10,
});
// typed User[], each with a typed profile

It has the pool’s methods a client may call: findMany, findManyAndCount, findManyPage, findOne, findOneById, count, exists, insertOne, insertMany, saveOne, saveMany, updateOneById, updateMany, deleteOneById and deleteMany. Each answers what the pool’s does: rows, a count, [rows, count], a page, the keys a write fills.

The query travels as JSON, so the client takes a WireQuery, which has no room for sql fragments. A sql fragment or a binary value throws before anything is sent; handle those in a route of your own.

Rows come back as the entity holds them, a Date field a Date and a bigint exact, read by the entity’s metadata, which importing its class registers. So they are not plain JSON: a cache that persists them, such as a query persister or dehydrated SSR state, needs a serializer that keeps a Date and a bigint.

A failed request over HTTP throws a RequestError, and so does a success that is no JSON { data } envelope (an HTML page a wrong base URL lands on), with the server’s message, its HTTP status, its error kind when it has one, and the path in the call that is at fault, such as ['query', '$where', 'email']:

import { RequestError } from 'uql-orm/browser';
try {
await querier.findMany(User, {});
} catch (err) {
if (err instanceof RequestError && err.status === 401)
location.href = '/login';
}

Headers set on the transport apply to every call, and per-call options add to them:

const querier = createClientQuerier(
httpTransport('/api/v1', {
headers: { Authorization: `Bearer ${session.token}` },
}),
);
await querier.findMany(
User,
{ $limit: 20 },
{ signal: AbortSignal.timeout(10_000) },
);

During server rendering, create one transport per request so a token never leaks into another user’s request. If the server names paths with entityPath, pass the same function to createClientQuerier(transport, { entityPath }).

Reads go as GET by default, the call in ?q=, so a browser or CDN can cache them. Set readMethod to 'POST' or 'QUERY' to send them in the request body instead, past URL-length limits on large queries:

const querier = createClientQuerier(
httpTransport('/api/v1', { readMethod: 'QUERY' }),
);

Writes are always POST. A body costs a CORS preflight cross-origin, and QUERY also needs every proxy on the way to forward the method.

A transport is a function, (call, opts) => Promise<unknown>, so wrapping one runs code around every call, enough for a global spinner:

const http = httpTransport('/api/v1');
const querier = createClientQuerier(async (call, opts) => {
document.body.classList.add('loading');
try {
return await http(call, opts);
} finally {
document.body.classList.remove('loading');
}
});

PGlite is Postgres compiled to WASM. Give PgliteQuerierPool an idb:// directory and the database lives in IndexedDB, surviving reloads. It is the postgres dialect, so your entities, queries and migrations are the server’s:

import { PgliteQuerierPool } from 'uql-orm/pglite';
const pool = new PgliteQuerierPool('idb://app');
const users = await pool.findMany(User, { $select: { id: true, email: true } });

PGlite has one connection, so one transaction runs at a time. To share one database across tabs, run PGlite in a worker and pass its handle to the pool. PGlite covers the rest.