P PasteCode
Playbook

Prompt-to-PR: Add an Admin Data Table

SOP for adding a server-side paginated, sortable, searchable admin data table in Next.js using TanStack Table and a PostgreSQL query — no ORM magic.

CursorClaude CodeCodexWindsurf Next.jsTypeScriptPostgreSQLTailwind
.md .json Difficulty: Medium Updated Jun 8, 2026

Admin tables are a common AI coding task that frequently produces insecure, fully client-side implementations. This playbook keeps pagination and sorting server-side and explicitly guards the route.

1. Requirement

Add an /admin/users page accessible only to users with role = "admin". The table is server-side paginated (25 rows), sortable by column, and searchable by email. Data comes from a PostgreSQL users table via a parameterized query — no unparameterized SQL.

2. First Prompt

First Prompt
Add an admin users table to this Next.js 15 App Router project.
Requirements:
1. Create `src/app/admin/users/page.tsx` — an async Server Component.
- Protect it: check the session (using the existing auth helper at
src/lib/auth.ts). If no session or session.user.role !== "admin",
call notFound() or redirect to /.
- Read `page` (default 1), `sort` (default "createdAt"), `order`
("asc"|"desc", default "desc"), and `q` (search string) from
`searchParams`.
- Fetch data by calling a function `getUsers({ page, sort, order, q })`
from `src/lib/queries/users.ts`.
- Pass results to `<UsersTable>` client component.
2. Create `src/lib/queries/users.ts` exporting `getUsers`.
- Use parameterized SQL via the existing db client (Drizzle or postgres.js,
whichever is in this project).
- Allowed sort columns whitelist: ["email","name","createdAt","role"].
Reject any other sort value by defaulting to "createdAt".
- Return `{ rows: User[], total: number }`.
- Page size: 25.
3. Create `src/components/admin/UsersTable.tsx` — a Client Component using
TanStack Table v8.
- Columns: email, name, role, createdAt (formatted), actions (Edit link).
- Column headers are clickable to sort — update URL search params via
useRouter/useSearchParams (do not manage sort state locally).
- Render a search input that debounces 300 ms before updating the URL.
- Render a pagination row: Previous / Next and "Page N of M".
4. Install `@tanstack/react-table` if not already present.
5. Do not implement the Edit action — leave it as a placeholder link.

3. Expected File Changes

package.json (@tanstack/react-table if missing)
src/app/admin/users/page.tsx (new — protected Server Component)
src/lib/queries/users.ts (new — parameterized query)
src/components/admin/UsersTable.tsx (new — TanStack Table client component)

4. Review Checklist

  • The page checks session.user.role === "admin" server-side — no client-only guard.
  • getUsers whitelists allowed sort columns before interpolating into SQL — no raw user input in column names.
  • All WHERE/LIMIT/OFFSET values use parameterized placeholders, not string concatenation.
  • Search (q) uses ILIKE '%' || $1 || '%' with a parameter, not string interpolation.
  • TanStack Table is used in "use client" component only — no @tanstack/react-table import in Server Components.
  • URL search params drive sort/page/search state — browser Back button works correctly.
  • total count comes from a SELECT COUNT(*) in the same query function — not a full table scan separate from the paged query.

5. Test Commands

Terminal window
bun dev
# Hit the page as an unauthenticated user
curl -I http://localhost:3000/admin/users
# Expect: 404 or redirect, not 200
# Log in as an admin user in the browser, visit /admin/users
# Confirm: 25 rows, sortable columns, search, pagination
# SQL audit — confirm no dynamic column names slip through
grep -n "sort\|order\|column" src/lib/queries/users.ts
bun tsc --noEmit
bun test

6. Common Failures

  • SQL injection via sort column — agent interpolates sort directly: `ORDER BY ${sort}`. Must use a whitelist lookup to a safe column name string.
  • searchParams is async in Next.js 15+ — must be awaited: const { page } = await searchParams.
  • TanStack Table renders in a Server Component — build error because it uses useState. Move it to a "use client" component.
  • total count off by one pageMath.ceil(total / 25) gives wrong page count if total is 0. Guard: Math.max(1, Math.ceil(total / 25)).
  • Role check missing — agent only checks for a session, not the admin role. Any logged-in user can access the table.

7. Fix Prompt

Fix Prompt
The sort column in getUsers is interpolated directly into SQL:
`ORDER BY ${sort} ${order}`
This is a SQL injection risk.
Fix: create an allowlist object:
const ALLOWED_SORT: Record<string, string> = {
email: "users.email",
name: "users.name",
createdAt: "users.created_at",
role: "users.role",
};
const safeSort = ALLOWED_SORT[sort] ?? "users.created_at";
Then use `safeSort` in the query. The order direction must also be
validated: only accept "asc" or "desc", default to "desc".

8. PR Description

PR description
## Feature: Admin users table at /admin/users
- Server-side pagination (25 rows/page), sorting, and email search
- Role guard: redirects non-admins server-side (no client-only check)
- Parameterized SQL with sort-column whitelist — no injection surface
- TanStack Table v8 client component; sort/page/search state lives in URL
- `getUsers` returns `{ rows, total }` from a single query function