入门

使用 Supabase 与 Next.js

了解如何创建一个 Supabase 项目,添加一些示例数据,并从 Next.js 应用程序中查询数据。


1

创建一个 Supabase 项目

前往 database.new 并创建一个新的 Supabase 项目。

或者,您可以使用管理 API 创建项目

1
# First, get your access token from https://supabase.org.cn/dashboard/account/tokens
2
export SUPABASE_ACCESS_TOKEN="your-access-token"
3
4
# List your organizations to get the organization ID
5
curl -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \
6
https://api.supabase.com/v1/organizations
7
8
# Create a new project (replace <org-id> with your organization ID)
9
curl -X POST https://api.supabase.com/v1/projects \
10
-H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \
11
-H "Content-Type: application/json" \
12
-d '{
13
"organization_id": "<org-id>",
14
"name": "My Project",
15
"region": "us-east-1",
16
"db_pass": "<your-secure-password>"
17
}'

当您的项目启动并运行时,前往 表格编辑器,创建一个新表格并插入一些数据。

或者,您可以在项目的 SQL 编辑器 中运行以下代码片段。这将创建一个包含一些示例数据的 instruments 表。

1
-- Create the table
2
create table instruments (
3
id bigint primary key generated always as identity,
4
name text not null
5
);
6
-- Insert some sample data into the table
7
insert into instruments (name)
8
values
9
('violin'),
10
('viola'),
11
('cello');
12
13
alter table instruments enable row level security;

通过添加 RLS 策略使表格中的数据可公开读取

1
create policy "public can read instruments"
2
on public.instruments
3
for select to anon
4
using (true);
2

创建一个 Next.js 应用

使用 create-next-app 命令和 with-supabase 模板,创建一个预配置了

1
npx create-next-app -e with-supabase
3

声明 Supabase 环境变量

.env.example 重命名为 .env.local 并填充你的 Supabase 连接变量

项目 URL
可发布密钥
匿名密钥
1
NEXT_PUBLIC_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>
2
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>

你还可以从 项目的 连接 对话框 获取项目 URL 和密钥。

阅读 API 密钥文档 以全面了解所有密钥类型及其用途。

4

从 Next.js 查询 Supabase 数据

app/instruments/page.tsx 创建一个新文件并填充以下内容。

这将从 Supabase 的 instruments 表中选择所有行并在页面上渲染它们。

1
import { createClient } from "@/lib/supabase/server";
2
import { Suspense } from "react";
3
4
async function InstrumentsData() {
5
const supabase = await createClient();
6
const { data: instruments } = await supabase.from("instruments").select();
7
8
return <pre>{JSON.stringify(instruments, null, 2)}</pre>;
9
}
10
11
export default function Instruments() {
12
return (
13
<Suspense fallback={<div>Loading instruments...</div>}>
14
<InstrumentsData />
15
</Suspense>
16
);
17
}
5

启动应用

运行开发服务器,在浏览器中访问 https://:3000/instruments,你应该会看到乐器列表。

1
npm run dev

下一步#