# 在 Next.js 中创建管理后台的提示词

> AI 代理提示词，用于构建受保护的 Next.js 管理后台，包含数据表格、服务端认证守卫和使用 Tailwind 的侧边栏布局。

**Type:** Prompt  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Next.js, PostgreSQL, TypeScript, Tailwind  
**Difficulty:** hard  
**Updated:** 2026-06-08

---

将此提示词交给您的 AI 代理，用于搭建一个基于角色的管理区域，包含固定侧边栏、可排序数据表格和服务端认证检查——无需搭建一个完整的全新 Next.js 项目或安装臃肿的管理框架。

## 主要提示词

```txt title="Main Prompt"
You are working in an existing Next.js App Router project with TypeScript, Tailwind CSS v4,
and PostgreSQL. Auth is already set up (assume a `getSession()` helper exists in `src/lib/get-session.ts`
that returns `{ user: { id, email, role } } | null`).

Task: add an admin dashboard at the `/admin` route group.

Requirements:
- Create a `src/app/(admin)/layout.tsx` that:
  - Calls `getSession()` and redirects to `/login` if the session is null or `role !== 'admin'`.
  - Renders a persistent sidebar with links: Dashboard, Users, Settings.
  - Uses Tailwind for layout — a fixed-width sidebar and a scrollable main area.
- Create `src/app/(admin)/dashboard/page.tsx` with:
  - Four KPI cards: Total Users, Active Today, Revenue (MRR), Churn Rate — all fetched from
    PostgreSQL using parameterized queries via `postgres` npm package.
  - A `<UsersTable>` server component that renders the 50 most recent users (id, email, role,
    created_at) with sortable column headers (URL-based sort param).
- Create `src/components/admin/KpiCard.tsx` and `src/components/admin/UsersTable.tsx`.
- All DB queries must use parameterized placeholders — never string interpolation.
- Do not install Prisma, Drizzle, or any ORM. Use the `postgres` package directly.
- Do not use any pre-built admin UI library (Refine, AdminJS, etc.).

Stop and list all planned file changes before writing any code.
```

## 实现说明

- `(admin)` 路由组的括号将 `/admin/dashboard` 从 URL 中隐藏，同时共享布局——AI 代理有时会忘记括号，从而创建字面上的 `/admin` 路径段。
- 可排序列应使用 `?sort=email&dir=asc` URL 参数，在服务端组件中通过 `searchParams` 属性读取——无需客户端状态。
- KPI 查询应使用 `Promise.all` 并行执行，以减少数据库往返次数。

## 预期文件变更

```txt
src/app/(admin)/layout.tsx                  (new)
src/app/(admin)/dashboard/page.tsx          (new)
src/components/admin/KpiCard.tsx            (new)
src/components/admin/UsersTable.tsx         (new)
src/lib/queries/admin-stats.ts             (new)
```

## 验收标准

- 非管理员用户访问 `/dashboard` 时重定向到 `/login`。
- KPI 卡片显示来自 PostgreSQL 的真实值。
- 用户表按 `sort` 和 `dir` URL 参数在服务端排序。
- `bun run build` 退出码为 0，无类型错误。

## 测试命令

```bash
bun run typecheck
bun run build
bun run dev
# log in as admin and visit /dashboard
# visit /dashboard without auth — confirm redirect to /login
# add ?sort=email&dir=asc to the URL and confirm table order
```

## 常见 AI 错误

- 创建了 `src/app/admin/layout.tsx` 而不是 `src/app/(admin)/layout.tsx`。
- 在客户端执行认证检查，这可以被绕过。
- 在 SQL 查询中使用了字符串插值：`` `SELECT * FROM users WHERE role = '${role}'` ``。
- 依次获取 KPI 统计数据，而不是使用 `Promise.all`。

## 修正提示词

```txt title="Fix Prompt"
The admin layout does not redirect unauthenticated users, or the route group folder name is wrong.
Fix in order:
1. Rename `src/app/admin/` to `src/app/(admin)/` — the parentheses are required for a route group.
2. In `layout.tsx`, add the auth check at the very top using `getSession()` and `redirect('/login')`.
3. Audit all SQL query strings and replace any interpolated variables with `$1`, `$2` placeholders.
Show the corrected diff only.
```