The first phase is not a feature. It is a floor.
If the app cannot boot without the right environment, if the database client is a mystery, or if nobody can tell whether Neon is reachable, every later bug is harder to find. So we build the smallest possible Next.js app that:
- installs and typechecks,
- refuses to boot with bad config,
- connects to Neon,
- answers
/api/healthhonestly.
No shelf yet. No auth yet. No items. Just a floor you can stand on.
Create the app
- 1
Scaffold Next.js
Run create-next-app and choose TypeScript, ESLint, Tailwind, the src directory, the App Router, Turbopack, and the @/* import alias.
npx create-next-app@latest kedai cd kedaiAs of October 2026, the current stable line is Next.js 16.4. Turbopack is the default bundler.
- 2
Install the real dependencies
Database, validation, storage, image processing, email, auth, and the server-only guard.
npm install drizzle-orm pg zod @aws-sdk/client-s3 @aws-sdk/s3-request-presigner sharp resend @react-email/components @node-rs/argon2 server-only npm install -D drizzle-kit @types/pg dotenv tsx vitest - 3
Add the scripts
Migrations, admin seeding, tests, and a typecheck. You will use these every phase.
"db:generate": "drizzle-kit generate", "db:migrate": "drizzle-kit migrate", "db:studio": "drizzle-kit studio", "seed:admin": "tsx src/db/seed.ts", "test": "vitest run", "typecheck": "tsc --noEmit"Keep the generated lockfile. Do not hand-edit it.
- 4
Create the empty folders
They give the app a shape before the files exist.
src/app/(site) src/app/admin src/app/api src/components/{site,admin,ui} src/db src/lib/{auth,storage,email,reservations,items,validation} src/emails tests - 5
Create an empty schema module
The database client imports the schema. Leave it empty for one lesson; the tables arrive in phase 2.
// src/db/schema.ts export {};
The repo map
Kedai repo structure
kedai/
├─ src/
one Next.js app
│ ├─ app/
routes, layouts, pages
│ │ ├─ (site)/
shelf, item, reservation receipt
│ │ ├─ admin/
login + protected back room
│ │ └─ api/
health, presign, expiry cron
│ ├─ components/
site, admin, ui
│ ├─ db/
schema, client, migrations, seed
│ ├─ lib/
config, auth, storage, email, reservations
│ ├─ emails/
React Email templates
│ └─ proxy.ts
Next 16 proxy (was middleware)
├─ drizzle.config.ts
drizzle-kit config
├─ .env.local
real secrets — never committed
├─ .env.example
every setting, no values
├─ master-plan-kedai.md
the blueprint
└─ tests/
vitest + a test Neon branch
Config that refuses to boot
Create src/lib/config.ts. Every server module reads config through this file, never process.env directly.
import "server-only";
import { z } from "zod";
const EnvSchema = z.object({
DATABASE_URL: z.string().url(),
PUBLIC_BASE_URL: z.string().url(),
SHOP_NAME: z.string().min(1).default("Kedai"),
SHOP_LOCATION: z.string().min(1),
PICKUP_INSTRUCTIONS: z.string().min(1),
DEFAULT_CURRENCY: z.string().length(3).default("MYR"),
RESERVATION_HOURS: z.coerce.number().int().min(1).max(168).default(24),
R2_ACCOUNT_ID: z.string().min(1),
R2_ACCESS_KEY_ID: z.string().min(1),
R2_SECRET_ACCESS_KEY: z.string().min(1),
R2_BUCKET: z.string().min(1),
R2_PUBLIC_BASE_URL: z.string().url(),
RESEND_API_KEY: z.string().startsWith("re_"),
EMAIL_FROM: z.string().min(1),
SHOP_EMAIL: z.string().email(),
DISABLE_EMAIL_SENDS: z
.enum(["true", "false"])
.default("false")
.transform((value) => value === "true"),
WHATSAPP_NUMBER: z.string().regex(/^\d{8,15}$/),
IP_HASH_SECRET: z.string().min(32),
CRON_SECRET: z.string().min(16),
ADMIN_EMAIL: z.string().email().optional(),
ADMIN_PASSWORD: z.string().min(12).optional(),
});
let cached: z.infer<typeof EnvSchema> | undefined;
export function getEnv() {
if (!cached) {
const parsed = EnvSchema.safeParse(process.env);
if (!parsed.success) {
console.error("Invalid environment variables", parsed.error.flatten().fieldErrors);
throw new Error("Invalid environment variables");
}
cached = parsed.data;
}
return cached;
}
Three details matter:
server-onlymakes the build fail if a Client Component ever imports this file. Secrets do not belong in the browser.- Lazy parsing (
getEnv()instead ofexport const env = ...) avoids breakingnext buildwhen a route is not evaluated. The app still refuses at runtime. z.enum(["true","false"]).transform(...)is deliberate.z.coerce.boolean()would turn the string"false"intotrue, which is a classic environment-variable bug.
The database client
Create src/db/client.ts:
import "server-only";
import { attachDatabasePool } from "@vercel/functions";
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import * as schema from "@/db/schema";
import { getEnv } from "@/lib/config";
const globalForDb = globalThis as unknown as { __kedaiPool?: Pool };
const pool =
globalForDb.__kedaiPool ??
new Pool({ connectionString: getEnv().DATABASE_URL });
if (process.env.NODE_ENV !== "production") {
globalForDb.__kedaiPool = pool;
}
if (process.env.VERCEL === "1") {
attachDatabasePool(pool);
}
export const db = drizzle({ client: pool, schema });
Why this shape:
- One pool, reused. Next.js dev mode reloads modules; without the global cache you can leak connections on every edit.
attachDatabasePoolis Vercel’s helper for closing idle connections before a function suspends. It is only called on Vercel; local Postgres or Neon does not need it.- Use the pooled Neon host (
...-pooler...) inDATABASE_URL. Serverless functions scale out; a direct host will run out of connections. - Transactions work.
pggives us the interactive transactions the reservation state machine needs.
The health route
Create src/app/api/health/route.ts:
import { sql } from "drizzle-orm";
import { db } from "@/db/client";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await db.execute(sql`select 1`);
return Response.json({ ok: true, db: true });
} catch {
return Response.json({ ok: false, db: false }, { status: 503 });
}
}
No stack traces, no connection string, no table names. It answers one question: can this app reach its database right now?
The proxy is not the lock
Next.js 16 renamed Middleware to Proxy. Create src/proxy.ts:
import { NextResponse, type NextRequest } from "next/server";
export function proxy(request: NextRequest) {
const isAdmin = request.nextUrl.pathname.startsWith("/admin");
const isLogin = request.nextUrl.pathname.startsWith("/admin/login");
if (isAdmin && !isLogin && !request.cookies.has("kedai_admin")) {
const url = request.nextUrl.clone();
url.pathname = "/admin/login";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*"],
};
This is an optimistic redirect, not authorization. It only checks whether a cookie exists; it cannot tell whether the session is valid, expired, or revoked. The real check is requireAdmin() in lesson 6, called by every admin page, Server Action, and Route Handler.
The environment file
Create .env.example with every setting, and .env.local with real values. .env.local is gitignored; .env.example is committed.
PUBLIC_BASE_URL=http://localhost:3000
SHOP_NAME=Kedai
SHOP_LOCATION=Petaling Jaya
PICKUP_INSTRUCTIONS=Pickup by arrangement. Postage can be quoted on WhatsApp.
DEFAULT_CURRENCY=MYR
RESERVATION_HOURS=24
DATABASE_URL=postgresql://...-pooler...
TEST_DATABASE_URL=postgresql://...
[email protected]
ADMIN_PASSWORD=change-me-12-chars
IP_HASH_SECRET=replace-with-32-random-characters
CRON_SECRET=replace-with-16-random-characters
RESEND_API_KEY=re_...
EMAIL_FROM="Kedai <[email protected]>"
[email protected]
DISABLE_EMAIL_SENDS=false
WHATSAPP_NUMBER=60123456789
R2_ACCOUNT_ID=
R2_ACCESS_KEY_ID=
R2_SECRET_ACCESS_KEY=
R2_BUCKET=kedai
R2_PUBLIC_BASE_URL=https://photos.yourdomain.com
drizzle.config.ts
Create this now; lesson 5 uses it.
import { config } from "dotenv";
import { defineConfig } from "drizzle-kit";
config({ path: ".env.local" });
export default defineConfig({
schema: "./src/db/schema.ts",
out: "./src/db/migrations",
dialect: "postgresql",
casing: "snake_case",
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});
Drizzle Kit does not load Next.js’s .env.local automatically. The dotenv call is what makes npm run db:generate see the same database URL the app sees.
The boot check
Run these in order. Do not skip one because it “looks fine”.
npm run typecheck
npm run dev
Open http://localhost:3000/api/health. You want:
{ "ok": true, "db": true }
Then try to break it:
- Stop the dev server.
- Temporarily remove
DATABASE_URLfrom.env.local. - Start the app again and open a page that calls
getEnv().
You should get a clear “Invalid environment variables” error, not a random undefined later. Put the value back.
Your mission
the plan's verify stepGet the empty app to boot, the typecheck to pass, and /api/health to return ok:true and db:true. Then break the config on purpose and confirm the error is clear. Paste the health JSON into your notes.
No shelf, no auth, no photos. If the floor is solid, the rest of the house is easier.
Recap
Phase 1 is a floor: install, typecheck, config, database client, health route.
One config module validates the environment with Zod and refuses to boot on bad values.
The pg pool is global in dev and attached to Vercel's lifecycle in production.
proxy.ts is Next 16's renamed middleware; it is an optimistic redirect, not authorization.
The health route is the first honest signal: can the app reach Neon right now?
Next: the database. The item is the unit of stock, and the partial unique index is the rule that keeps one chair from being sold twice.
Up next
The item is the unit of stock
Phase 2 — schema, migrations, integer money, and the constraints that make a double sale impossible.