Composables
All composables are auto-imported and return a typed PostgrestClient.
usePostgrest(options?)
For components, pages and plugins. Works on the client and during SSR.
const postgrest = usePostgrest()
const { data, error } = await postgrest.from('todos').select('id, title')
The token is resolved in this order:
options.token, if you pass one- The session token, if
nuxt-auth-utilsis installed - The public anon
key - No
Authorizationheader (PostgREST'sdb-anon-role)
| Option | Type | Description |
|---|---|---|
token | string | Explicit JWT. Wins over everything else. |
headers | Record<string, string> | Extra headers for every request. |
Wrap queries in useAsyncData so SSR results are transferred to the client instead of refetched:
const { data } = await useAsyncData('todos', async () => {
const { data, error } = await usePostgrest().from('todos').select('*')
if (error) throw error
return data
})
usePostgrestUser(event, options?)
For Nitro server routes. Acts as the requesting user, so RLS applies. Token resolution matches usePostgrest(), except the session lookup also reads server-only secure session data.
export default defineEventHandler(async (event) => {
const postgrest = await usePostgrestUser(event)
const { data, error } = await postgrest.from('todos').select('*')
if (error) throw createError({ statusCode: 500, message: error.message })
return data
})
It is async because reading the session is. Options are the same as usePostgrest().
usePostgrestAdmin()
For Nitro server routes that need privileged access: background jobs, webhooks, admin tools. Uses NUXT_POSTGREST_SECRET_KEY and is created once per server process.
export default defineEventHandler(async () => {
const { data } = await usePostgrestAdmin().from('todos').select('*')
return data
})
createPostgrestClient(options)
Build a client with explicit connection details. Available in app and server code. Use it for multi-tenant setups, other PostgREST instances or other schemas.
const tenant = createPostgrestClient({
url: `https://${tenantId}.api.example.com`,
key: tenantJwt,
})
| Option | Type | Description |
|---|---|---|
url | string | PostgREST URL. Required. |
key | string | JWT sent as Authorization: Bearer. Omit for anon. |
schema | string | Postgres schema to target. |
headers | Record<string, string> | Extra headers. Can override Authorization. |
fetch | typeof fetch | Custom fetch implementation. |
timeout | number | Request timeout in milliseconds. |
It's typed with your Database by default. Pass generics to change the database or schema:
const internal = createPostgrestClient<Database, 'internal'>({ url, key, schema: 'internal' })