跳到内容
光环标志
光环基地

快速启动

从零到可查询的 API:专用 Postgres 数据库、行级安全性、实时和 TypeScript 类型生成 - 无需信用卡。

教程5分钟 读取级别 初学者修改于 2026年10月21日

该页面已自动翻译。英文版具有权威性。

给您的编码代理的提示词

Set up Aurabase in this app by following this page: https://aurabase.cloud/en/docs/getting-started.md

Documentation: read https://aurabase.cloud/llms.txt first. Every docs page is also available as Markdown: add .md to its URL, for example (the same works for every page): https://aurabase.cloud/en/docs/getting-started.md

Client: install @aurabase/aurabase-js and create the client with createClient(NEXT_PUBLIC_AURABASE_URL, NEXT_PUBLIC_AURABASE_ANON_KEY). Keep AURABASE_SERVICE_ROLE_KEY on the server: never put it in client code.

Project access: to read the schema and run SQL, start the Aurabase MCP server over stdio (82 tools with a project key):
npx -y -p @aurabase/mcp-server aurabase-mcp --url https://<slug>.aurabase.cloud --project-id <project-id> --service-role-key aura_sk_…
The project id is in Studio › Settings › General. The service role key is shown once when the project is created; regenerate it in Studio › Settings › Connection if you lost it.

快速入门#

安装 SDK、创建客户端并读取第一行。

1.安装SDK#

将 SDK 添加到您的项目中。 Rust 选项卡安装 aurabase 包; cURL 选项卡检查您的项目 URL 是否响应。

bash
pnpm add @aurabase/aurabase-js

2. 创建客户端#

使用您的项目 URL 和匿名密钥创建客户端,两者都在 Studio › 设置 › 连接中。将服务角色密钥保留在服务器上。

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

const aura = createClient(
  process.env.NEXT_PUBLIC_AURABASE_URL!,
  process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!,
)

3、查询数据库#

从 todos读取最多 10 行。该表是在下面的“创建表”部分中创建的;直到它存在为止,error 被设置。

typescript
// `todos` 在下面的“创建表”中创建
const { data, error } = await aura
  .from('todos')
  .select('id, title, done')
  .limit(10)

console.log(data, error)

先决条件#

我们假设已安装 Node.js ≥ 20 并且 POSIX 终端在范围内。不需要本地数据库:Aurabase 为每个项目提供专用的 Postgres 数据库。

信息

您来自 Supabase 或 Firebase吗?大多数概念都是可移植的。请参阅 迁移指南。

安装SDK#

官方 SDK 公开了一个用于 CRUD、身份验证、实时和存储的类型化客户端。它在 Next.js、React、Node、Bun 或 Deno中的工作方式相同。

terminalbash
# 推荐
pnpm add @aurabase/aurabase-js

包名称包含 @aurabase/ 范围。没有范围的包 aurabase-js 不是由 Aurabase维护的:不要安装它。

提示

SDK 直接包括 Next.js(应用程序路由器、服务器操作、中间件)、Remix、Nuxt 和 SvelteKit 的 @aurabase/aurabase-js/ssr (createServerClient) 导出,具有自动会话 cookie 管理和防截断分块功能。

创建一个项目#

从 Studio 创建一个项目。当它变为活动状态时,Studio 会显示“立即复制密钥”面板,其中包含随时可用的 .env.local(复制或下载它):service_role 密钥出现一次,之后仅保留其哈希值。设置 › 连接稍后会显示项目 URL 和公共匿名密钥;如果您丢失了 service_role 密钥,请在那里重新生成它(前一个已被撤销)。 NEXT_PUBLIC_AURABASE_URL 和 NEXT_PUBLIC_AURABASE_ANON_KEY 可以在客户端发布; AURABASE_SERVICE_ROLE_KEY 严格保留在服务器端。

.env.localbash
NEXT_PUBLIC_AURABASE_URL=https://<slug>.aurabase.cloud
NEXT_PUBLIC_AURABASE_ANON_KEY=aura_anon_…
AURABASE_SERVICE_ROLE_KEY=aura_sk_…
模式访问包含
project_{uuid}你您的申请表
project_{uuid}_auth系统users、 sessions、 oauth_accounts、 mfa
project_{uuid}_storage系统buckets、 objects、 rls_policies
project_{uuid}_platform系统functions、 jobs、 cron_jobs、 api_keys
更喜欢终端?

整个路径也可以从 CLI 运行(有关安装,请参阅 CLI): aura projects create 等待项目准备就绪并打印一次 URL 和密钥。

terminalbash
aura login
aura projects create todos-app --json > project.json    # 等待项目激活
aura link --project-id "$(jq -r .id project.json)"
export NEXT_PUBLIC_AURABASE_URL="$(jq -r .url project.json)"
export AURABASE_SERVICE_ROLE_KEY="$(jq -r .service_role_key project.json)"
aura db raw "create table todos (id bigint generated always as identity primary key, title text not null, done boolean not null default false, user_id uuid not null default auth.uid(), created_at timestamptz not null default now())"
aura db raw "create policy todos_own_read on todos for select to aura_authenticated using (auth.uid() = user_id)"
aura db raw "create policy todos_own_insert on todos for insert to aura_authenticated with check (auth.uid() = user_id)"
aura db table realtime todos on
aura db raw "select count(*) from todos" --as authenticated --user <a user id>   # 看看该用户看到了什么
服务角色键

切勿在客户端捆绑包中包含 AURABASE_SERVICE_ROLE_KEY。 它绕过所有 RLS 策略,并且 API 从浏览器中拒绝它 (401 SECRET_KEY_IN_BROWSER)。保留它用于服务器调用(路由处理程序、服务器操作、作业)。

创建一个表#

在 Studio 中打开 数据库,单击 SQL 编辑器(表面板底部的链接)并运行此脚本。每个表都启用行级安全性:前两个策略允许每个登录用户读取和创建自己的行,第三个策略是 示例,允许访问者读取表,以便您无需登录即可看到第一行。策略针对 aura_authenticated 角色(访问者为aura_anon)。

todos.sqlsql
create table todos (
  id bigint generated always as identity primary key,
  title text not null,
  done boolean not null default false,
  user_id uuid not null default auth.uid(),
  created_at timestamptz not null default now()
);
create policy "todos_own_read" on todos for select to aura_authenticated using (auth.uid() = user_id);
create policy "todos_own_insert" on todos for insert to aura_authenticated with check (auth.uid() = user_id);
-- 仅作为示例:任何访问者都可以阅读每个待办事项。在生产前删除它:
--   在 todos 上删除策略“todos_public_read”;
create policy "todos_public_read" on todos for select to aura_anon using (true);

然后生成模式的 TypeScript 类型(命令读取 .env.local):

terminalbash
npx @aurabase/gen --out lib/aurabase.types.ts

第一次通话#

通过从环境变量中读取键来创建可重用的 Aurabase 客户端,然后查询您的第一个表。以下路径相对于应用程序的根目录:如果您的项目使用 src/ 目录,请将 lib/、 components/ 和 app/ 放入其中,以便解析 @/ 导入别名。

lib/aurabase.tstypescript
import { createClient } from '@aurabase/aurabase-js'
import type { Database } from './aurabase.types'

export const aura = createClient<Database>(
  process.env.NEXT_PUBLIC_AURABASE_URL!,
  process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!,
)

然后,在路由处理程序或服务器组件中:

app/api/todos/route.tstypescript
import { aura } from '@/lib/aurabase'

export async function GET() {
  const { data, error } = await aura
    .from('todos')
    .select('id, title, done')
    .order('created_at', { ascending: false })
    .limit(10)

  if (error) throw error
  return Response.json(data)
}
提示

由于示例策略 todos_public_read,这将返回表的行,包括没有登录用户的行。如果没有它(一旦您删除它,就像在生产之前一样),访问者将获得 []:其他策略仅打开 aura_authenticated的行,因此首先使用 aura.auth.signInWithPassword({ email, password }) 登录用户(请参阅 Next.js 的现成登录页面)。每次架构更改后,使用 npx @aurabase/gen 重新生成 Database 类型。

要插入第一行,请注册用户并登录,然后插入。 user_id 列默认为 auth.uid():

scripts/first-row.tstypescript
import { aura } from '../lib/aurabase'

async function main() {
  const email = 'you@example.com'
  const password = 'a-strong-password'

  await aura.auth.signUp({ email, password })
  await aura.auth.signInWithPassword({ email, password })

  const { data, error } = await aura.from('todos').insert({ title: 'First todo' }).select()
  console.log(data, error)
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})

使用 tsx运行它,这会解析无扩展导入并读取 .env.local:

terminalbash
pnpm add -D tsx
pnpm approve-builds   # pnpm 10+:允许 esbuild 的安装脚本,然后运行:
pnpm exec tsx --env-file=.env.local scripts/first-row.ts
npm 11 阻止 esbuild 的安装脚本

对于 npm 11 或更高版本,npx tsx 会失败并显示“您为另一个平台安装了 esbuild”,因为 esbuild 的安装脚本默认被阻止。如上所述使用 pnpm,或跳过 tsx 并在使用扩展名('../lib/aurabase.ts'、 './aurabase.types.ts')编写两个导入后使用 Node 的内置类型剥离(Node 22.6+)运行脚本: node --env-file=.env.local --experimental-strip-types scripts/first-row.ts。

电子邮件确认默认关闭

对于项目的用户,signUp 后跟 signInWithPassword 会立即生效:电子邮件确认是 关闭,直到您在 Studio › 身份验证 › 配置中将其打开(需要邮件服务器)。然后任何人都可以使用任何地址进行注册,因此在生产之前将其打开。

注意

service_role 密钥没有登录用户,因此 auth.uid() 是 NULL ,并且依赖于默认值的插入失败并显示 NOT_NULL_VIOLATION。从服务器显式传递 user_id。

实时连接#

三种自动协商传输:WebSocket、SSE、NATS。客户根据网络选择最好的一种 - 无需配置。

使用 CLI 在表上启用一次实时:

terminalbash
aura db table realtime todos on

或使用 HTTP API,从服务器(来自 .env.local的值):

terminalbash
curl -X PUT "$NEXT_PUBLIC_AURABASE_URL/v1/db/schema/tables/todos/realtime" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  -H "Content-Type: application/json" \
  -d '{"enabled": true}'

然后订阅更改。登录用户接收其 RLS 策略允许其读取的行,包括登录前打开通道的时间(自动重新进行身份验证);拒绝订阅报告 CHANNEL_ERROR 并说明原因。

components/LiveTodos.tsxtypescript
'use client'
import { aura } from '@/lib/aurabase'
import { useEffect } from 'react'

export function LiveTodos() {
  useEffect(() => {
    const channel = aura.realtime
      .channel('todos')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'todos' }, (change) =>
        console.log(change.eventType, change.new),
      )
      .subscribe((status, err) => {
        // 在开发中,React StrictMode 会挂载、卸载和重新挂载组件:
        // 第一个关闭来自于清理工作并且是预期的。
        if (status === 'SUBSCRIBED') console.log('realtime connected')
        if (status === 'CHANNEL_ERROR') console.error('realtime refused:', err?.message)
      })

    return () => {
      void channel.unsubscribe()
    }
  }, [])
  return null
}
提示

订阅通过单个 TCP 连接进行多路复用。根据需要打开任意数量 — 零额外网络成本。

为了走得更远#