feat: close remaining gaps — middleware, demo wiring, error UX, env validation
CI / lint + typecheck + test + build (push) Canceled after 0s
CI / lint + typecheck + test + build (push) Canceled after 0s
- Auth: middleware.ts guards /protected via better-auth session cookie; protected page reads session server-side (auth.api.getSession) - Demo wiring (app/demo + components/demo): react-markdown + remark-gfm + shiki CodeBlock, RHF+zod form with react-query mutation + sonner toast, react-table items list (legacy API, table v9), /api/items GET+POST (zod v4 coercion, schema in lib/items.ts shared with unit tests) - Error UX: app/error.tsx (retry + digest), not-found.tsx (404), loading.tsx - Env: lib/env.ts zod-validated (no import-time throw), .env.example sync (NEXT_PUBLIC_BETTER_AUTH_URL), auth-client uses env - Tooling: @vitest/coverage-v8 (test:coverage works), tsconfig cleanup (drop .next/dev/dev/types artifact), README rewrite, demo e2e specs
This commit is contained in:
@@ -4,6 +4,9 @@ BETTER_AUTH_SECRET=
|
|||||||
# Full absolute URL of the deployed app, e.g. https://example.com
|
# Full absolute URL of the deployed app, e.g. https://example.com
|
||||||
BETTER_AUTH_URL=
|
BETTER_AUTH_URL=
|
||||||
|
|
||||||
|
# Public auth URL for the browser client (must match BETTER_AUTH_URL in prod)
|
||||||
|
NEXT_PUBLIC_BETTER_AUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
# Optional: database URL for better-auth (Kysely/Drizzle adapter)
|
# Optional: database URL for better-auth (Kysely/Drizzle adapter)
|
||||||
# DATABASE_URL=postgres://user:pass@localhost:5432/db
|
# DATABASE_URL=postgres://user:pass@localhost:5432/db
|
||||||
|
|
||||||
|
|||||||
@@ -1,36 +1,117 @@
|
|||||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
# Next.js Template
|
||||||
|
|
||||||
## Getting Started
|
Production-ready Next.js 16 (App Router, Turbopack) starter on Bun, with
|
||||||
|
shadcn/ui Base UI components, TypeScript strict, and a zero-warning
|
||||||
|
lint/typecheck/test/build pipeline.
|
||||||
|
|
||||||
First, run the development server:
|
## Stack
|
||||||
|
|
||||||
|
- **Framework:** Next.js 16.3 (App Router, Turbopack, standalone output)
|
||||||
|
- **Runtime:** Bun 1.3.14
|
||||||
|
- **UI:** shadcn/ui Base-Nova (Base UI) + Tailwind CSS v4, lucide-react, motion
|
||||||
|
- **Data:** @tanstack/react-query, @tanstack/react-table
|
||||||
|
- **Forms:** react-hook-form + zod (v4) + @hookform/resolvers
|
||||||
|
- **Auth:** better-auth (memory adapter, swap to Drizzle/Postgres when ready)
|
||||||
|
- **API client:** openapi-fetch + openapi-typescript, ky
|
||||||
|
- **Markdown:** react-markdown + remark-gfm + shiki (server-side highlighting)
|
||||||
|
- **Misc:** zustand, nuqs, sonner, cmdk, vaul, embla-carousel-react, date-fns,
|
||||||
|
next-themes, recharts
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run dev
|
bun install
|
||||||
# or
|
cp .env.example .env # optional: set BETTER_AUTH_SECRET / BETTER_AUTH_URL
|
||||||
yarn dev
|
bun run dev # http://localhost:3000
|
||||||
# or
|
|
||||||
pnpm dev
|
|
||||||
# or
|
|
||||||
bun dev
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
Requires Node ≥ 18 (Bun runtime) — see `packageManager` in package.json.
|
||||||
|
|
||||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
## Scripts
|
||||||
|
|
||||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
| Script | Description |
|
||||||
|
| --------------------------------- | ------------------------------------------------------------------- |
|
||||||
|
| `bun run dev` | Start dev server (Turbopack, NODE_ENV pinned to development) |
|
||||||
|
| `bun run build` | Production build (standalone output for Docker) |
|
||||||
|
| `bun run start` | Serve the production build |
|
||||||
|
| `bun run lint` | ESLint (next core-web-vitals + typescript) |
|
||||||
|
| `bun run lint:fix` | ESLint with autofix |
|
||||||
|
| `bun run typecheck` | `tsc --noEmit` (strict + noUnusedLocals/Parameters) |
|
||||||
|
| `bun run test` | Vitest unit tests (jsdom + jest-dom) |
|
||||||
|
| `bun run test:watch` | Vitest watch mode |
|
||||||
|
| `bun run test:coverage` | Vitest with v8 coverage report |
|
||||||
|
| `bun run test:e2e` | Playwright E2E (Chromium, dedicated :3100) |
|
||||||
|
| `bun run format` / `format:check` | Prettier write / check (Tailwind v4 plugin) |
|
||||||
|
| `bun run api:generate` | Regenerate `types/api.ts` from `/api/openapi` (dev server must run) |
|
||||||
|
| `bun run prepare` | Install husky hooks |
|
||||||
|
|
||||||
## Learn More
|
Git hooks (husky + lint-staged) run ESLint + Prettier on staged files.
|
||||||
|
|
||||||
To learn more about Next.js, take a look at the following resources:
|
## Project structure
|
||||||
|
|
||||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
```
|
||||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
app/
|
||||||
|
page.tsx # landing page
|
||||||
|
demo/ # wiring example: markdown+shiki, form, table, session
|
||||||
|
protected/ # route guarded by middleware (better-auth session)
|
||||||
|
error.tsx / loading.tsx / not-found.tsx
|
||||||
|
api/
|
||||||
|
health/ # GET health JSON
|
||||||
|
openapi/ # OpenAPI 3.1 spec for codegen
|
||||||
|
auth/[...all]/ # better-auth handler
|
||||||
|
items/ # GET list / POST create (zod-validated)
|
||||||
|
components/
|
||||||
|
providers.tsx # QueryClient + Theme + Nuqs + Tooltip + Sonner
|
||||||
|
ui/ # shadcn Base-Nova components (CLI-managed)
|
||||||
|
demo/ # form + table wiring examples
|
||||||
|
hooks/ # use-mobile (useSyncExternalStore)
|
||||||
|
lib/
|
||||||
|
auth.ts # better-auth server (memory adapter)
|
||||||
|
auth-client.ts # better-auth react client
|
||||||
|
api.ts # typed openapi-fetch client
|
||||||
|
http.ts # ky wrapper
|
||||||
|
query-client.ts # react-query client (per-request on server)
|
||||||
|
env.ts # zod-validated env (no import-time throw)
|
||||||
|
types/api.ts # generated openapi-typescript types
|
||||||
|
middleware.ts # auth route guard
|
||||||
|
e2e/ # Playwright specs
|
||||||
|
.github/workflows/ci.yml
|
||||||
|
Dockerfile # multi-stage standalone build
|
||||||
|
```
|
||||||
|
|
||||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
## Auth
|
||||||
|
|
||||||
## Deploy on Vercel
|
better-auth is wired but intentionally runs on the in-memory adapter so the
|
||||||
|
template builds without a database.
|
||||||
|
|
||||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
1. `bunx @better-auth/cli secret` → put the result in `BETTER_AUTH_SECRET`.
|
||||||
|
2. Set `BETTER_AUTH_URL` (+ `NEXT_PUBLIC_BETTER_AUTH_URL` for the client).
|
||||||
|
3. To persist users, swap `memoryAdapter({})` in `lib/auth.ts` for a real
|
||||||
|
adapter (e.g. `drizzleAdapter(db, { provider: "pg" })`) and add the DB URL.
|
||||||
|
|
||||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
Routes under `/protected` require a session (see `middleware.ts`).
|
||||||
|
|
||||||
|
## OpenAPI + typed client
|
||||||
|
|
||||||
|
`app/api/openapi` serves an OpenAPI 3.1 document. Regenerate the typed client:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun run dev & # server must be up
|
||||||
|
bun run api:generate # writes types/api.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Then use `lib/api.ts` (`createClient<paths>` from openapi-fetch).
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -t nextjs-template .
|
||||||
|
docker run -p 3000:3000 nextjs-template
|
||||||
|
```
|
||||||
|
|
||||||
|
Multi-stage standalone image (~50MB runtime); runs as non-root user; requires
|
||||||
|
NODE_ENV=production and the env vars above at runtime.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Private template.
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { createItemSchema, MOCK_ITEMS, type Item, type CreateItemOutput } from "@/lib/items";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
return NextResponse.json({ items: MOCK_ITEMS });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
const parsed = createItemSchema.safeParse(body);
|
||||||
|
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: "Validation failed",
|
||||||
|
details: parsed.error.flatten().fieldErrors,
|
||||||
|
},
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const input: CreateItemOutput = parsed.data;
|
||||||
|
const item: Item = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
...input,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// In a real app: persist to DB here. MOCK_ITEMS is module-scoped, so the
|
||||||
|
// created item lives only for the lifetime of the server process.
|
||||||
|
MOCK_ITEMS.unshift(item);
|
||||||
|
|
||||||
|
return NextResponse.json({ item }, { status: 201 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import ReactMarkdown from "react-markdown";
|
||||||
|
import remarkGfm from "remark-gfm";
|
||||||
|
import { CodeBlock } from "@/components/ui/code-block";
|
||||||
|
import { DemoClient } from "@/components/demo/demo-client";
|
||||||
|
|
||||||
|
const SAMPLE_MD = `# Demo Page
|
||||||
|
|
||||||
|
This page shows the core wiring of the template:
|
||||||
|
|
||||||
|
- **Server component** renders this markdown via \`react-markdown\` + \`remark-gfm\`
|
||||||
|
- **Shiki** highlights code blocks server-side
|
||||||
|
- **React Query** fetches \`/api/items\`
|
||||||
|
- **React Hook Form + Zod** validates the "Add item" form
|
||||||
|
- **better-auth** session is read on the server below
|
||||||
|
|
||||||
|
## Code sample
|
||||||
|
|
||||||
|
\`\`\`ts
|
||||||
|
export function getGreeting(name: string): string {
|
||||||
|
return \`Hello, \${name}!\`;
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
> Tip: copy this page as a starting point for real features.
|
||||||
|
`;
|
||||||
|
|
||||||
|
export default function DemoPage() {
|
||||||
|
return (
|
||||||
|
<main className="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-8 p-8">
|
||||||
|
<article className="prose prose-sm dark:prose-invert">
|
||||||
|
<ReactMarkdown
|
||||||
|
remarkPlugins={[remarkGfm]}
|
||||||
|
components={{
|
||||||
|
code(props) {
|
||||||
|
const { children, className, ...rest } = props;
|
||||||
|
const match = /language-(\w+)/.exec(className ?? "");
|
||||||
|
if (match) {
|
||||||
|
return (
|
||||||
|
<CodeBlock
|
||||||
|
code={String(children).replace(/\n$/, "")}
|
||||||
|
lang={match[1]}
|
||||||
|
className="my-4 overflow-x-auto rounded-lg border text-sm"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<code className={className} {...rest}>
|
||||||
|
{children}
|
||||||
|
</code>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{SAMPLE_MD}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<DemoClient />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
export default function Error({
|
||||||
|
error,
|
||||||
|
reset,
|
||||||
|
}: {
|
||||||
|
error: Error & { digest?: string };
|
||||||
|
reset: () => void;
|
||||||
|
}) {
|
||||||
|
useEffect(() => {
|
||||||
|
console.error(error);
|
||||||
|
}, [error]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="flex flex-1 flex-col items-center justify-center gap-4 p-8">
|
||||||
|
<h1 className="text-2xl font-semibold">Something went wrong</h1>
|
||||||
|
<p className="max-w-md text-center text-sm text-muted-foreground">
|
||||||
|
{error.message || "An unexpected error occurred."}
|
||||||
|
</p>
|
||||||
|
{error.digest ? (
|
||||||
|
<p className="font-mono text-xs text-muted-foreground">Error ID: {error.digest}</p>
|
||||||
|
) : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => reset()}
|
||||||
|
className="rounded-lg border bg-background px-4 py-2 text-sm font-medium hover:bg-muted"
|
||||||
|
>
|
||||||
|
Try again
|
||||||
|
</button>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 items-center justify-center p-8" role="status">
|
||||||
|
<div className="flex items-center gap-3 text-sm text-muted-foreground">
|
||||||
|
<span className="size-4 animate-spin rounded-full border-2 border-foreground/20 border-t-foreground" />
|
||||||
|
Loading…
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
export default function NotFound() {
|
||||||
|
return (
|
||||||
|
<main className="flex flex-1 flex-col items-center justify-center gap-4 p-8">
|
||||||
|
<p className="text-5xl font-bold text-muted-foreground">404</p>
|
||||||
|
<h1 className="text-2xl font-semibold">Page not found</h1>
|
||||||
|
<p className="max-w-md text-center text-sm text-muted-foreground">
|
||||||
|
The page you are looking for does not exist or has been moved.
|
||||||
|
</p>
|
||||||
|
<Link
|
||||||
|
href="/"
|
||||||
|
className="rounded-lg border bg-background px-4 py-2 text-sm font-medium hover:bg-muted"
|
||||||
|
>
|
||||||
|
Back to home
|
||||||
|
</Link>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
return (
|
return (
|
||||||
@@ -37,6 +38,12 @@ export default function Home() {
|
|||||||
</a>{" "}
|
</a>{" "}
|
||||||
center.
|
center.
|
||||||
</p>
|
</p>
|
||||||
|
<Link
|
||||||
|
href="/demo"
|
||||||
|
className="rounded-full border border-black/[.08] bg-foreground px-5 py-2 text-sm font-medium text-background transition-colors hover:bg-[#383838] dark:border-white/[.145] dark:hover:bg-[#1a1a1a]"
|
||||||
|
>
|
||||||
|
View the demo wiring →
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
||||||
<a
|
<a
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { headers } from "next/headers";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function ProtectedPage() {
|
||||||
|
const session = await auth.api.getSession({ headers: await headers() });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="mx-auto flex max-w-2xl flex-1 flex-col items-center justify-center gap-4 p-8">
|
||||||
|
<h1 className="text-2xl font-semibold">Protected Page</h1>
|
||||||
|
{session ? (
|
||||||
|
<div className="flex flex-col items-center gap-2 rounded-lg border p-6">
|
||||||
|
<p className="text-lg">
|
||||||
|
Welcome, <span className="font-medium">{session.user.name}</span>!{" "}
|
||||||
|
<span className="text-muted-foreground">({session.user.email})</span>
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Session expires: {new Date(session.session.expiresAt).toLocaleString()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-muted-foreground">No session found.</p>
|
||||||
|
)}
|
||||||
|
<Link href="/" className="text-sm text-primary underline-offset-4 hover:underline">
|
||||||
|
← Back home
|
||||||
|
</Link>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ItemForm } from "@/components/demo/item-form";
|
||||||
|
import { ItemList } from "@/components/demo/item-list";
|
||||||
|
|
||||||
|
export function DemoClient() {
|
||||||
|
return (
|
||||||
|
<section className="flex flex-col gap-6">
|
||||||
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
|
<ItemForm />
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<h2 className="text-sm font-semibold">Items (react-query + react-table)</h2>
|
||||||
|
<ItemList />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
const itemSchema = z.object({
|
||||||
|
name: z.string().min(1, "Name is required").max(100),
|
||||||
|
quantity: z.coerce
|
||||||
|
.number({ error: "Quantity must be a number" })
|
||||||
|
.int("Must be a whole number")
|
||||||
|
.min(0, "Minimum 0")
|
||||||
|
.max(10000, "Maximum 10000"),
|
||||||
|
});
|
||||||
|
|
||||||
|
type ItemFormValues = z.input<typeof itemSchema>;
|
||||||
|
type ItemSubmitValues = z.output<typeof itemSchema>;
|
||||||
|
|
||||||
|
export function ItemForm() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
formState: { errors, isSubmitting },
|
||||||
|
} = useForm<ItemFormValues, unknown, ItemSubmitValues>({
|
||||||
|
resolver: zodResolver(itemSchema),
|
||||||
|
defaultValues: { name: "", quantity: 1 },
|
||||||
|
});
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: async (values: ItemSubmitValues) => {
|
||||||
|
const res = await fetch("/api/items", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(values),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => null);
|
||||||
|
throw new Error(err?.error ?? "Failed to create item");
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success("Item created");
|
||||||
|
reset();
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["items"] });
|
||||||
|
},
|
||||||
|
onError: (err: Error) => {
|
||||||
|
toast.error(err.message);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
onSubmit={handleSubmit((values) => mutation.mutate(values))}
|
||||||
|
className="flex flex-col gap-3 rounded-lg border p-4"
|
||||||
|
noValidate
|
||||||
|
>
|
||||||
|
<h2 className="text-sm font-semibold">Add item (RHF + zod + react-query)</h2>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label htmlFor="name" className="text-xs font-medium">
|
||||||
|
Name
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="name"
|
||||||
|
{...register("name")}
|
||||||
|
className="rounded-md border bg-background px-3 py-1.5 text-sm outline-none focus:border-ring"
|
||||||
|
placeholder="e.g. USB-C cable"
|
||||||
|
/>
|
||||||
|
{errors.name && <span className="text-xs text-destructive">{errors.name.message}</span>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label htmlFor="quantity" className="text-xs font-medium">
|
||||||
|
Quantity
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="quantity"
|
||||||
|
type="number"
|
||||||
|
{...register("quantity")}
|
||||||
|
className="rounded-md border bg-background px-3 py-1.5 text-sm outline-none focus:border-ring"
|
||||||
|
/>
|
||||||
|
{errors.quantity && (
|
||||||
|
<span className="text-xs text-destructive">{errors.quantity.message}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isSubmitting || mutation.isPending}
|
||||||
|
className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{mutation.isPending ? "Creating…" : "Create item"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { flexRender } from "@tanstack/react-table";
|
||||||
|
import {
|
||||||
|
legacyCreateColumnHelper as createColumnHelper,
|
||||||
|
getCoreRowModel,
|
||||||
|
useLegacyTable,
|
||||||
|
type LegacyColumnDef,
|
||||||
|
} from "@tanstack/react-table/legacy";
|
||||||
|
import { format } from "date-fns";
|
||||||
|
import type { Item } from "@/lib/items";
|
||||||
|
|
||||||
|
const columnHelper = createColumnHelper<Item>();
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
columnHelper.accessor("name", {
|
||||||
|
header: "Name",
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("quantity", {
|
||||||
|
header: "Qty",
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("createdAt", {
|
||||||
|
header: "Created",
|
||||||
|
cell: (info) => format(new Date(info.getValue<string>()), "MMM d, HH:mm"),
|
||||||
|
}),
|
||||||
|
] as LegacyColumnDef<Item>[];
|
||||||
|
|
||||||
|
export function ItemList() {
|
||||||
|
const { data, isLoading, isError, error, refetch } = useQuery({
|
||||||
|
queryKey: ["items"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await fetch("/api/items");
|
||||||
|
if (!res.ok) throw new Error("Failed to load items");
|
||||||
|
const body = await res.json();
|
||||||
|
return body.items as Item[];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const table = useLegacyTable({
|
||||||
|
data: data ?? [],
|
||||||
|
columns,
|
||||||
|
getCoreRowModel: getCoreRowModel(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <p className="text-sm text-muted-foreground">Loading items…</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isError) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-3 text-sm text-destructive">
|
||||||
|
<span>{error.message}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => refetch()}
|
||||||
|
className="rounded-md border px-2 py-1 hover:bg-muted"
|
||||||
|
>
|
||||||
|
Retry
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="overflow-hidden rounded-lg border">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-muted/50 text-left">
|
||||||
|
{table.getHeaderGroups().map((headerGroup) => (
|
||||||
|
<tr key={headerGroup.id}>
|
||||||
|
{headerGroup.headers.map((header) => (
|
||||||
|
<th key={header.id} className="px-4 py-2 font-medium">
|
||||||
|
{header.isPlaceholder
|
||||||
|
? null
|
||||||
|
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{table.getRowModel().rows.map((row) => (
|
||||||
|
<tr key={row.id} className="border-t hover:bg-muted/30">
|
||||||
|
{row.getVisibleCells().map((cell) => (
|
||||||
|
<td key={cell.id} className="px-4 py-2">
|
||||||
|
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||||
|
</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{data?.length === 0 ? (
|
||||||
|
<p className="px-4 py-3 text-sm text-muted-foreground">No items yet.</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { test, expect } from "@playwright/test";
|
||||||
|
|
||||||
|
test("demo page shows markdown, code block, and items table", async ({ page }) => {
|
||||||
|
await page.goto("/demo");
|
||||||
|
|
||||||
|
// Markdown rendered
|
||||||
|
await expect(page.getByRole("heading", { name: "Demo Page" })).toBeVisible();
|
||||||
|
await expect(page.getByText("Server component renders this markdown")).toBeVisible();
|
||||||
|
|
||||||
|
// Shiki code block (highlighted <pre> wrapper)
|
||||||
|
const codeBlock = page.locator("pre");
|
||||||
|
await expect(codeBlock.first()).toBeVisible();
|
||||||
|
|
||||||
|
// Items table loaded via react-query
|
||||||
|
await expect(page.getByText("Ergonomic chair")).toBeVisible();
|
||||||
|
await expect(page.getByText("Mechanical keyboard")).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("demo form creates an item (RHF + zod + mutation)", async ({ page }) => {
|
||||||
|
await page.goto("/demo");
|
||||||
|
|
||||||
|
const name = "Playwright gadget";
|
||||||
|
await page.getByLabel("Name").fill(name);
|
||||||
|
await page.getByLabel("Quantity").fill("5");
|
||||||
|
await page.getByRole("button", { name: "Create item" }).click();
|
||||||
|
|
||||||
|
await expect(page.getByText("Item created")).toBeVisible(); // sonner toast
|
||||||
|
await expect(page.getByText(name)).toBeVisible(); // appears in table
|
||||||
|
|
||||||
|
// Zod validation: empty name shows error
|
||||||
|
await page.getByLabel("Name").fill("");
|
||||||
|
await page.getByRole("button", { name: "Create item" }).click();
|
||||||
|
await expect(page.getByText("Name is required")).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("protected page redirects to home when unauthenticated", async ({ page }) => {
|
||||||
|
await page.goto("/protected");
|
||||||
|
await expect(page).toHaveURL(/\/\?next=%2Fprotected/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { createItemSchema } from "@/lib/items";
|
||||||
|
|
||||||
|
describe("items API schema", () => {
|
||||||
|
it("accepts valid input (coerces numeric strings)", () => {
|
||||||
|
const result = createItemSchema.safeParse({ name: "Chair", quantity: "4" });
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
if (result.success) {
|
||||||
|
expect(result.data).toEqual({ name: "Chair", quantity: 4 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects empty name", () => {
|
||||||
|
const result = createItemSchema.safeParse({ name: "", quantity: 1 });
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
if (!result.success) {
|
||||||
|
expect(result.error.flatten().fieldErrors.name).toBeTruthy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects non-numeric quantity", () => {
|
||||||
|
const result = createItemSchema.safeParse({ name: "Chair", quantity: "abc" });
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects negative quantity", () => {
|
||||||
|
const result = createItemSchema.safeParse({ name: "Chair", quantity: -5 });
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
+2
-1
@@ -1,7 +1,8 @@
|
|||||||
import { createAuthClient } from "better-auth/react";
|
import { createAuthClient } from "better-auth/react";
|
||||||
|
import { env } from "@/lib/env";
|
||||||
|
|
||||||
export const authClient = createAuthClient({
|
export const authClient = createAuthClient({
|
||||||
baseURL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL ?? "http://localhost:3000",
|
baseURL: env.NEXT_PUBLIC_BETTER_AUTH_URL,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const { useSession, signIn, signUp, signOut } = authClient;
|
export const { useSession, signIn, signUp, signOut } = authClient;
|
||||||
|
|||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
const envSchema = z.object({
|
||||||
|
NEXT_PUBLIC_BETTER_AUTH_URL: z.string().url().default("http://localhost:3000"),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validated public env vars. Uses .default() so missing vars don't throw at
|
||||||
|
* import time (keeps next build + CI safe); values fall back to dev defaults.
|
||||||
|
*/
|
||||||
|
const parsed = envSchema.safeParse({
|
||||||
|
NEXT_PUBLIC_BETTER_AUTH_URL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const env = parsed.success
|
||||||
|
? parsed.data
|
||||||
|
: {
|
||||||
|
NEXT_PUBLIC_BETTER_AUTH_URL: "http://localhost:3000",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const isEnvValid = () => parsed.success;
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export type Item = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
quantity: number;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createItemSchema = z.object({
|
||||||
|
name: z.string().min(1, "Name is required").max(100),
|
||||||
|
quantity: z.coerce.number({ error: "Quantity must be a number" }).int().min(0).max(10000),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CreateItemInput = z.input<typeof createItemSchema>;
|
||||||
|
export type CreateItemOutput = z.output<typeof createItemSchema>;
|
||||||
|
|
||||||
|
export const MOCK_ITEMS: Item[] = [
|
||||||
|
{ id: "1", name: "Ergonomic chair", quantity: 4, createdAt: "2026-09-01T08:00:00Z" },
|
||||||
|
{ id: "2", name: "Mechanical keyboard", quantity: 12, createdAt: "2026-09-02T09:30:00Z" },
|
||||||
|
{ id: "3", name: "USB-C dock", quantity: 7, createdAt: "2026-09-03T10:15:00Z" },
|
||||||
|
{ id: "4", name: "Monitor arm", quantity: 3, createdAt: "2026-09-04T11:45:00Z" },
|
||||||
|
];
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { getSessionCookie } from "better-auth/cookies";
|
||||||
|
|
||||||
|
const PROTECTED_PATHS = ["/protected"];
|
||||||
|
|
||||||
|
export function middleware(request: NextRequest) {
|
||||||
|
const { pathname } = request.nextUrl;
|
||||||
|
|
||||||
|
if (PROTECTED_PATHS.some((p) => pathname.startsWith(p))) {
|
||||||
|
const sessionCookie = getSessionCookie(request);
|
||||||
|
if (!sessionCookie) {
|
||||||
|
const loginUrl = new URL("/", request.url);
|
||||||
|
loginUrl.searchParams.set("next", pathname);
|
||||||
|
return NextResponse.redirect(loginUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ["/((?!_next/static|_next/image|favicon.ico|api|.*\\..*).*)"],
|
||||||
|
};
|
||||||
@@ -74,6 +74,7 @@
|
|||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
|
"@vitest/coverage-v8": "^5.0.1",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "16.3.5",
|
"eslint-config-next": "16.3.5",
|
||||||
"husky": "^9.1.7",
|
"husky": "^9.1.7",
|
||||||
|
|||||||
+1
-2
@@ -30,8 +30,7 @@
|
|||||||
"**/*.tsx",
|
"**/*.tsx",
|
||||||
".next/types/**/*.ts",
|
".next/types/**/*.ts",
|
||||||
".next/dev/types/**/*.ts",
|
".next/dev/types/**/*.ts",
|
||||||
"**/*.mts",
|
"**/*.mts"
|
||||||
".next/dev/dev/types/**/*.ts"
|
|
||||||
],
|
],
|
||||||
"exclude": ["node_modules"]
|
"exclude": ["node_modules"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user