Frameworks
Supatype has bindings for React, Vue, Svelte and Solid, a React Native helper, and a server helper for Next.js. Each one wraps the client you already create, so everything on the Client page still applies.
Packages
| Package | Exports |
|---|---|
@supatype/react | SupatypeProvider, useSupatype, useQuery, useMutation, useFunction, useAuth, useSubscription, useChannel, useRealtimeConnection, useLivePreview, RichText |
@supatype/vue | supatypePlugin, useSupatype, useQuery, useMutation, useFunction, useAuth, useSubscription, useChannel, useRealtimeConnection |
@supatype/svelte | setSupatypeClient, getSupatypeClient, createQuery, createMutation, createFunction, createAuth, createSubscription, createChannel, createRealtimeConnection |
@supatype/solid | SupatypeContext, useSupatype, createQuery, createMutation, createFunction, createAuth, createSubscription, createChannel, createRealtimeConnection |
@supatype/react-native | createNativeClient, secureStoreAdapter, asyncStorageAdapter, openOAuth, createAuthUrlListener |
@supatype/ssr | createServerClient, and GET from @supatype/ssr/next |
supatype init adds @supatype/client to your app, and @supatype/ssr as well in a Next.js app. Add the binding for your framework yourself, on the same release as @supatype/client:
$ npm install @supatype/react # React and Next.js$ npm install @supatype/vue$ npm install @supatype/svelte$ npm install @supatype/solid$ npm install @supatype/react-native @supatype/react # React Native, then:$ npx expo install expo-secure-store expo-web-browser expo-linkingWith pnpm, Yarn or Bun, use that tool’s add command instead.
Every example below imports the client from src/supatype.ts, created once as shown in Client: Create the client. With Vite, read the names supatype dev writes for development and supatype build sets for a production build:
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,})A build made without the values, such as a plain vite build that Supatype serves, reads them from /supatype-env.js, so index.html needs <script src="/supatype-env.js" vite-ignore></script> in its head. init adds it only to an index.html it writes itself; in a Vite app that already had one, add the tag yourself, as Deploy your frontend: Supatype hosts it shows.
Sign-in screens are covered on Auth: Pre-built UI, and the subscription hooks on Realtime: Framework hooks. This page does not repeat them.
React
Wrap your app in SupatypeProvider and pass the client. Every hook reads the client from it and throws when there is no provider above it.
import { SupatypeProvider, useQuery, useMutation, useFunction } from "@supatype/react"import { supatype } from "./supatype"
function Posts() { const { data: posts, loading, error, refetch } = useQuery("post", { select: "id, title, slug", order: { column: "title" }, limit: 20, }) const { mutate: removePost } = useMutation("post", "delete") const { invoke: greet, data: reply } = useFunction<{ greeting: string }>("greet")
if (loading) return <p>Loading</p> if (error) return <p>{error.message}</p> return ( <ul> {posts?.map((post) => ( <li key={post.id}> {post.title} <button onClick={async () => { await removePost(undefined, { filter: { id: post.id } }); refetch() }}>Delete</button> </li> ))} <button onClick={() => greet({ name: "Alex" })}>{reply?.greeting ?? "Say hello"}</button> </ul> )}
export function App() { return <SupatypeProvider client={supatype}><Posts /></SupatypeProvider>}useQuery
useQuery(table, options) returns data, error, count, loading and refetch. It runs again when the options change, and when a different user signs in or out.
| Option | What it does |
|---|---|
select | The select expression. Default *. |
filter | Equality filters, one per column. |
order | { column, ascending }. Ascending by default. |
limit, offset | Paging. An offset with no limit reads 100 rows, in every binding. |
enabled | false skips the query. |
refetchInterval | Runs the query again every so many milliseconds. |
cache | The same cache options as the client’s .cache(). |
draft | Reads saved drafts instead of published rows, on a model with drafts. See Drafts and publishing. |
For anything filter cannot say, such as ranges or embeds with conditions, use the client directly through useSupatype().
useMutation and useFunction
useMutation(table, operation) takes "insert", "update", "delete" or "upsert" and returns mutate, loading and error. mutate(data, { filter, publish, select }) takes the rows to write; filter picks the rows for an update or delete, and publish: true publishes the drafts an update saves. Without select, the written rows are not returned and data is null, so call refetch on your query afterwards. To get them back, pass select: true for every column or a column string such as select: "id,title", written as .select() takes it. Returning rows needs permission to read them as well as write them.
mutate resolves with { data, error, count }. There are no onMutate, onSuccess or onError callbacks, so an optimistic update and its rollback are yours to write.
useFunction(name) returns invoke, data, error and loading. invoke(body, { method, headers }) calls supatype.functions.invoke. See Functions: Call a function.
useAuth() returns user, session, loading, error, signUp, signIn (email and password), signInWithOAuth, signInWithOtp and signOut, and re-renders when the session changes. For anything else, such as MFA or a password reset, call useSupatype().auth. See Auth.
Live preview
Studio can show your app in a pane beside the edit form and stream the unsaved values into it as the editor types. Tell Studio where a record’s page lives in supatype.config.ts:
export default defineConfig({ // ... admin: { livePreview: { Post: { urlPattern: "https://example.com/preview/{slug}" } } },})A path such as "/preview/{slug}" is enough when the same deployment serves your app (app.mode set to static or proxy). With app.mode: "none", supatype push refuses a path and wants the full URL.
On that page, useLivePreview returns the live values while Studio is sending them and your own data otherwise:
import { useLivePreview, RichText } from "@supatype/react"import type { TableRow } from "@supatype/client"
export function PostPreview({ post }: { post: TableRow<"post"> }) { const { data, isPreview } = useLivePreview({ initialData: post }) return ( <article> {isPreview && <p>Preview</p>} <h1>{data.title}</h1> <RichText content={data.body} /> </article> )}A message is applied only when it comes from the window framing the page, at a Studio origin. By default that is the origin of the provider’s client URL, since Studio is served at /studio/ on your API. If Studio is served somewhere else, or the page has no provider, pass studioOrigin with one URL or a list. Messages from any other origin are ignored with a console warning. model limits the hook to messages for one model.
This is the unsaved form state. To show the last saved draft instead, use useQuery with draft: true.
RichText
RichText renders a saved rich text field as React elements. Text is rendered as text, never as HTML, and links keep only a safe href. It works in Server Components and Client Components. Props are content, className, and as to choose the wrapper: div (the default), article, section, aside or main. A null content renders nothing.
Vue
Install the plugin with your client. The composables must be called inside setup.
import { createApp } from "vue"import { supatypePlugin } from "@supatype/vue"import { supatype } from "./supatype"import App from "./App.vue"
createApp(App).use(supatypePlugin, supatype).mount("#app")<script setup lang="ts">import { useQuery, useMutation } from "@supatype/vue"
const { data: posts, loading, refetch } = useQuery("post", { columns: "id, title", limit: 20 })const { mutate: removePost } = useMutation("post", "delete")
async function remove(id: string) { await removePost(undefined, { filter: { id } }) await refetch()}</script>
<template> <p v-if="loading">Loading</p> <ul v-else> <li v-for="post in posts" :key="post.id"> {{ post.title }} <button @click="remove(post.id)">Delete</button> </li> </ul></template>Results are refs. The query runs when the component mounts. To sort, page or filter from component state, pass the options as a ref or a getter, such as useQuery("post", () => ({ limit: 20, offset: page.value * 20 })); the query runs again whenever they change. enabled may be a ref; the query runs again when it turns true. useFunction(name) returns invoke(body), data, error and loading.
Svelte
Set the client once in a parent component. The create* functions read it from context, so call them during component setup, then read the stores with $.
<script lang="ts"> import { setSupatypeClient } from "@supatype/svelte" import { supatype } from "./supatype" import Posts from "./Posts.svelte"
setSupatypeClient(supatype)</script>
<Posts /><script lang="ts"> import { createQuery } from "@supatype/svelte"
const { data: posts, loading } = createQuery("post", { columns: "id, title", limit: 20 })</script>
{#if $loading} <p>Loading</p>{:else} <ul>{#each $posts ?? [] as post (post.id)}<li>{post.title}</li>{/each}</ul>{/if}createQuery fetches as soon as it is created and returns readable stores plus refetch. To sort, page or filter from component state, pass the options as a store; the query runs again whenever it changes. From $state, toStore(() => ({ limit: 20, offset: page * 20 })) from svelte/store makes one. createMutation and createFunction work like the Vue versions.
Solid
Provide the client with SupatypeContext.Provider. Results are accessors, so call them to read.
import { For, Show } from "solid-js"import { SupatypeContext, createQuery } from "@supatype/solid"import { supatype } from "./supatype"
function Posts() { const { data: posts, loading } = createQuery("post", { columns: "id, title", limit: 20 }) return ( <Show when={!loading()} fallback={<p>Loading</p>}> <ul><For each={posts() ?? []}>{(post) => <li>{post.title}</li>}</For></ul> </Show> )}
export function App() { return <SupatypeContext.Provider value={supatype}><Posts /></SupatypeContext.Provider>}The query runs on mount. To sort, page or filter from a signal, pass the options as a function, such as createQuery("post", () => ({ limit: 20, offset: page() * 20 })); the query runs again whenever the signals it reads change. createMutation and createFunction work like the Vue versions.
How Vue, Svelte and Solid differ from React
- The query option is
columns, notselect.refetchInterval,cacheanddraftare React only. mutate(data, { filter, select })takesfilterandselectas React’s does, but notpublish. Withoutselect,dataisnull.invoketakes a body only, so the call is always aPOST.signInandsignUptake(email, password)rather than an object,signInWithOAuth(provider)sends the browser to the provider, and there is aresetPassword(email).- There is no live preview hook or rich text component.
All four bindings run the query again when a different user signs in or out.
React Native
createNativeClient is createClient with session storage that survives app restarts. Pass expo-secure-store (recommended) or AsyncStorage; without either it throws. Use the EXPO_PUBLIC_ values supatype keys writes.
import * as SecureStore from "expo-secure-store"import * as Linking from "expo-linking"import { createNativeClient, createAuthUrlListener } from "@supatype/react-native"
export const supatype = createNativeClient({ url: process.env.EXPO_PUBLIC_SUPATYPE_URL!, anonKey: process.env.EXPO_PUBLIC_SUPATYPE_ANON_KEY!, secureStore: SecureStore,})
// Finish sign-ins that come back through a deep link, on cold and warm start.export const stopAuthLinks = createAuthUrlListener(supatype, { linking: Linking, pathIncludes: "auth/callback" })Wrap the app in SupatypeProvider from @supatype/react and use the same hooks as on the web. The native client does not read sessions from a URL by itself, which is why the listener is there.
openOAuth(client, { provider, redirectTo, webBrowser }) runs an OAuth sign-in in expo-web-browser with PKCE and returns the session, or cancelled: true when the user closes the browser. The ready-made native screens are on Auth: Pre-built UI.
Next.js
next build prerenders pages before any deployment’s values exist, so a Next.js app takes them when it runs instead. One route serves the browser client its address and anon key on each page load, from SUPATYPE_URL and SUPATYPE_ANON_KEY in the server’s environment, and the server client reads the same two variables. The same build then runs against whichever deployment it is started for. supatype init writes both pieces into an App Router app:
export { GET } from "@supatype/ssr/next"import Script from "next/script"
export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <Script src="/supatype-env.js" strategy="beforeInteractive" /> {children} </body> </html> )}The route needs no segment config, and must not export dynamic: Next 16 with cacheComponents on, as a new create-next-app has it, refuses that with a 500. GET reads the request, which is what makes Next 14 and Next 16 with cacheComponents render it per request instead of prerendering it with the build machine’s values; Next 15, and Next 16 without cacheComponents, render every GET per request anyway. A route written by init 0.9.1 has the line export const dynamic = "force-dynamic". supatype generate, which the project’s prepare script runs on every npm install, replaces that route with the current one while it is still as init wrote it, and prints updated; a route changed since is left alone, with a warning to delete the line. Upgrade @supatype/ssr with the CLI: the route needs 0.9.2 or later. The route answers window.__SUPATYPE_ENV__ = {"url":"...","anonKey":"..."}; with Cache-Control: no-cache, as the Supatype server’s own /supatype-env.js does. It answers 404 only when SUPATYPE_PUBLIC_ENV is false, and, when SUPATYPE_URL or SUPATYPE_ANON_KEY is unset or SUPATYPE_ANON_KEY holds a service role key, 200, not cached, with a script that sets only error to a reason naming every variable to fix, which the browser client throws on its first request. The browser client, created with NEXT_PUBLIC_SUPATYPE_URL and NEXT_PUBLIC_SUPATYPE_ANON_KEY left unset at build time, reads what the script set at its first request. How to set the two variables on each host is in Deploy your frontend: Next.js.
In a Pages Router app, init writes nothing and prints the steps instead: create the same route file under app/supatype-env.js/, beside pages/; in pages/_document.tsx, import Script from next/script and put the same <Script> tag inside <Head>; then add @supatype/ssr to the app’s dependencies. For a static export (output: "export" in next.config), which cannot serve a route, init writes neither piece and prints supatype build -- next build, or Supatype hosting, whose server answers /supatype-env.js itself.
The browser client
Create the browser client once, from the generated file, for client components to import. Pass it the two NEXT_PUBLIC_ names with no default. In next dev they come from .env.development.local. In a production build they are unset, so the client reads what /supatype-env.js set; a default would be fixed into the build and win over the route’s values.
import { createClient } from "../supatype/generated/client"
export const supatype = createClient({ url: process.env.NEXT_PUBLIC_SUPATYPE_URL, anonKey: process.env.NEXT_PUBLIC_SUPATYPE_ANON_KEY,})When the app is in src/app/, put it at src/lib/supatype.ts and import "../../supatype/generated/client". The root layout is a Server Component, so give the provider a client component of its own, and wrap {children} in the layout’s <body> with it, after the <Script> tag:
"use client"
import type { ReactNode } from "react"import { SupatypeProvider } from "@supatype/react"import { supatype } from "@/lib/supatype"
export function Providers({ children }: { children: ReactNode }) { return <SupatypeProvider client={supatype}>{children}</SupatypeProvider>}"use client"
import { useQuery } from "@supatype/react"
export function PostList() { const { data: posts, loading, error } = useQuery("post", { select: "id, title", limit: 20 }) if (loading) return <p>Loading</p> if (error) return <p>{error.message}</p> return <ul>{posts?.map((post) => <li key={post.id}>{post.title}</li>)}</ul>}Every hook in the React section works the same way in a client component. The session it signs in is the one the server client below reads from the cookie.
Server components, route handlers and middleware
In the browser the client copies the session into a cookie named st-auth-token (path /, SameSite=Lax, Secure on HTTPS). createServerClient from @supatype/ssr reads that cookie on the server and builds a client signed in as the same user. Given only its options, it takes the address and anon key from SUPATYPE_URL and SUPATYPE_ANON_KEY, read on each call, and where one is unset, from NEXT_PUBLIC_SUPATYPE_URL or NEXT_PUBLIC_SUPATYPE_ANON_KEY. With neither, its first request throws an error saying it is running on a server and naming SUPATYPE_URL and SUPATYPE_ANON_KEY. Pass them first, as createServerClient(url, anonKey, options), to use others.
Put the helper in the folder that holds app/: supatype-server.ts at the project root for a create-next-app made without src/, or src/supatype-server.ts when the app is in src/app/. create-next-app points the @/* import alias at that folder, so @/supatype-server finds it in both layouts.
import { cookies } from "next/headers"import { connection } from "next/server"import { createServerClient } from "@supatype/ssr"
// Server Components: no setAll, so the client never refreshes the session.export async function serverClient() { const store = await cookies() // Render at request time: the client reads the clock to check the session's expiry. await connection() return createServerClient({ cookies: { getAll: () => store.getAll() } })}
// Route Handlers and Server Actions: a refreshed session goes back to the browser.export async function writableServerClient() { const store = await cookies() return createServerClient({ cookies: { getAll: () => store.getAll(), setAll: (cookiesToSet) => cookiesToSet.forEach(({ name, value, options }) => store.set(name, value, options ?? {})), }, })}import { RichText } from "@supatype/react"import { serverClient } from "@/supatype-server"
export default async function Page() { const supatype = await serverClient() const { data: posts } = await supatype.from("post").select("id, title, body") return posts?.map((post) => <RichText key={post.id} content={post.body} as="article" />)}A Route Handler uses writableServerClient() the same way. Middleware can write cookies, so refresh the session there, before the page renders, and check the user with the auth server:
import { NextResponse, type NextRequest } from "next/server"import { createServerClient } from "@supatype/ssr"
export async function middleware(request: NextRequest) { const response = NextResponse.next() const supatype = createServerClient({ cookies: { getAll: () => request.cookies.getAll(), setAll: (cookiesToSet) => cookiesToSet.forEach(({ name, value, options }) => response.cookies.set(name, value, options ?? {})), }, }) const { data } = await supatype.auth.getUser() if (!data.user) return NextResponse.redirect(new URL("/sign-in", request.url)) return response}
export const config = { matcher: ["/account/:path*"] }What the cookie handling does and does not do:
- Without
setAll, as in a Server Component, the client never refreshes the session: an expired access token is sent as it is, and the API refuses it. A refresh there would spend the browser’s refresh token and keep the new one to itself, so the browser’s own next refresh would be refused. Do not pass asetAllthat does nothing to get round this. - With
setAll, the client refreshes an expired access token when a request it makes finds it expired, and writes every change to the session (a refresh, a sign-in, a sign-out) back throughsetAll. - A cookie whose access token has expired is kept only when it has a refresh token. Otherwise the server client runs as an anonymous caller.
- Telling whether it has expired reads the clock, so
serverClient()awaitsconnection()fromnext/serverfirst, which renders the component at request time. Without it, Next 16 withcacheComponentslogsNext.js encountered the unstable value Date.now() while prerenderingfor every page that uses it.connection()is in Next 15 and later; on Next 14 leave that line out. - The cookie is decoded, not verified. Queries made with it are checked by the API, so access rules hold. But do not trust
auth.getSession()on the server to decide who someone is: callauth.getUser(), which asks the auth server, as the middleware above does. - Decoding uses
atobandTextDecoder, not Node’sBuffer, so it works on the edge runtime too. - Set
cookiePrefixon both sides if you change the client’sauth.cookiePrefix. The default isst. - The server client is built from
@supatype/client, not your generated client file, soupdate(..., { publish: true })is not accepted on it.
In development, supatype dev, init and keys --write write a local stack’s SUPATYPE_URL and SUPATYPE_ANON_KEY, with the NEXT_PUBLIC_ copies, to .env.development.local, which Next.js reads in development only, so the route answers in next dev. A value fixed into the build that way always wins over the route’s.