コンテンツへスキップ
オーラベースのロゴ
オーラベース

Connect to your database

Find your project URL and keys, choose between the SDK, the REST API and a direct PostgreSQL connection, and get a working connection string for psql or an ORM.

ハウツーガイド11 分 読み取りレベル 初心者

このページはまだお使いの言語では利用できません。英語で表示されます。

Every project can be reached three ways: the JavaScript SDK, the REST API it calls, and a direct PostgreSQL connection for tools that speak the PostgreSQL protocol. This page tells you which one to use and how to set each up.

Choose a connection#

Where your code runsUseWhy
Browser, mobile appSDK with the anon keyHTTPS only, no database password to ship. Row level security decides what each user sees.
Serverless function, edge runtimeSDK or REST, anon key with the user's token, or the service_role keyEach call is an HTTP request: no connection to open, keep or pool on your side.
Long-running backend (API server, worker)SDK or REST; direct connection if you need an ORM or SQL features the REST API does not offerThe direct connection gives you plain PostgreSQL, with your own pool.
Schema changes from a terminal or CIaura db raw, or SQL migrations with aura db migrationRuns as the project administrator role; RLS is enabled on every table it creates.
psql, a BI tool, a database GUIDirect connectionStandard PostgreSQL protocol over TLS.
Export (schema and rows)Direct connection with a PostgreSQL 18 pg_dumpSee Export with pg_dump: dump as the administrator role of the project.

The direct connection exists only where the deployment publishes the PostgreSQL port (5432). When it does not, aura db connection says so: This deployment does not publish direct PostgreSQL access (port 5432). Use the SDK, the REST API, the Studio SQL editor, or aura db raw.

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 docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See Example schema.

  • For the direct connection: psql (any recent version connects; pg_dump must be version 18).

Project URL and keys#

The SDK and the REST API need two values, printed by aura projects create and shown in the Studio under Settings › Connection and Settings › API keys:

ValueExampleWhere it goes
Project URLhttp://my-app-utsrqfcx.localhost:8080 on a local stackcreateClient(url, key), base URL of every REST call
anon keyaura_anon_…Public. Browser and mobile code. Reaches PostgreSQL as the role aura_anon, or aura_authenticated with a signed-in user.
service_role keyaura_sk_…Secret. Servers, CI, the CLI. Bypasses row level security. Refused from a browser (401 SECRET_KEY_IN_BROWSER).

The initial keys are shown once, when the project is created. List them, create others or revoke one with aura db api-keys list, aura db api-keys create <name> --scope anon|authenticated|service_role and aura db api-keys revoke <id>. The roles and keys page explains what each key becomes inside PostgreSQL.

Connect with the SDK#

Install @aurabase/aurabase-js and create a client with the project URL and a key. The URL is enough to target the project: there is no project id to pass.

import { createClient } from '@aurabase/aurabase-js'

// In a browser: the anon key. Row level security filters the rows.
const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const visitor = await aura.from('todos').select('title')
console.log('anon:', visitor.data, visitor.error)

// On a server only: the service_role key, which bypasses row level security.
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const all = await admin.from('todos').select('title').eq('done', false).order('title')
console.log('service_role:', all.data, all.error)
anon: [] null
service_role: [
  { title: 'Add a row level security policy' },
  { title: 'Create a table' },
  { title: 'Invite a teammate' }
] null

The anon key gets an empty list, not an error: todos has an owner policy and no user is signed in. Sign a user in with aura.auth.signInWithPassword() and the same client returns that user's rows, as in the Quickstart.

Connect over REST#

Any HTTP client works. Send the key in the apikey header (or X-API-Key); for a signed-in user, add Authorization: Bearer <access token>. Filters use the column=operator.value form.

curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/todos?select=title&done=eq.false&order=title.asc" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY"
{"data":[{"title":"Add a row level security policy"},
 {"title":"Create a table"},
 {"title":"Invite a teammate"}],"meta":{}}

A read returns at most 1,000 rows, whatever limit you ask for. The full list of endpoints is in the REST API reference.

Connect with psql or an ORM#

Each project has its own PostgreSQL login role, proj_ followed by eight hexadecimal characters, and a host of the form <project-slug>.db.<domain> on port 5432. Show them with:

aura db connection

Output (your host, database and role differ):

» Direct PostgreSQL access
  • host      my-app-utsrqfcx.db.localhost
  • port      5432
  • database  project_41fd6f07_3acf_48cf_9eb5_d665ce99a849
  • user      proj_76c0d308
  • psql "postgresql://proj_76c0d308@my-app-utsrqfcx.db.localhost:5432/project_41fd6f07_3acf_48cf_9eb5_d665ce99a849?sslmode=require"
  ℹ The password is shown only when issued: aura db connection --new-password (this revokes the current one).
  • TLS is required. Connections go through a transaction pooler: use ?pgbouncer=true with Prisma, and session-level features (LISTEN, advisory locks) do not persist across transactions.

The password is issued on demand and shown once: the platform does not keep it in clear, so a lost password is replaced, never recovered. --new-password issues one, prints the full connection string, and revokes the previous password (it asks for confirmation unless you pass --yes). --json prints host, port, database, user, password and connection_uri.

Issue a password, keep the connection string in a file that your ORM or scripts load, and run a first query:

aura db connection --new-password --yes --json \
  | node -pe '"export DATABASE_URL=\x27" + JSON.parse(require("fs").readFileSync(0, "utf8")).connection_uri + "\x27"' > .env.database
source .env.database
psql "$DATABASE_URL" -X -A -t -c "select current_database() = current_schema() as same_name, current_setting('server_version_num')::int / 10000 as major"
t|18

The database and the schema of the project share the same name, and the server is PostgreSQL 18. Keep .env.database out of version control.

  • psql, interactively. aura connect opens psql on the linked project and lets psql ask for the password. If DATABASE_URL is set in your environment, aura connect uses it instead.
  • Prisma. Put the connection string in DATABASE_URL and add &pgbouncer=true to it. Prisma documents this flag, for Prisma ORM 6 and 7, for a PgBouncer pooler in transaction mode that does not track prepared statements.
  • Other clients (node-postgres, Drizzle, SQLx, DBeaver, Metabase): the same connection string, with TLS on (sslmode=require).

Rules of the direct connection#

  • TLS is required. A plaintext connection is refused: FATAL: TLS required: this endpoint does not accept plaintext connections (use sslmode=require).
  • sslmode=verify-full fails on a local stack, by design. The local certificate is self-signed for *.db.localhost, so a client that verifies the chain stops with a message about the missing root certificate (~/.postgresql/root.crt). In production the certificate is issued for *.db.<your-domain>: if it chains to a public authority, sslmode=verify-full&sslrootcert=system checks it against the trust store of the system (PostgreSQL 18 documentation, sslrootcert).
  • Confined to your project. The router reads the role name, picks your project's database and forces it, whatever database name you ask for. Presenting your role on another project's host is refused: FATAL: the requested host does not match this user's project.
  • Transaction pooler on Free and Pro. On the cluster of your organization the connection goes through PgBouncer in transaction mode: session state does not survive from one transaction to the next. Use SET LOCAL inside a transaction, and do not rely on LISTEN, session-level advisory locks or named prepared statements. Run long schema migrations with aura db migration or aura db raw rather than an ORM migration tool, which expects a session connection that this endpoint does not offer. On a dedicated cluster (Team and Enterprise), the connection goes straight to the primary, without the pooler.
  • Not a superuser, no RLS bypass. The proj_ role reads and writes the tables of your schema, under their row level security policies. It may switch, inside a transaction, to the administrator role of the project, the role aura db raw runs as: BEGIN; SET LOCAL ROLE tenant_<project-id>_admin; …; COMMIT;, where <project-id> is the project id with underscores instead of dashes. That role owns the tables and bypasses row level security.
  • A table created as the administrator role is public until you enable RLS. The administrator role grants every new table to the public roles, and the hook that enables row level security runs only for SQL sent through Aurabase (aura db raw, migrations, the Studio, the table API), not over this connection. Enable RLS in the same transaction as the CREATE TABLE: alter table <name> enable row level security;.

Tables created over the direct connection#

A table created by the proj_ role does not go through the hook that enables row level security on tables created by Aurabase. The platform closes it instead: the public roles get no privilege on it. The anon key and signed-in users receive permission denied, while the service_role key, the Studio and your own role read and write it.

source .env.database
psql "$DATABASE_URL" -X -q \
  -c "create table direct_notes (id int primary key, body text)" \
  -c "insert into direct_notes values (1, 'written over psql')" \
  -c "notify pgrst, 'reload schema'"
sleep 3
curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/direct_notes?select=body" -H "apikey: $AURABASE_ANON_KEY"; echo
curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/direct_notes?select=body" -H "apikey: $AURABASE_SERVICE_ROLE_KEY"; echo
{"error":{"code":"INSUFFICIENT_PRIVILEGE","details":"","message":"permission denied for table direct_notes","request_id":"b58072c9-ec71-4e42-abbf-b9955072cd00","type":"auth_forbidden","upstream_code":"42501"}}
{"data":[{"body":"written over psql"}],"meta":{}}

notify pgrst, 'reload schema' tells the REST API about the new table; without it, the next call answers TABLE_NOT_FOUND for a few seconds. To expose such a table to the SDK, turn row level security on first, then grant and add a policy. Never grant a public role on a table whose RLS is off: every holder of the anon key would read it.

alter table direct_notes enable row level security;
grant select on direct_notes to aura_authenticated;
create policy direct_notes_read on direct_notes for select to aura_authenticated using (true);

Export with pg_dump#

pg_dump refuses a server newer than itself. With an older client you get:

pg_dump: error: aborting because of server version mismatch
pg_dump: detail: server version: 18.7 (Debian 18.7-1.pgdg12+2); pg_dump version: 16.15 (Homebrew)

Use a PostgreSQL 18 client and limit the dump to your schema with --schema: the database also holds the internal schemas of the platform (auth, storage), which the project role cannot lock, and a plain pg_dump stops on them with permission denied.

The proj_ role does not bypass row level security: a dump of a table that has RLS on stops with query would be affected by row-level security policy. Dump as the administrator role of the project with --role; it owns the tables and reads every row. The schema, the database and the role all derive from the project id, with underscores instead of dashes:

pg_dump --no-owner \
  --role=tenant_41fd6f07_3acf_48cf_9eb5_d665ce99a849_admin \
  --schema=project_41fd6f07_3acf_48cf_9eb5_d665ce99a849 \
  "$DATABASE_URL" > my-project.sql

The file holds the tables, views, functions, policies and rows of your schema. Add --schema-only for the structure alone.

Result#

One question, how many rows todos holds, asked through three doors. The REST API with the service_role key and aura db raw bypass row level security and count every row; the proj_ role of the direct connection does not, and the owner policy of todos shows it no row because it carries no user id:

source .env.database
curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/todos?select=id" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  | node -pe 'JSON.parse(require("fs").readFileSync(0, "utf8")).data.length'
aura db raw --json "select count(*)::int as todos from todos"
psql "$DATABASE_URL" -X -A -t -c "select count(*) as todos from todos"
4
[
  {
    "todos": 4
  }
]
0

Common errors#

MessageCauseFix
FATAL: TLS required: this endpoint does not accept plaintext connections (use sslmode=require)sslmode=disable, or a client without TLS.Keep sslmode=require in the connection string.
root certificate file "…/.postgresql/root.crt" does not existsslmode=verify-full or verify-ca against the self-signed certificate of a local stack.Use sslmode=require locally.
FATAL: the requested host does not match this user's projectThe role of one project presented on the host of another.Take host and role from the same aura db connection output.
FATAL: SASL authentication failedThe password was replaced by a later --new-password, from the CLI or the Studio.Issue a new one and update every client that uses it.
aborting because of server version mismatchpg_dump older than 18.Install a PostgreSQL 18 client.
permission denied for table … (403 INSUFFICIENT_PRIVILEGE over the SDK)The table was created over the direct connection.Enable RLS, grant, add a policy (see above).

Clean up#

Drop the table created over the direct connection and delete the file that holds the password:

source .env.database
psql "$DATABASE_URL" -X -q -c "drop table if exists direct_notes"
rm .env.database

The password stays valid until you issue a new one with aura db connection --new-password.

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ 問題を報告する