Next.jsで作る最初のアプリ
ユーザーがメールアドレスで新規登録し、自分のToDoだけを見られるToDoリストです。データベースにはダッシュボードを、アプリでは@espobase/clientを使います。
1. プロジェクトとテーブルを作成する
ダッシュボードでプロジェクトを作成します。SQLエディタを開いて、次を実行します:
create table todos ( id bigint generated by default as identity primary key, owner_id uuid not null default espobase.user_id(), title text not null, done boolean not null default false, created_at timestamptz not null default now() ); -- Row level security is already on. This rule lets each signed-in user see and change only their own todos: create policy "Users manage their own todos" on todos for all using (owner_id = espobase.user_id()) with check (owner_id = espobase.user_id());
クリック操作のほうがよいですか? テーブルエディタでテーブルを作成し、データベース › ポリシーで「ユーザーが行の所有者」テンプレートを、所有者カラムにowner_idを指定して追加します。
2. 設定とキー
- 認証 › 設定: Site URLにアプリが動作するアドレスを設定します(例:開発中は
http://localhost:3000)。確認メールとパスワードリセットのメールはそこにリンクします。 - API: 公開可能キーを作成します。キーは作成時にしか表示されないため、今すぐコピーしてください。
Next.jsアプリでクライアントをインストールし、設定を.env.localに追加します:
npm install @espobase/client
NEXT_PUBLIC_ESPOBASE_URL=https://api.espobase.com/project/<your project ref> NEXT_PUBLIC_ESPOBASE_KEY=eb_pk_… # the PUBLISHABLE key: safe in the browser
シークレットキー(eb_sk_…)をNEXT_PUBLIC_変数に入れないでください。これらの変数はブラウザに送られます。CLIを使えば、npx espobase initがURLを表示し、TypeScriptの型を書き出してくれます。
3. クライアント
// lib/espobase.ts
import { createClient } from "@espobase/client";
export const espobase = createClient(
process.env.NEXT_PUBLIC_ESPOBASE_URL!,
process.env.NEXT_PUBLIC_ESPOBASE_KEY!,
);4. 新規登録とログイン
"use client";
import { espobase } from "@/lib/espobase";
// Sign up: Espobase emails a confirmation link to your Site URL.
await espobase.auth.signUp({ email, password });
// Sign in (after confirming): the session is kept and refreshed for you.
await espobase.auth.signInWithPassword({ email, password });
// React to sign-in and sign-out anywhere in your app.
espobase.auth.onAuthStateChange((_event, session) => setSession(session));確認リンクは、#の後ろにトークンを付けてSite URLを開きます。espobase.auth.verifyEmail({ token })で確認してください。そのための数行のコードとパスワードリセットについてはログインとセキュリティルールをご覧ください。
5. データを読み書きする
// Only the signed-in user's todos come back: the security rule filters them.
const { data: todos, error } = await espobase.from("todos").select("*").order("created_at");
// owner_id fills itself in (its default is espobase.user_id()).
await espobase.from("todos").insert({ title: "Buy milk" });
await espobase.from("todos").update({ done: true }).eq("id", todo.id);
await espobase.from("todos").delete().eq("id", todo.id);すべてのリクエストにはログイン中のユーザーが含まれ、データベースがあなたのルールを適用します。ログインしていないユーザーには空のリストが返され、APIを直接呼び出しても、他人のToDoを読んだり変更したりすることは誰にもできません。