はじめに
「顧客リストはスプレッドシートで共有しているが、誰がいつ書き換えたのか分からない」
「2人が同時に編集して、片方の更新が消えた」
「共有リンクが社外に回っていないか、正直把握できていない」
このあたりが気になり始めたら、社内向けの管理画面を作るタイミングです。
この記事では、Next.js(App Router)とSupabaseを使って、ログイン付きの顧客管理画面を作ります。対象はログイン、一覧、検索、編集までです。コードはすべてコピペで動く形にしています。
「そもそもいつWebアプリに移すべきか」は前回の記事、「データをSupabaseに移す手順」はその前の記事にまとめています。
完成イメージ
/login ログイン画面(メールアドレス+パスワード)
/customers 顧客一覧(キーワード検索・ページ送り)
/customers/12/edit 編集画面(同時編集による上書きを防止)
┌──────────────────────────────────────────────┐
│ 顧客管理 山田 | ログアウト │
├──────────────────────────────────────────────┤
│ [顧客名・メールで検索 ] [検索] │
│ 3件 │
│ ID │ 顧客名 │ メール │ ステータス │ │
│ 1 │ 株式会社サンプル商事 │ info@... │ 取引中 │編集│
│ 2 │ 合同会社テスト工房 │ ... │ 休止中 │編集│
│ ← 前へ 1 / 1 次へ → │
└──────────────────────────────────────────────┘
できるようになることは次の5つです。
- ログインした人だけが画面を開ける
-
staffテーブルに登録された社員だけがデータを読める。editor権限の人だけが更新できる - 更新日時と更新者が自動で記録される
- 他の人が先に更新していたら、保存せずに警告する(上書き事故の防止)
- 変更履歴(変更前と変更後の値)が自動で残る(実用例で追加)
ファイル構成
admin-app/
├── .env.local
├── proxy.ts
├── lib/
│ ├── config.ts
│ └── supabase/
│ └── server.ts
└── app/
├── globals.css
├── page.tsx
├── login/
│ ├── actions.ts
│ └── page.tsx
└── customers/
├── layout.tsx
├── page.tsx
└── [id]/
└── edit/
├── actions.ts
├── edit-form.tsx
└── page.tsx
準備 / 前提
| 項目 | 内容 |
|---|---|
| Node.js | 20.9 以上 |
| Next.js | 16(App Router)。15以前の場合は「つまずきやすいポイント」を参照 |
| Supabase | プロジェクト作成済み(Freeプランで可) |
| 言語 | TypeScript |
安全設計の考え方
SupabaseのURLと公開用キー(publishable key)は、ブラウザに見えてしまう前提の値です。そのため、守りは画面側だけでなくDB側にも置きます。
| 層 | 役割 | ここを突破されたら |
|---|---|---|
proxy.ts(画面) |
未ログインの人をログイン画面に戻す | 画面は表示されるが、データは空(RLSが守る) |
| RLS(DB) |
staff 登録者だけが読める。editor だけが更新できる |
ここが最後の砦 |
料金面で必ずぶつかる壁
| サービス | 注意点 |
|---|---|
| Supabase Free | しばらくアクセスがないとプロジェクトが一時停止する。業務で常用するなら Pro を検討 |
| Vercel Hobby | 商用利用不可。業務で使う場合は Pro プラン、または別のホスティングを使う |
Supabase側の設定
① テーブルとRLSを作る
ダッシュボードの「SQL Editor」で、以下をまとめて実行します。
-- 顧客テーブル
create table public.customers (
id bigint generated always as identity primary key,
name text not null,
email text,
phone text,
status text not null default 'active'
check (status in ('active', 'paused', 'closed')),
note text,
updated_at timestamptz not null default now(),
updated_by uuid references auth.users(id)
);
-- 管理画面を使える社員の名簿
create table public.staff (
user_id uuid primary key references auth.users(id) on delete cascade,
name text not null,
role text not null default 'viewer'
check (role in ('viewer', 'editor'))
);
alter table public.customers enable row level security;
alter table public.staff enable row level security;
-- ログイン中の人が staff に登録されているか(editor が必要な場合は role も見る)
create or replace function public.is_staff(required_role text default 'viewer')
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1
from public.staff s
where s.user_id = (select auth.uid())
and (required_role = 'viewer' or s.role = 'editor')
);
$$;
-- customers:staff は閲覧可、editor のみ更新可
create policy "staff can read customers"
on public.customers for select
to authenticated
using ((select public.is_staff('viewer')));
create policy "editors can update customers"
on public.customers for update
to authenticated
using ((select public.is_staff('editor')))
with check ((select public.is_staff('editor')));
-- staff:自分の行だけ読める(画面右上に名前を出すため)
create policy "staff can read own row"
on public.staff for select
to authenticated
using (user_id = (select auth.uid()));
-- 更新時に updated_at と updated_by を自動で入れる
create or replace function public.set_updated()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
new.updated_at := now();
new.updated_by := auth.uid();
return new;
end;
$$;
create trigger customers_set_updated
before update on public.customers
for each row execute function public.set_updated();
-- サンプルデータ
insert into public.customers (name, email, phone, status, note) values
('株式会社サンプル商事', 'info@sample-shoji.example.com', '03-0000-0001', 'active', '月末締め翌月末払い'),
('合同会社テスト工房', 'contact@test-kobo.example.com', '06-0000-0002', 'paused', '来期再開予定'),
('デモ物産株式会社', null, '052-000-0003', 'closed', null);
② 新規サインアップを止める
「Authentication」→「Sign In / Providers」で、「Allow new users to sign up」をオフにします。
ここがオンのままだと、公開用キーを使って誰でもアカウントを作れてしまいます。その場合もRLSでデータは守られますが、二重に塞いでおきます。
③ ユーザーを作って staff に登録する
「Authentication」→「Users」→「Add user」→「Create new user」で、自分のアカウントを作ります(「Auto Confirm User」にチェック)。作ったら、SQL Editorで staff に登録します。
insert into public.staff (user_id, name, role)
select id, '山田', 'editor' -- ★ 表示名と権限
from auth.users
where email = 'yamada@example.com'; -- ★ 作成したユーザーのメールアドレス
Step 1:プロジェクトを作る
npx create-next-app@latest admin-app --ts --tailwind --app --no-src-dir --import-alias "@/*"
cd admin-app
npm install @supabase/supabase-js @supabase/ssr
途中で質問が出たら、Enter(既定値)で進めて構いません。
続けて、app/globals.css を次の1行だけに置き換えます。テンプレートに入っているダークモード用の配色が残っていると、OSがダークモードのときに白い背景の上へ明るい文字が乗って読めなくなるためです。
@import "tailwindcss";
Step 2:設定値をまとめる
プロジェクト直下に .env.local を作ります。
# ★ Supabase ダッシュボード上部の「Connect」、または Project Settings > API Keys で確認
NEXT_PUBLIC_SUPABASE_URL=https://xxxxxxxxxxxx.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_xxxxxxxxxxxx
- 旧形式の
anonキー(eyJ...で始まるもの)でも動きます -
service_role/secretキーは絶対にここに入れないでください。RLSを素通りする管理者用のキーです
画面側の設定は lib/config.ts にまとめます。
// lib/config.ts
export const CONFIG = {
APP_NAME: '顧客管理', // ★ 画面上部に表示する名前
PAGE_SIZE: 20, // ★ 一覧の1ページあたりの件数
STATUS_LABELS: {
// ★ ステータスの表示名(キーはDBのcheck制約と合わせる)
active: '取引中',
paused: '休止中',
closed: '取引終了',
},
} as const
export type CustomerStatus = keyof typeof CONFIG.STATUS_LABELS
export type Customer = {
id: number
name: string
email: string | null
phone: string | null
status: CustomerStatus
note: string | null
updated_at: string
}
Step 3:Supabaseクライアントを作る
サーバー側(Server Component / Server Action)から使うクライアントです。ログイン状態はCookieで受け渡します。
// lib/supabase/server.ts
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
export async function createClient() {
const cookieStore = await cookies()
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options)
)
} catch {
// Server Component からはCookieを書けない。
// セッションの更新は proxy.ts 側で行うので無視してよい
}
},
},
}
)
}
Step 4:未ログインの人をログイン画面に戻す
プロジェクト直下(app/ と同じ階層)に proxy.ts を作ります。全リクエストの前に動き、セッションの更新と未ログイン時のリダイレクトを担当します。
// proxy.ts
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
// ログインなしで開けるパス
const PUBLIC_PATHS = ['/login']
export async function proxy(request: NextRequest) {
let response = NextResponse.next({ request })
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
response = NextResponse.next({ request })
cookiesToSet.forEach(({ name, value, options }) =>
response.cookies.set(name, value, options)
)
},
},
}
)
// 期限切れのセッションはここで更新される(この呼び出しは消さないこと)
const {
data: { user },
} = await supabase.auth.getUser()
const { pathname } = request.nextUrl
const isPublic = PUBLIC_PATHS.some(
(p) => pathname === p || pathname.startsWith(`${p}/`)
)
if (!user && !isPublic) {
return redirectWithCookies(request, response, '/login')
}
if (user && pathname === '/login') {
return redirectWithCookies(request, response, '/customers')
}
return response
}
// リダイレクトするときも、更新済みのセッションCookieを引き継ぐ
function redirectWithCookies(
request: NextRequest,
from: NextResponse,
pathname: string
) {
const url = request.nextUrl.clone()
url.pathname = pathname
url.search = ''
const redirect = NextResponse.redirect(url)
from.cookies.getAll().forEach((cookie) => redirect.cookies.set(cookie))
return redirect
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}
サーバー側でログイン状態を確認するときは、getSession() ではなく getUser() を使います。getSession() はCookieの中身をそのまま信じるため、改ざんされたCookieでも通ってしまいます。
トップページ(/)は一覧に飛ばすだけにします。
// app/page.tsx
import { redirect } from 'next/navigation'
export default function Home() {
redirect('/customers')
}
Step 5:ログイン画面
ログインとログアウトはServer Actionで実装します。
// app/login/actions.ts
'use server'
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
export type LoginState = { error: string | null }
export async function login(
_prev: LoginState,
formData: FormData
): Promise<LoginState> {
const email = String(formData.get('email') ?? '').trim()
const password = String(formData.get('password') ?? '')
if (!email || !password) {
return { error: 'メールアドレスとパスワードを入力してください' }
}
const supabase = await createClient()
const { error } = await supabase.auth.signInWithPassword({ email, password })
if (error) {
// どちらが違うかは教えない(アカウントの存在確認に使われるため)
return { error: 'メールアドレスまたはパスワードが違います' }
}
redirect('/customers')
}
export async function logout() {
const supabase = await createClient()
await supabase.auth.signOut()
redirect('/login')
}
// app/login/page.tsx
'use client'
import { useActionState } from 'react'
import { login, type LoginState } from './actions'
const initialState: LoginState = { error: null }
export default function LoginPage() {
const [state, formAction, pending] = useActionState(login, initialState)
return (
<main className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
<form
action={formAction}
className="w-full max-w-sm space-y-4 rounded-lg border bg-white p-6 shadow-sm"
>
<h1 className="text-xl font-bold">ログイン</h1>
<label className="block">
<span className="text-sm font-medium">メールアドレス</span>
<input
name="email"
type="email"
required
autoComplete="email"
className="mt-1 w-full rounded border px-3 py-2"
/>
</label>
<label className="block">
<span className="text-sm font-medium">パスワード</span>
<input
name="password"
type="password"
required
autoComplete="current-password"
className="mt-1 w-full rounded border px-3 py-2"
/>
</label>
{state.error && (
<p role="alert" className="text-sm text-red-600">
{state.error}
</p>
)}
<button
type="submit"
disabled={pending}
className="w-full rounded bg-blue-600 py-2 text-white disabled:opacity-50"
>
{pending ? 'ログイン中…' : 'ログイン'}
</button>
</form>
</main>
)
}
Step 6:共通レイアウト(ヘッダーと権限チェック)
/customers 以下の全ページに共通のヘッダーを付けます。staff に登録されていない人には中身を見せません。
// app/customers/layout.tsx
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { logout } from '@/app/login/actions'
import { CONFIG } from '@/lib/config'
export default async function CustomersLayout({
children,
}: {
children: React.ReactNode
}) {
const supabase = await createClient()
const {
data: { user },
} = await supabase.auth.getUser()
// proxy.ts をすり抜けた場合の保険
if (!user) redirect('/login')
// staff に未登録の人には中身を見せない(RLSでも弾かれるが、画面でも明示する)
const { data: staff } = await supabase
.from('staff')
.select('name, role')
.eq('user_id', user.id)
.maybeSingle()
return (
<div className="min-h-screen bg-gray-50 text-gray-900">
<header className="flex items-center justify-between border-b bg-white px-6 py-3">
<Link href="/customers" className="font-bold">
{CONFIG.APP_NAME}
</Link>
<div className="flex items-center gap-4 text-sm">
<span className="text-gray-600">{staff?.name ?? user.email}</span>
<form action={logout}>
<button type="submit" className="text-gray-600 underline">
ログアウト
</button>
</form>
</div>
</header>
<main className="p-6">
{staff ? (
children
) : (
<p className="text-red-600">
このアカウントには閲覧権限がありません。管理者に連絡してください。
</p>
)}
</main>
</div>
)
}
Step 7:一覧画面(検索・ページ送り)
検索キーワードとページ番号はURLのクエリ(?q=サンプル&page=2)で持たせます。そうすると、検索結果のURLを同僚にそのまま共有できます。
// app/customers/page.tsx
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { CONFIG, type Customer } from '@/lib/config'
type Props = {
searchParams: Promise<{ q?: string; page?: string; updated?: string }>
}
// PostgREST のフィルタ構文を壊す記号は検索語から除く
function sanitizeKeyword(raw: string): string {
return raw.replace(/[,()"\\%_*]/g, ' ').trim()
}
function pageHref(q: string, page: number): string {
const params = new URLSearchParams()
if (q) params.set('q', q)
if (page > 1) params.set('page', String(page))
const qs = params.toString()
return qs ? `/customers?${qs}` : '/customers'
}
function formatDateTime(iso: string): string {
return new Date(iso).toLocaleString('ja-JP', {
timeZone: 'Asia/Tokyo',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
export default async function CustomersPage({ searchParams }: Props) {
const { q = '', page = '1', updated } = await searchParams
const keyword = sanitizeKeyword(q)
const currentPage = Math.max(1, Math.floor(Number(page)) || 1)
const from = (currentPage - 1) * CONFIG.PAGE_SIZE
const to = from + CONFIG.PAGE_SIZE - 1
const supabase = await createClient()
let query = supabase
.from('customers')
.select('id, name, email, phone, status, note, updated_at', { count: 'exact' })
if (keyword) {
query = query.or(`name.ilike.%${keyword}%,email.ilike.%${keyword}%`)
}
const { data, count, error } = await query
.order('id', { ascending: true })
.range(from, to)
// 範囲外のページ(PGRST103)は「0件」として扱う。それ以外はログに残す
const fetchError = error && error.code !== 'PGRST103' ? error : null
if (fetchError) console.error('[customers list]', fetchError)
const customers = (data ?? []) as Customer[]
const total = count ?? 0
const totalPages = Math.max(1, Math.ceil(total / CONFIG.PAGE_SIZE))
return (
<div className="space-y-4">
{updated === '1' && (
<p className="rounded bg-green-50 px-4 py-2 text-sm text-green-800">
保存しました
</p>
)}
<form method="get" className="flex flex-wrap gap-2">
<input
name="q"
defaultValue={q}
placeholder="顧客名・メールで検索"
className="w-full max-w-xs rounded border bg-white px-3 py-2"
/>
<button type="submit" className="rounded bg-gray-800 px-4 py-2 text-white">
検索
</button>
{q && (
<Link href="/customers" className="px-2 py-2 text-sm text-gray-600 underline">
クリア
</Link>
)}
</form>
{fetchError ? (
<p className="text-red-600">
データの取得に失敗しました。時間をおいて再読み込みしてください。
</p>
) : (
<>
<p className="text-sm text-gray-600">{total}件</p>
<div className="overflow-x-auto rounded border bg-white">
<table className="w-full text-sm">
<thead className="bg-gray-100 text-left">
<tr>
<th className="px-3 py-2">ID</th>
<th className="px-3 py-2">顧客名</th>
<th className="px-3 py-2">メール</th>
<th className="px-3 py-2">電話</th>
<th className="px-3 py-2">ステータス</th>
<th className="px-3 py-2">更新日時</th>
<th className="px-3 py-2"></th>
</tr>
</thead>
<tbody>
{customers.length === 0 ? (
<tr>
<td colSpan={7} className="px-3 py-6 text-center text-gray-500">
該当するデータがありません
</td>
</tr>
) : (
customers.map((c) => (
<tr key={c.id} className="border-t">
<td className="px-3 py-2">{c.id}</td>
<td className="px-3 py-2">{c.name}</td>
<td className="px-3 py-2">{c.email ?? '-'}</td>
<td className="px-3 py-2">{c.phone ?? '-'}</td>
<td className="px-3 py-2">
{CONFIG.STATUS_LABELS[c.status] ?? c.status}
</td>
<td className="px-3 py-2">{formatDateTime(c.updated_at)}</td>
<td className="px-3 py-2">
<Link
href={`/customers/${c.id}/edit`}
className="text-blue-600 underline"
>
編集
</Link>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
<nav className="flex items-center gap-4 text-sm">
{currentPage > 1 ? (
<Link href={pageHref(q, currentPage - 1)} className="text-blue-600 underline">
← 前へ
</Link>
) : (
<span className="text-gray-400">← 前へ</span>
)}
<span>
{currentPage} / {totalPages}
</span>
{currentPage < totalPages ? (
<Link href={pageHref(q, currentPage + 1)} className="text-blue-600 underline">
次へ →
</Link>
) : (
<span className="text-gray-400">次へ →</span>
)}
</nav>
</>
)}
</div>
)
}
Step 8:編集画面(同時編集の上書き防止つき)
スプレッドシート運用でいちばん多い事故が「後から保存した人の内容で、先に保存された更新が消える」ことです。
これを防ぐため、編集画面を開いた時点の updated_at を隠しフィールドで持たせておきます。保存時にその値が変わっていたら更新しません。これを楽観的ロックと呼びます。
8-1. 保存処理(Server Action)
// app/customers/[id]/edit/actions.ts
'use server'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { CONFIG } from '@/lib/config'
export type UpdateState = {
error: string | null
values?: {
name: string
email: string
phone: string
status: string
note: string
}
}
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
export async function updateCustomer(
_prev: UpdateState,
formData: FormData
): Promise<UpdateState> {
const id = String(formData.get('id') ?? '')
const prevUpdatedAt = String(formData.get('updated_at') ?? '')
const values = {
name: String(formData.get('name') ?? '').trim(),
email: String(formData.get('email') ?? '').trim(),
phone: String(formData.get('phone') ?? '').trim(),
status: String(formData.get('status') ?? ''),
note: String(formData.get('note') ?? '').trim(),
}
// --- 入力チェック(ブラウザ側のチェックは迂回できるので、サーバーでも必ず行う)---
if (!/^\d+$/.test(id) || !prevUpdatedAt) {
return { error: '不正なリクエストです', values }
}
if (!values.name) {
return { error: '顧客名は必須です', values }
}
if (values.name.length > 100) {
return { error: '顧客名は100文字以内で入力してください', values }
}
if (values.email && !EMAIL_RE.test(values.email)) {
return { error: 'メールアドレスの形式が正しくありません', values }
}
if (!Object.keys(CONFIG.STATUS_LABELS).includes(values.status)) {
return { error: 'ステータスの値が不正です', values }
}
if (values.note.length > 2000) {
return { error: '備考は2000文字以内で入力してください', values }
}
const supabase = await createClient()
// updated_at が開いた時点と同じ場合だけ更新する
const { data, error } = await supabase
.from('customers')
.update({
name: values.name,
email: values.email || null,
phone: values.phone || null,
status: values.status,
note: values.note || null,
})
.eq('id', id)
.eq('updated_at', prevUpdatedAt)
.select('id')
if (error) {
console.error('[updateCustomer]', error)
return { error: '保存に失敗しました。時間をおいて再度お試しください', values }
}
// 1件も更新されなかった → 先に誰かが更新した or 権限がない
if (!data || data.length === 0) {
const { data: current } = await supabase
.from('customers')
.select('updated_at')
.eq('id', id)
.maybeSingle()
if (current && current.updated_at !== prevUpdatedAt) {
return {
error:
'他の人が先に更新しました。画面を再読み込みして、最新の内容で編集し直してください',
values,
}
}
return { error: '編集権限がありません(閲覧専用アカウントです)', values }
}
revalidatePath('/customers')
redirect('/customers?updated=1')
}
8-2. 入力フォーム
// app/customers/[id]/edit/edit-form.tsx
'use client'
import Link from 'next/link'
import { useActionState } from 'react'
import { updateCustomer, type UpdateState } from './actions'
import { CONFIG, type Customer } from '@/lib/config'
const initialState: UpdateState = { error: null }
const inputClass = 'mt-1 w-full rounded border px-3 py-2'
export default function EditForm({ customer }: { customer: Customer }) {
const [state, formAction, pending] = useActionState(updateCustomer, initialState)
// エラーで戻ってきたときは入力した値を残す
// (React 19 は送信後にフォームを初期値へリセットするため)
const v = state.values ?? {
name: customer.name,
email: customer.email ?? '',
phone: customer.phone ?? '',
status: customer.status,
note: customer.note ?? '',
}
return (
<form action={formAction} className="max-w-xl space-y-4 rounded border bg-white p-6">
<input type="hidden" name="id" value={customer.id} />
<input type="hidden" name="updated_at" value={customer.updated_at} />
<label className="block">
<span className="text-sm font-medium">
顧客名 <span className="text-red-600">*</span>
</span>
<input name="name" defaultValue={v.name} required maxLength={100} className={inputClass} />
</label>
<label className="block">
<span className="text-sm font-medium">メールアドレス</span>
<input name="email" type="email" defaultValue={v.email} className={inputClass} />
</label>
<label className="block">
<span className="text-sm font-medium">電話番号</span>
<input name="phone" type="tel" defaultValue={v.phone} className={inputClass} />
</label>
<label className="block">
<span className="text-sm font-medium">ステータス</span>
<select name="status" defaultValue={v.status} className={inputClass}>
{Object.entries(CONFIG.STATUS_LABELS).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</label>
<label className="block">
<span className="text-sm font-medium">備考</span>
<textarea name="note" defaultValue={v.note} rows={4} maxLength={2000} className={inputClass} />
</label>
{state.error && (
<p role="alert" className="text-sm text-red-600">
{state.error}
</p>
)}
<div className="flex gap-3">
<button
type="submit"
disabled={pending}
className="rounded bg-blue-600 px-4 py-2 text-white disabled:opacity-50"
>
{pending ? '保存中…' : '保存'}
</button>
<Link href="/customers" className="px-4 py-2 text-gray-600 underline">
キャンセル
</Link>
</div>
</form>
)
}
8-3. 編集ページ本体
// app/customers/[id]/edit/page.tsx
import { notFound } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import type { Customer } from '@/lib/config'
import EditForm from './edit-form'
type Props = {
params: Promise<{ id: string }>
}
export default async function EditCustomerPage({ params }: Props) {
const { id } = await params
if (!/^\d+$/.test(id)) notFound()
const supabase = await createClient()
const { data, error } = await supabase
.from('customers')
.select('id, name, email, phone, status, note, updated_at')
.eq('id', id)
.maybeSingle()
if (error) {
console.error('[customers edit]', error)
throw new Error('データの取得に失敗しました')
}
if (!data) notFound()
return (
<div className="space-y-4">
<h1 className="text-lg font-bold">顧客情報の編集(ID: {data.id})</h1>
<EditForm customer={data as Customer} />
</div>
)
}
動作確認
npm run dev
http://localhost:3000 を開くと、ログイン画面が表示されます。以下を順に確認します。
- ログインすると一覧が表示される
- 検索とページ送りが動く
- 編集して保存すると、一覧の更新日時が変わる
- ブラウザを2つ開いて同じ顧客を編集し、後から保存した側に警告が出る
実用例
例1:変更履歴を自動で残す
「誰が何をどう変えたか」を後から追えるようにします。アプリ側のコードは変更不要で、SQLを追加するだけです。
create table public.customer_logs (
id bigint generated always as identity primary key,
customer_id bigint not null,
changed_by uuid,
changed_at timestamptz not null default now(),
before_data jsonb,
after_data jsonb
);
alter table public.customer_logs enable row level security;
create policy "staff can read logs"
on public.customer_logs for select
to authenticated
using ((select public.is_staff('viewer')));
-- security definer:画面のユーザーに insert 権限を与えずに記録だけ行う
create or replace function public.log_customer_change()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
insert into public.customer_logs (customer_id, changed_by, before_data, after_data)
values (old.id, auth.uid(), to_jsonb(old), to_jsonb(new));
return new;
end;
$$;
create trigger customers_log_change
after update on public.customers
for each row execute function public.log_customer_change();
確認用のSQLです。誰がいつ、どの項目を変えたかが分かります。
select
l.changed_at,
s.name as changed_by,
l.before_data ->> 'status' as status_before,
l.after_data ->> 'status' as status_after
from public.customer_logs l
left join public.staff s on s.user_id = l.changed_by
where l.customer_id = 1 -- ★ 確認したい顧客ID
order by l.changed_at desc;
例2:前回の記事で移行したテーブルに適用する
Supabase移行の記事で作ったテーブルに、この画面を載せる場合です。更新管理用のカラムを足してから、上記のRLSとトリガーを設定します。
alter table public.customers
add column if not exists updated_at timestamptz not null default now(),
add column if not exists updated_by uuid references auth.users(id);
テーブル名やカラム名が違う場合は、SQLと lib/config.ts の Customer 型、各画面の select(...) を合わせて書き換えてください。
例3:閲覧だけできるメンバーを追加する
閲覧だけのメンバーは、role を viewer にして登録します。編集画面で保存しようとすると「編集権限がありません」と表示され、DBは更新されません。
insert into public.staff (user_id, name, role)
select id, '佐藤', 'viewer' -- ★
from auth.users
where email = 'sato@example.com'; -- ★
退職者が出たら、Supabaseの「Authentication」→「Users」からユーザーを削除します。on delete cascade により staff からも自動で消えます。
例4:Vercelにデプロイする
- GitHubにpushする(
.env.localは.gitignore済みなので含まれない) - Vercelでリポジトリをインポートする
- 「Environment Variables」に
NEXT_PUBLIC_SUPABASE_URLとNEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEYを登録する - デプロイする
console.error で出したログは、Vercelの「Logs」で確認できます。「保存できない」と問い合わせが来たときの調査に使えます。
つまずきやすいポイント
| 症状 | 原因 | 対処 |
|---|---|---|
| ログインできるが一覧が0件(エラーなし) |
staff に未登録で、RLSにより全行が見えていない |
select * from public.staff; で自分の user_id があるか確認する |
permission denied for table customers |
authenticated ロールにテーブル権限がない |
grant select, update on public.customers to authenticated; を実行する。staff と customer_logs も同様に grant select する |
| ログインしても何も起きない/ログイン画面に戻される |
proxy.ts の置き場所が違う |
app/ と同じ階層(プロジェクト直下)に置く。src/ を使う場合は src/proxy.ts
|
Next.js 15以前で proxy.ts が動かない |
15以前はファイル名が異なる | ファイル名を middleware.ts、関数名を middleware に変える |
Invalid API key / 環境変数が undefined
|
.env.local の変更後に再起動していない、またはVercelに未登録 |
npm run dev を再起動する。Vercelは環境変数を登録してから再デプロイする |
| 保存すると「編集権限がありません」 |
role が viewer
|
update public.staff set role = 'editor' where name = '山田'; |
| 保存すると毎回「他の人が先に更新しました」 | 別のスクリプトやトリガーが updated_at を書き換えている、または古いタブで編集している |
ページを再読み込みしてから編集する。他に customers を更新している処理がないか確認する |
| 誰でもアカウントを作れてしまう | サインアップが有効のまま | 「Allow new users to sign up」をオフにする(RLSで守られていても塞いでおく) |
| ダークモードで文字が読めない | テンプレートの globals.css の配色が残っている |
Step 1のとおり @import "tailwindcss"; だけにする |
まとめ
- Next.js(App Router)+ Supabaseで、ログイン付きの社内管理画面はファイル10個程度で作れる
- 公開用キーはブラウザに見える前提。守りはRLS(DB側)に置く。画面側の
proxy.tsは入口の案内役 -
staffテーブルとis_staff()関数で「誰が読めて、誰が書けるか」をDBで管理する - サインアップを無効化し、ユーザーは管理者が作る運用にする
-
updated_atを使った楽観的ロックで、同時編集の上書き事故を防ぐ - 更新者・更新日時・変更履歴はトリガーで自動記録する。アプリ側に書き忘れが起きない
- 無料プランには一時停止や商用利用不可の制限がある。業務で使うならプランを確認する
Webシステム開発のご相談
「スプレッドシートやGASで回している業務を、ちゃんとした管理画面にしたい」「Supabaseで社内システムを作りたいが、権限設計に不安がある」などのご相談を受け付けています。