Generate TypeScript types from your database
One command turns your tables into types. Your editor then rejects a wrong column or a wrong value before you run anything.
Your tables, views, functions and enums become one TypeScript type, Database. Passed to createClient, it lets the compiler reject a wrong table, column or value before you run anything.
Prerequisites#
-
A linked project:
aura link <project-id>. -
The example schema, installed with the service role key of the project:
export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docsIt creates
profiles,orgs,org_members,posts,todos, the viewopen_todosand the functiontodo_count(p_user uuid). See Example schema. -
Node.js 20 or later for
@aurabase/gen.
Reading the schema requires the service_role key: run the generators on your machine or in CI, never in a browser. The examples write types.ts, models.rs and src/types/; the Clean up block removes them.
Generate the file#
@aurabase/gen is the generator to use in an application. With version 0.7.5, create the output folder first: the published package does not create it and fails with ENOENT: no such file or directory.
mkdir -p src/types
npx @aurabase/gen --url "$NEXT_PUBLIC_AURABASE_URL" --key "$AURABASE_SERVICE_ROLE_KEY" --out src/types/database.types.tsOn the example schema it prints (measured with @aurabase/gen 0.7.5, not replayed by this page):
[aurabase-gen] ✓ Types written to src/types/database.types.ts (5 table(s), 1 function(s), 0 enum(s), 1 view(s)).Run it again whenever the schema changes, for example after each aura db push.
Options#
| Option | Environment variable | Default | Effect |
|---|---|---|---|
--url <url> | NEXT_PUBLIC_AURABASE_URL | URL of the project | |
--key <key> | AURABASE_SERVICE_ROLE_KEY | service_role key. An aura_anon_ or aura_auth_ key is refused before any request. | |
-o, --out <file> | AURABASE_TYPES_OUT | Standard output | File to write |
-s, --schema <name> | AURABASE_SCHEMA | public | Name of the schema key inside Database (Database['public']) |
-t, --type-name <name> | Database | Name of the main type | |
--numeric-as-string | Off | numeric and decimal become string instead of number, to keep their precision | |
--allow-empty | Off | Write the file even if a table has no column (a MongoDB project); without it, the command fails | |
--check | Off | Compare with the --out file instead of writing it (Check the types in CI) | |
-h, --help, -v, --version | Help and version |
Without --url and --key, the variables are read from the environment, then from .env.local, .env.development.local, .env.development and .env in the current folder, in this order; a variable already set wins.
With the CLI or the API#
aura db generate asks the project for its types (GET /v1/db/{project_id}/types.ts) and writes them to types.ts in the current folder:
aura db generate > /dev/null
sed -n '/^ todos: {/,/^ Relationships/p' types.ts todos: {
Row: {
id: number;
user_id: string;
title: string;
done: boolean;
created_at: string;
};
Insert: {
id?: number;
user_id: string;
title: string;
done?: boolean;
created_at?: string;
};
Update: {
id?: number;
user_id?: string;
title?: string;
done?: boolean;
created_at?: string;
};
Relationships: [];The route can be called directly with the service_role key; the anon key is refused:
curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/types.ts" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" | grep -c '^export'
curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/types.ts" -H "apikey: $AURABASE_ANON_KEY" | node -pe 'JSON.parse(require("fs").readFileSync(0, "utf8")).error.message'26
Forbidden: DDL operation is reserved to the service_role roleaura db generate --lang rust writes models.rs, one struct per table, from the same schema; nullable columns become Option<…> and enums become Rust enums:
aura db generate --lang rust > /dev/null
sed -n '/^pub struct Todos/,/^}/p' models.rspub struct Todos {
pub id: i64,
pub user_id: String,
pub title: String,
pub done: bool,
pub created_at: String,
}@aurabase/gen | aura db generate | |
|---|---|---|
| Output | The file you choose, or standard output | types.ts in the current folder |
Database type | Same tables, views, functions and enums | Same |
| Helpers | Tables, TablesInsert, TablesUpdate, Enums | Tables, TablesInsert, TablesUpdate, an interface per table (Todos, TodosInsert…), TableName |
| Options | All the options above | --lang ts (default) or rust |
| Drift check | --check | None |
Without a linked project, aura db generate reads the database of DATABASE_URL with a simpler generator (Local development). aura db watch regenerates types.ts after each push (Push, pull, diff and watch).
What the file contains#
Part of Database['public'] | From | Contents |
|---|---|---|
Tables | Each table | Row (a read row), Insert (optional when the column has a default, is nullable or is an identity), Update (all optional), Relationships (foreign keys) |
Views | Each view | Row only, every column nullable |
Functions | Each function | Args (argument names and types) and Returns; a returns table (…) function gives an array of rows |
Enums | Each enum type | The union of its values, such as 'todo' | 'doing' | 'done' |
CompositeTypes | Always empty |
Types follow the JSON the API returns: integers and float give number, numeric gives number (or string with --numeric-as-string), uuid, dates and timestamps give string, json and jsonb give Json, arrays give arrays, bigint gives number.
Use it with the client#
Excerpt of src/lib/aurabase.ts:
import { createClient } from '@aurabase/aurabase-js'
import type { Database } from '../types/database.types'
export const aura = createClient<Database>(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!)Row types for your components#
import type { Tables, TablesInsert, TablesUpdate, Enums } from '../types/database.types'
type Todo = Tables<'todos'> // a row, as read
type NewTodo = TablesInsert<'todos'> // what insert() accepts
type TodoPatch = TablesUpdate<'todos'> // what update() acceptsTables<'open_todos'> gives the row of a view, and Enums<'name'> the values of an enum.
What is checked#
Checked with TypeScript 5.9.3, @aurabase/aurabase-js 0.7.5 and a file generated from the example schema (not replayed by this page):
const { data } = await aura.from('todos').select('id, title, done')
const title: string | undefined = data?.[0]?.title // ok
const wrong: number | undefined = data?.[0]?.title // error: string is not assignable to number
await aura.from('todos').insert({ title: 1 }) // error: number is not assignable to string
await aura.from('todos').insert({ title: 'ok', user_id: userId }) // ok: the other columns have defaults
await aura.from('todos').update({ done: 'yes' }) // error: string is not assignable to boolean
await aura.from('todos').select('id').eq('done', 'no') // error: string is not assignable to boolean
await aura.from('anything').select('id') // error: no overload matches this call
await aura.from('open_todos').insert({ title: 'x' }) // error: a view has no Insert type
const typo = await aura.from('todos').select('id, titel')
typo.data?.[0]?.id // error: column 'titel' does not exist on 'todos'- Tables and views. A name that is not in the file is rejected. A view can be read, not written.
- Columns in
select('…'). The string is parsed: a misspelled column turns the row type into an error that names the column, as soon as you use the row. - Values.
insert(),update()and filters such aseq()are checked against the column types. InInsert, a column without a default that is not nullable is required:todos.user_idhere. - Relationships. An embed such as
select('role, orgs(name)')is typed fromRelationships. - Functions.
aura.rpc()does not use theFunctionspart of the file: its arguments are not checked and itsdataisunknown. Type the result yourself. - Freshness. The file describes the schema at the time you generated it: regenerate it after each migration, and check it in CI.
Check the types in CI#
--check regenerates the file in memory and compares it with --out. It exits with 0 and [aurabase-gen] ✓ src/types/database.types.ts is up to date. when they match, and with 1 and [aurabase-gen] Types in src/types/database.types.ts are out of date. Re-run aurabase-gen without --check. when the schema changed and the committed file was not regenerated. Excerpt of a CI step (not replayed here):
- run: npx @aurabase/[email protected] --check --out src/types/database.types.ts
env:
NEXT_PUBLIC_AURABASE_URL: ${{ vars.PROJECT_URL }}
AURABASE_SERVICE_ROLE_KEY: ${{ secrets.SERVICE_ROLE_KEY }}Run it after aura db push in the same job, so that the types are compared with the migrated schema.
Common errors#
| Message | Cause | Fix |
|---|---|---|
[aurabase-gen] ENOENT: no such file or directory, open '…' | The folder of --out does not exist (@aurabase/gen 0.7.5). | mkdir -p the folder first. |
[aurabase-gen] Error: the project URL and/or service_role key is missing. | Neither the options nor the variables are set. | Pass --url and --key, or set the variables. |
[aurabase-gen] Error: schema introspection requires a service_role key (aura_sk_...), not an anon/auth key. | An anon or authenticated key was passed. | Use the service_role key. |
[aurabase-gen] Types in … are out of date. Re-run aurabase-gen without --check. | The schema changed since the file was generated. | Regenerate and commit the file. |
[aurabase-gen] Tables without any column: … Use --allow-empty to generate anyway. | A MongoDB project, whose collections have no declared columns. | Add --allow-empty, knowing these types check nothing. |
API failed to generate types (403 Forbidden): … | aura db generate with a key that is not service_role. | Export the service_role key. |
Clean up#
rm -f types.ts models.rs
rm -rf src/types