Client
@supatype/client talks to your project’s REST, auth, storage, realtime and functions. Its types come from your schema, so a wrong table or column fails the build.
Pre-1.0: APIs and config may change between releases.
Create the client
Import createClient from the client file the CLI generates, not from @supatype/client directly. The generated file tells the client which models keep drafts.
import { createClient } from "../supatype/generated/client"
export const supatype = createClient({ url: import.meta.env.VITE_SUPATYPE_URL, anonKey: import.meta.env.VITE_SUPATYPE_ANON_KEY,})Every page in these docs imports the client from this one file. In development, supatype init, supatype dev and supatype keys write the local stack’s VITE_SUPATYPE_URL and VITE_SUPATYPE_ANON_KEY, with PUBLIC_, NEXT_PUBLIC_ and EXPO_PUBLIC_ copies for other frameworks, to .env.development.local. Vite, Next.js and Expo read that file in development only, so a production build never ships them. Read these rather than copying a URL from an example: init picks a free gateway port for each project, kept in .env as API_EXTERNAL_URL.
A production build gets your deployment’s values from supatype build, which runs your build command with them, or from the host’s settings. When Supatype serves the app, the page can read them from the server instead, with <script src="/supatype-env.js" vite-ignore></script> in index.html (vite-ignore keeps vite build from warning that it cannot bundle it); a Next.js app serves the same script from a route (Frameworks: Next.js). For each value the build did not carry, the client reads the one that script set, at its first request. It never guesses the address from the page. createClient itself never throws, so a page that creates the client at module scope still prerenders. The first request made with no address or no anon key throws a MissingClientValuesError naming what is missing and the variables to set, rather than returning it as { data: null, error }. Deploy your frontend covers each host.
supatype.url and supatype.anonKey are the address and anon key the client uses: the ones given to createClient, else the ones the page set (see above), read each time you ask. Each is an empty string while neither has one, and neither throws. Use anonKey for a call the client does not make, such as opening a second connection or a plain fetch to the API.
The session is saved and restored by default. A restored session keeps the user as it was, including isAnonymous, identities and factors, so a guest is still a guest after a reload. Pass auth: { persistSession: false } to keep it in memory only.
createClient takes these options as well as url and anonKey:
| Option | What it does |
|---|---|
serviceRoleKey | Bypasses row-level security. Use it only on a server or in a trusted tool, and never ship it to a browser. |
headers | Headers sent with every request. Pass a function to have it read on each request. |
auth.storageKey | Key the session is saved under. Default "supatype.auth.session". |
auth.storage | Your own session store with getItem, setItem and removeItem, such as AsyncStorage in React Native. |
auth.cookiePrefix | Prefix of the auth cookie @supatype/ssr reads. Default "st". |
timeout, retry | See Timeouts and retries. |
initialSession | A session to start with. @supatype/ssr uses it to hand a cookie session to the client. |
queryCache | The in-memory cache for .cache() reads. Default: one shared cache. |
Generated types
supatype dev, supatype push and supatype generate write these files. Do not edit them.
| File | Holds |
|---|---|
supatype/generated/client.ts | The createClient to import, the table types, the columns that keep exact values and the models that keep drafts. It also re-exports @supatype/client |
supatype/generated/index.d.ts | Row, insert and update types for each table |
types/database.ts | The Database type, for code that wants the raw shapes |
Tables are named as in the database: post, comment, post_tag. Calling createClient with no type argument picks up the generated types. To type a client against a schema you do not generate, such as a second project or a test double, pass the database type: createClient<MyDatabase>({ ... }).
Exact numbers keep every digit when you import from the generated client.ts. A BigInt column reads as a bigint. Decimal and Money columns read as strings.
A number too large for JavaScript, in a column the client does not know, returns an error that names the column. This usually happens in an embed: select the column directly instead. This covers a number inside an array too, at any depth, such as a json column holding [9007199254740993]. BigInt[] and Decimal[] columns the generated types describe keep every element exact instead.
Read rows
const { data: posts, error } = await supatype .from("post") .select("id, title, slug, author(name), comment(body)") .order("published_at", { ascending: false }) .limit(10)
if (error) throw new Error(error.message)for (const post of posts ?? []) console.log(post.title, post.author?.name)select takes a list of columns. The result type follows the list. * selects every column.
Name a related table to embed it: author(name) follows author_id, and comment(body) lists a post’s comments. A many-to-many relation embeds through its junction table: select("title, tag(name)").
A to-one embed can be null. Write author!inner(name) to keep only posts that have one. Rename an embed with writer:author(name).
single() returns one row and errors when there is not exactly one. maybeSingle() returns null for no row.
const { data: post } = await supatype.from("post").select("*").eq("slug", "hello-world").maybeSingle()console.log(post?.title)Linking many-to-many rows
A many-to-many link is a row in the junction table, and you write it like any other row. The junction is named after the two tables, sorted and joined with _ (lot_tag for lot and tag), with a <model>_id column for each end. It is in the generated types, so from("lot_tag") is typed. Nested connect and set writes are not supported yet.
// add a link, and several at onceawait supatype.from("lot_tag").insert({ lot_id: lot.id, tag_id: tag.id })await supatype.from("lot_tag").insert(tags.map((t) => ({ lot_id: lot.id, tag_id: t.id })))
// list a lot's tags, or the links themselvesconst { data } = await supatype.from("lot").select("title, tags:tag(name)").eq("id", lot.id)const { data: links } = await supatype.from("lot_tag").select("tag_id").eq("lot_id", lot.id)
// remove a linkawait supatype.from("lot_tag").delete().eq("lot_id", lot.id).eq("tag_id", tag.id)Who may write a link follows from its two ends. A link is readable by a caller who can read both rows, and writable by a caller who can read both and may update the model that owns the link: the one whose own ManyToMany field names the junction (either one, when both declare it). A refused insert returns an error. A delete the caller may not make removes no row and returns no error, so ask for the deleted rows with .select() if you need to know. See Access Rules.
count is null unless you ask for it:
const { count } = await supatype.from("post").select("id", { count: "exact" }).eq("kind", "news")console.log(count)Filters
| Filter | Matches |
|---|---|
eq, neq | equal, not equal |
gt, gte, lt, lte | greater or less than |
like, ilike | a pattern, ilike ignores case |
in | any of a list |
is | null, true or false |
contains, containedBy | an array, range or jsonb column that holds the value, or is held by it |
not, or, match | negation, either filter, several equalities |
await supatype.from("post").select("id").in("kind", ["news", "guide"]).is("published_at", null)await supatype.from("post").select("id").ilike("title", "%hello%").range(0, 19)Reads also take order, limit and range. Filters work on update and delete too.
Cache a read
.cache({ ttl }) keeps a read’s result in the client’s memory for ttl milliseconds. Add server: true to cache it on the server as well, for a model that declares a cache; add public: true to share one entry between users when the model allows it.
const { data, meta } = await supatype .from("post") .select("id, title") .cache({ ttl: 30_000, server: true }) // milliseconds
console.log(meta?.cacheStatus) // "HIT", "MISS" or "BYPASS"The cache status is meta.cacheStatus, on the result next to data and error: it is not a field of the result itself. It is "HIT" when a cache answered and "MISS" when the read went to the database. "BYPASS" appears only when the server says so in its X-Supatype-Cache-Status header. A model with no server cache, or a project with caching off, sends no header, and the read reports "MISS". A read that did not call .cache() has no meta.cacheStatus, and meta itself can be absent.
Globals
A singleton model (singleton: true) holds one row that always exists, such as site settings. global(name) reads and updates it without a filter. name is the model’s snake case name, as in _global_site_settings; for a model that sets its own tableName, use from(tableName) instead.
const { data: settings } = await supatype.global<{ title: string }>("site_settings").get()await supatype.global("site_settings").update({ title: "New title" })get() returns the row, or null. update(fields) changes only the fields you name and returns the row. Both return { data, error }, and the model’s access rules apply as for any other read or write.
Insert, update, delete
const { data: created, error: insertError } = await supatype .from("post") .insert({ title: "Draft idea", body: "Plain text is fine.", kind: "guide", author_id: userId }) .select("id") .single()if (insertError || !created) throw new Error(insertError?.message ?? "insert failed")
await supatype.from("comment").update({ body: "Edited" }).eq("id", commentId)await supatype.from("comment").delete().eq("id", commentId)A write returns no rows unless you add .select(): without it, data is null. Returning a row needs permission to read it, so leave .select() off when the access rules let the caller create a row but not read it. On a write, single() and maybeSingle() work only after .select(). On a delete, .select() returns the rows it deleted. upsert inserts or updates by primary key.
An update or delete with no filter is refused, so .delete() alone returns an error instead of emptying the table. The supatype/postgres image loads pg_safeupdate, which raises DELETE requires a WHERE clause (or the same for UPDATE). To change every row, add a filter that matches all of them, such as .not("id", "is", null).
A RichText field takes a plain string on write.
Some owner columns can be left out. A SupatypeAuthUserId field that the create rule names in Owner<>, and that has no default of its own, defaults to the caller. A relation’s key, such as author_id, is not filled in, so send it.
Drafts and publishing
On a model with versions: { drafts: true }, update saves a draft. The live row does not change until the record is published.
// Save a draftawait supatype.from("post").update({ title: "Better title" }).eq("id", postId)
// Save and publish in one callawait supatype.from("post").update({ title: "Final title" }, { publish: true }).eq("id", postId)
// Read draftsconst { data: drafts } = await supatype.from("post").draft().select("id, title").eq("id", postId)
// Publish the saved draftawait supatype.rpc("publish", { model_table: "post", record_id: postId }, { schema: "supatype" })insert on a drafts model creates a draft record. Publish it to make it live. A plain select() reads the live table, which holds the published values.
{ publish: true } is only accepted on drafts models, and only when the client comes from the generated file.
Auth
await supatype.auth.signUp({ email: "alex@example.com", password: "a-long-password" })
const { data, error: signInError } = await supatype.auth.signInWithPassword({ email: "alex@example.com", password: "a-long-password",})if (signInError) throw new Error(signInError.message)console.log(data.session?.user.id)
const { data: { session } } = await supatype.auth.getSession()console.log(session?.accessToken)
const { data: { subscription } } = supatype.auth.onAuthStateChange((event, current) => { console.log(event, current?.user.email)})subscription.unsubscribe()
await supatype.auth.signOut()Once signed in, every request carries the user’s token, so access rules see them. onAuthStateChange calls back at once with the current state, then on each change.
When the project asks new users to confirm their email, signUp returns session: null and does not sign the user in. They sign in once they have confirmed.
getUser() fetches the user from the server. Magic links, OAuth, one-time codes and MFA are on supatype.auth too, and so is SAML single sign-on: signInWithSSO({ domain }) or signInWithSSO({ providerId }) sends the browser to the organisation’s identity provider, with PKCE by default. See Single sign-on.
Storage
const bucket = supatype.storage.from("covers")
const { data: upload, error: uploadError } = await bucket.upload(`${userId}/cover.png`, file, { contentType: "image/png", upsert: true,})if (uploadError || !upload) throw new Error(uploadError?.message ?? "upload failed")
const { data: { publicUrl } } = bucket.getPublicUrl(upload.path)const { data: signed } = await bucket.createSignedUrl(upload.path, 60)console.log(publicUrl, signed?.signedUrl)getPublicUrl works for public buckets. createSignedUrl gives a link that expires after the number of seconds you pass. download, list and remove are on the bucket too.
An ImageAsset or FileAsset column holds { bucket, path }, not a URL. publicUrl builds the URL from it, and returns null for an empty column:
const { data: post } = await supatype.from("post").select("title, cover").eq("slug", "hello-world").maybeSingle()const coverUrl = supatype.storage.publicUrl(post?.cover)The bucket’s access rules from the schema decide who may upload, overwrite and delete.
Realtime
const sub = supatype.from("comment").subscribe((change) => { console.log(change.eventType, change.new, change.old)}, { event: "INSERT" })
sub.unsubscribe()Each change reaches only subscribers allowed to read that row. event is INSERT, UPDATE, DELETE or *. For broadcast and presence, use supatype.realtime.channel(name).
Functions
const { data: reply, error: fnError } = await supatype.functions.invoke("hello", { body: { name: "Alex" } })if (fnError) console.error(fnError.code, fnError.message)console.log(reply)The call goes to /functions/v1/hello with the user’s token. A JSON response is parsed. Function names and bodies are not typed. invoke also takes method (default POST), headers and idempotent. Only a GET is retried on a transient failure, because a POST may already have run. Pass idempotent: true when running the function twice is harmless.
await supatype.functions.invoke("stats", { method: "GET", headers: { "x-region": "eu" } })Inside a function, ctx.url is the API’s internal address, for calls the function makes. ctx.publicUrl is the public address, for links you give to people.
supatype.rpc(name, params, options) calls a Postgres function. Its options are count, head, schema for a function outside the default schema, and idempotent. A function is not part of the schema: see Server logic in a Postgres function for writing one and what Supatype does not manage.
GraphQL
import type { TableRow } from "../supatype/generated/client"
type Post = TableRow<"post">type Author = TableRow<"author">type PostPage = { postCollection: { edges: { node: Pick<Post, "title" | "body"> & { author: Pick<Author, "name"> } }[] }}
const { data, error } = await supatype.graphql<PostPage>(`{ postCollection(first: 10) { edges { node { title body author { name } } } }}`)if (error) throw new Error(error.message)const first = data?.postCollection.edges[0]?.nodeconsole.log(first?.author.name, first?.body.root.children?.[0])The query goes to /graphql/v1 as the signed-in user, under the same access rules as REST. Pass variables as the second argument, and { idempotent: true } as the third to retry a read on a transient failure.
Rich text, blocks and json fields come back as objects and arrays, not strings. pg_graphql types every json and jsonb column with its JSON scalar and sends it as a JSON-encoded string, so the client reads the schema once per role, finds each field of that type in your query, and decodes it. Aliases, named and inline fragments, nested relations and lists all decode. A field the client cannot place stays exactly as returned: one added since the schema was read (it reads the schema again on the next call), a document with more than one operation, or a schema it could not read.
The type argument names the answer’s shape and is not checked at runtime. Build it from the generated TableRow types so body is typed as the rich text document it now is. Variables you send are not encoded: a json argument still takes a string.
Relation fields use your schema’s names. The side that holds the key takes the relation field’s name, so author above. The other side takes its HasMany or HasOne field’s name, so an author’s posts are posts. A list is still a connection, read through edges { node }. REST embeds are named as before.
Using another GraphQL client? readGraphqlSchema reads the data of an introspection answer to GRAPHQL_SCHEMA_QUERY, and decodeGraphqlJsonFields(query, data, schema) decodes an answer the same way. Read the schema again when it returns schemaIsStale: true.
Errors
Queries, rpc, functions.invoke, auth and most storage calls return { data, error }. Check error before using data.
error is a SupatypeError, an Error with message and, when known, code, status, details and hint, so error instanceof SupatypeError holds and String(error) reads SupatypeError: <message>. Its own fields are only those, so spreading it or turning it into JSON gives exactly them. A failure in transit is the SDK error the client threw, such as a NetworkError (error instanceof NetworkError); those are SupatypeCodedErrors, which always carry a code and a helpUrl. When a field validator refused the write, field names the column, so you can mark that input.
An insert an access rule refuses returns code 42501. An update or delete that the rules hide matches no rows and returns no error. single() with no row returns PGRST116.
When the server refuses a request with 401, the client sends it again only if the token expired or was invalid (PGRST301, PGRST303 or “JWT expired”), the caller is signed in, and refreshing the session gave a new token. Any other 401 is returned as error after one try, including an anon write that an access rule refuses.
Timeouts and retries
Every HTTP request the client makes (tables, rpc, graphql, functions, auth and storage, uploads included) is aborted after timeout milliseconds, 30000 by default. Raise it for large uploads on slow links. The realtime socket is not an HTTP request and is not covered.
Only requests that are safe to send twice are retried:
GETandHEADrequests: table selects, storage downloads,auth.getUser(), and anrpccall withhead: true.- The two reads storage sends as
POST:listandcreateSignedUrl. - An
rpc,graphqlorfunctions.invokecall you passidempotent: true.
Inserts, updates, upserts, deletes, uploads, sign-in and sign-up, and any rpc, graphql or function call without idempotent: true are sent once: a write that failed in flight may already have been applied, and sending it again could apply it twice. A 429 on one of these comes back as the server’s own error.
A retried request is retried up to 3 times, after 200 ms, 1 s and 3 s, on a dropped connection or a 5xx. A 429 waits for its Retry-After (5 seconds when the header is absent). A timeout and a 4xx are never retried. retry: false turns retries off for every request.
const { data, error } = await supatype.rpc( "search_posts", { query: "supatype" }, { idempotent: true }, // the function only reads, so a retry is harmless)