Next.js Zero to Advanced #10: Authentication & Authorization
In Part 9 we built a REST API for DigiStore products, and in Part 8 we built admin pages with Server Actions. The problem: until now anyone can create, update and delete products, because Server Actions and Route Handlers are public endpoints. In Part 10 we close that hole. We will build register, login and logout with bcryptjs and a session cookie signed with jose, add proxy.ts, add requireAdmin() to every admin action, then build a "Buy" button that stores an Order and an /orders page that only shows the orders of the logged-in user.
Authentication vs Authorization
These two terms are often mixed up, but they are different:
- Authentication answers "who are you?" (logging in with email and password).
- Authorization answers "what are you allowed to do?" (only an ADMIN may delete products, a user may only see their own orders).
The flow we are going to build:
- The user registers or logs in through a Server Action. The password is checked with bcrypt.
- The server creates a JWT containing
userIdandrole, signs it withSESSION_SECRET, then stores it in an httpOnlysessioncookie. - On every request the server verifies the cookie signature. A cookie tampered with by the user is rejected automatically.
proxy.tsredirects guests away from/adminand/orders(a convenience only).- Every Server Action, Route Handler and sensitive page re-checks the session and the role from the database. This is the real security layer.
Setting Up Dependencies and SESSION_SECRET
We already installed bcryptjs in Part 6 for the seed script. Now add jose to sign and verify JWTs:
npm install joseGenerate a random secret of at least 32 characters. Never make one up yourself or use a guessable word:
openssl rand -base64 32Copy the output into .env (already in .gitignore since Part 5). The example below is only a placeholder:
# .env
DATABASE_URL="postgresql://db_user:YOUR_PASSWORD@localhost:5432/digistore"
SESSION_SECRET="paste-the-openssl-output-here"This secret must never get a
NEXT_PUBLIC_prefix. Variables with that prefix are bundled into browser JavaScript, and anyone who knows the secret can forge an admin session.
Creating lib/session.ts
We keep all session logic in one file. The line import 'server-only' makes the build fail if this file is accidentally imported from a Client Component. Next.js handles this import internally, so installing the server-only package is optional.
// lib/session.ts
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { SignJWT, jwtVerify } from 'jose'
import type { Role } from '@prisma/client'
import { prisma } from '@/lib/prisma'
export const SESSION_COOKIE = 'session'
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000 // 7 days
export type SessionPayload = {
userId: string
role: Role
}
function getSecretKey() {
// TODO: Securely load this value from an environment variable or secrets vault. Do not hardcode.
const secret = process.env.SESSION_SECRET
if (!secret || secret.length < 32) {
throw new Error('SESSION_SECRET is missing or shorter than 32 characters')
}
return new TextEncoder().encode(secret)
}
export async function encrypt(payload: SessionPayload) {
return new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('7d')
.sign(getSecretKey())
}
export async function decrypt(token: string | undefined): Promise<SessionPayload | null> {
if (!token) return null
try {
const { payload } = await jwtVerify<SessionPayload>(token, getSecretKey(), {
algorithms: ['HS256'],
})
return { userId: payload.userId, role: payload.role }
} catch {
return null // token is malformed, expired or forged
}
}
export async function createSession(payload: SessionPayload) {
const token = await encrypt(payload)
const cookieStore = await cookies()
cookieStore.set(SESSION_COOKIE, token, {
httpOnly: true, // not readable by browser JavaScript
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
sameSite: 'lax',
path: '/',
expires: new Date(Date.now() + SESSION_TTL_MS),
})
}
export async function deleteSession() {
const cookieStore = await cookies()
cookieStore.delete(SESSION_COOKIE)
}
export async function getSession() {
const cookieStore = await cookies()
return decrypt(cookieStore.get(SESSION_COOKIE)?.value)
}
// Fresh user data from the database, at most one query per request
export const getCurrentUser = cache(async () => {
const session = await getSession()
if (!session) return null
return prisma.user.findUnique({
where: { id: session.userId },
select: { id: true, name: true, email: true, role: true },
})
})
export async function requireUser() {
const user = await getCurrentUser()
if (!user) redirect('/login')
return user
}
export class AuthError extends Error {
readonly status: 401 | 403
constructor(status: 401 | 403) {
super(status === 401 ? 'Unauthorized' : 'Forbidden')
this.status = status
}
}
export async function requireAdmin() {
const user = await getCurrentUser()
if (!user) throw new AuthError(401)
if (user.role !== 'ADMIN') throw new AuthError(403)
return user
}
export function authErrorResponse(error: unknown) {
if (error instanceof AuthError) {
return Response.json({ error: error.message }, { status: error.status })
}
throw error
}Some important decisions in this file:
- httpOnly stops malicious scripts (XSS) from stealing the cookie. secure makes sure the cookie is only sent over HTTPS in production; on
localhostwe still use HTTP, so the value depends onNODE_ENV. sameSite: 'lax' stops the cookie from being sent on cross-site POSTs, one of the defenses against CSRF. - Minimal payload: only
userIdandrole. A JWT is only signed, not encrypted, so anyone can read its contents. Never put email, passwords or other personal data in it. algorithms: ['HS256']pins the accepted algorithm so tokens with any other algorithm are rejected.requireAdmin()reads the role from the database, not just from the token. If an admin is demoted to USER, their rights disappear immediately even though their old cookie is still valid for 7 days.
Validating the Register and Login Forms
All input from the browser is untrusted, so we validate it on the server with zod, just like productSchema in Part 8. Add these schemas to lib/validation.ts:
// lib/validation.ts (add below productSchema)
export const registerSchema = z.object({
name: z.string().trim().min(2, 'Name must be at least 2 characters').max(80),
email: z.string().trim().toLowerCase().email('Invalid email format'),
password: z
.string()
.min(8, 'Password must be at least 8 characters')
.max(72, 'Password must be at most 72 characters'),
})
export const loginSchema = z.object({
email: z.string().trim().toLowerCase().email(),
password: z.string().min(1).max(72),
})
export const buySchema = z.object({
productId: z.string().min(1).max(64),
})The 72-character limit is not random: bcrypt only processes the first 72 bytes of a password, so we reject longer input instead of silently truncating it.
Server Actions: Register, Login, Logout
// app/actions/auth.ts
'use server'
import bcrypt from 'bcryptjs'
import { redirect } from 'next/navigation'
import { prisma } from '@/lib/prisma'
import { createSession, deleteSession } from '@/lib/session'
import { loginSchema, registerSchema } from '@/lib/validation'
export type AuthFormState =
| { message?: string; errors?: Record<string, string[] | undefined> }
| undefined
const GENERIC_LOGIN_ERROR = 'Incorrect email or password.'
export async function register(
_prevState: AuthFormState,
formData: FormData,
): Promise<AuthFormState> {
const parsed = registerSchema.safeParse({
name: formData.get('name'),
email: formData.get('email'),
password: formData.get('password'),
})
if (!parsed.success) {
return { errors: parsed.error.flatten().fieldErrors }
}
const { name, email, password } = parsed.data
const existing = await prisma.user.findUnique({ where: { email }, select: { id: true } })
if (existing) {
return { message: 'Registration failed. If you already have an account, please log in.' }
}
const passwordHash = await bcrypt.hash(password, 12)
// role is NOT taken from the form: it defaults to USER (schema default)
const user = await prisma.user.create({
data: { name, email, passwordHash },
select: { id: true, role: true },
})
await createSession({ userId: user.id, role: user.role })
redirect('/products')
}
export async function login(
_prevState: AuthFormState,
formData: FormData,
): Promise<AuthFormState> {
const parsed = loginSchema.safeParse({
email: formData.get('email'),
password: formData.get('password'),
})
if (!parsed.success) return { message: GENERIC_LOGIN_ERROR }
const user = await prisma.user.findUnique({
where: { email: parsed.data.email },
select: { id: true, role: true, passwordHash: true },
})
const passwordOk = user
? await bcrypt.compare(parsed.data.password, user.passwordHash)
: false
if (!user || !passwordOk) return { message: GENERIC_LOGIN_ERROR }
await createSession({ userId: user.id, role: user.role })
redirect(user.role === 'ADMIN' ? '/admin/products' : '/products')
}
export async function logout() {
await deleteSession()
redirect('/login')
}Note three things. First, the login error message is always the same ("Incorrect email or password") whether the email is unknown or the password is wrong, so an attacker cannot learn which emails are registered. Second, role is never read from formData; otherwise anyone could add <input name="role" value="ADMIN"> through DevTools. Third, redirect() is called outside any try/catch, because according to the Next.js docs it works by throwing a special error.
Login and Register Pages
The form uses useActionState (like the product form in Part 8) to show error messages and pending state. Because it needs a hook, the form is a separate Client Component:
// app/login/LoginForm.tsx
'use client'
import { useActionState } from 'react'
import { login } from '@/app/actions/auth'
export function LoginForm() {
const [state, formAction, pending] = useActionState(login, undefined)
return (
<form action={formAction} className="space-y-4">
<div>
<label htmlFor="email" className="block text-sm font-medium">Email</label>
<input id="email" name="email" type="email" autoComplete="email" required
className="mt-1 w-full rounded-md border px-3 py-2" />
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium">Password</label>
<input id="password" name="password" type="password" autoComplete="current-password" required
className="mt-1 w-full rounded-md border px-3 py-2" />
</div>
{state?.message && (
<p role="alert" className="text-sm text-red-600">{state.message}</p>
)}
<button type="submit" disabled={pending}
className="w-full rounded-md bg-blue-600 px-4 py-2 font-medium text-white disabled:opacity-50">
{pending ? 'Processing...' : 'Log in'}
</button>
</form>
)
}// app/login/page.tsx
import { Suspense } from 'react'
import type { Metadata } from 'next'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { getCurrentUser } from '@/lib/session'
import { LoginForm } from './LoginForm'
export const metadata: Metadata = { title: 'Log in' }
export default function LoginPage() {
return (
<main className="mx-auto max-w-sm px-4 py-12">
<Suspense fallback={null}>
<RedirectIfLoggedIn />
</Suspense>
<h1 className="mb-6 text-2xl font-bold">Log in to DigiStore</h1>
<LoginForm />
<p className="mt-4 text-sm">
No account yet? <Link href="/register" className="text-blue-600 underline">Register</Link>
</p>
</main>
)
}
// Reads the session cookie, so it renders inside <Suspense> (Cache Components)
async function RedirectIfLoggedIn() {
const user = await getCurrentUser()
if (user) redirect('/products') // already logged in
return null
}Only the small RedirectIfLoggedIn reads the cookie (inside <Suspense>), so the form stays in the static shell. The app/register/page.tsx page and RegisterForm.tsx follow the same pattern (including RedirectIfLoggedIn): add a name input, switch the action to register, use autoComplete="new-password", and show per-field errors under each input, for example {state?.errors?.email?.[0]}. If you built components/ui/Button.tsx in Part 4, use it for the submit button to keep the UI consistent.
User menu in the Header
// components/UserMenu.tsx
import Link from 'next/link'
import { logout } from '@/app/actions/auth'
import { getCurrentUser } from '@/lib/session'
export async function UserMenu() {
const user = await getCurrentUser()
if (!user) return <Link href="/login">Log in</Link>
return (
<div className="flex items-center gap-4 text-sm">
{user.role === 'ADMIN' && <Link href="/admin/products">Admin</Link>}
<Link href="/orders">My Orders</Link>
<form action={logout}>
<button type="submit" className="underline">Log out</button>
</form>
</div>
)
}Render <UserMenu /> inside the Header from Part 4, wrapped in <Suspense>:
// components/Header.tsx
import { Suspense } from 'react'
import Link from 'next/link'
import { buttonClasses } from '@/components/ui/Button'
import { UserMenu } from '@/components/UserMenu'
export function Header() {
return (
<header className="sticky top-0 z-10 border-b border-gray-200 bg-white/90 backdrop-blur">
<nav className="mx-auto flex h-16 max-w-6xl items-center justify-between px-4">
<Link href="/" className="text-lg font-bold text-brand-700">
DigiStore
</Link>
<div className="flex items-center gap-4">
<Link href="/products" className={buttonClasses('ghost', 'sm')}>
Produk
</Link>
<Link href="/products" className={buttonClasses('primary', 'sm', 'hidden sm:inline-flex')}>
Mulai Belanja
</Link>
{/* UserMenu reads cookies, so it must sit inside Suspense */}
<Suspense fallback={<div aria-hidden="true" className="h-5 w-24 animate-pulse rounded bg-gray-200" />}>
<UserMenu />
</Suspense>
</div>
</nav>
</header>
)
}Why the <Suspense>? UserMenu reads cookies() through getCurrentUser(), and cookies only exist at request time. With Cache Components (on since Part 1), Next.js prerenders a static shell of every route at build time, and reading cookies outside a <Suspense> boundary is a build error; since the Header is in the root layout, every page would fail. With the boundary, the rest of the page stays in the static shell and only the user menu streams in per request. Reading cookies does not make the whole page dynamic. We will see this in the build output in Part 11.
proxy.ts: Optimistic Checks
In Next.js 16, the middleware.ts file was renamed to proxy.ts, and the exported function is called proxy. Proxy now uses the Node.js runtime by default. Create the file at the project root (next to the app folder):
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server'
import { SESSION_COOKIE, decrypt } from '@/lib/session'
export async function proxy(request: NextRequest) {
const session = await decrypt(request.cookies.get(SESSION_COOKIE)?.value)
if (!session) {
return NextResponse.redirect(new URL('/login', request.nextUrl))
}
if (request.nextUrl.pathname.startsWith('/admin') && session.role !== 'ADMIN') {
return NextResponse.redirect(new URL('/', request.nextUrl))
}
return NextResponse.next()
}
export const config = {
matcher: ['/admin/:path*', '/orders/:path*'],
}The proxy only verifies the cookie signature, without a database query, because it runs on every matching request, including prefetches. That is why it is called an optimistic check. The Next.js docs stress that the proxy is not a complete authorization solution:
- A Server Action is not its own route. It is sent as a POST to the page where it is used, so an action called from
/products/[slug]never passes through the/adminmatcher. - Our matcher does not cover
/api. Changing the matcher or moving a file can silently remove protection. - The role in the token may be stale. Only the database knows the current role.
requireAdmin() in Every Server Action and Route Handler
Now we fill in the placeholder we left in Part 8. Call requireAdmin() as the first line of every admin action, before reading formData:
// app/admin/products/actions.ts (only the changed parts; everything else stays as in Part 8)
'use server'
import { requireAdmin } from '@/lib/session'
// ...the other imports from Part 8 stay (prisma, productSchema, ProductFormState, DeleteProductState, ...)
export async function createProduct(
_prevState: ProductFormState,
formData: FormData,
): Promise<ProductFormState> {
await requireAdmin() // replaces: // TODO(Part 10): await requireAdmin()
// ...readProductForm, validateProduct and prisma.product.create as in Part 8
}
export async function updateProduct(
id: string,
_prevState: ProductFormState,
formData: FormData,
): Promise<ProductFormState> {
await requireAdmin()
// ...as in Part 8
}
export async function deleteProduct(
_prevState: DeleteProductState,
formData: FormData,
): Promise<DeleteProductState> {
await requireAdmin()
// ...read the id from formData and prisma.product.delete as in Part 8
}The signatures stay exactly as in Part 8, because useActionState depends on them; we only add one line. If the caller is not an admin, requireAdmin() throws an AuthError, so the action stops before touching the database. Regular users never see admin buttons; only someone deliberately calling the action endpoint directly will hit this error.
For the Route Handlers from Part 9 we want a 401/403 JSON response, not an error page. Use authErrorResponse() in POST, PATCH and DELETE. GET stays public because anyone may browse the catalog.
// app/api/products/route.ts
import { authErrorResponse, requireAdmin } from '@/lib/session'
export async function POST(request: Request) {
try {
await requireAdmin()
} catch (error) {
return authErrorResponse(error)
}
// ...parse JSON, productSchema.safeParse, prisma.product.create (Part 9)
}
// Do the same in PATCH and DELETE in app/api/products/[id]/route.tsAdmin pages must check on their own too. For a logged-in user who is not an admin, notFound() hides the fact that the page exists:
// app/admin/products/page.tsx (changes to the Part 8 file)
import { notFound, redirect } from 'next/navigation'
import { getCurrentUser } from '@/lib/session'
// AdminProductsPage stays as in Part 8: a static heading plus <Suspense> around <ProductTable />
async function ProductTable({ searchParams }: { searchParams: SearchParams }) {
const user = await getCurrentUser() // reads cookies: fine here, inside Suspense
if (!user) redirect('/login')
if (user.role !== 'ADMIN') notFound()
const { status } = await searchParams
// ...the rest of ProductTable as in Part 8
}The check sits in ProductTable, inside the <Suspense> from Part 8, not at the top of AdminProductsPage: with Cache Components, reading cookies outside a boundary fails the build. Add the same three lines to EditProductForm on the edit page.
Test the API without a cookie:
curl -i -X POST http://localhost:3000/api/products \
-H "Content-Type: application/json" \
-d '{"title":"Tes","slug":"tes","description":"Coba","price":10000,"category":"EBOOK"}'Result:
HTTP/1.1 401 Unauthorized
content-type: application/json
{"error":"Unauthorized"}The "Buy" Button and the Order Model
The Order model has existed since Part 6. Now we create the buy action (no payment gateway; treat it as a free checkout for the demo):
// app/actions/orders.ts
'use server'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { prisma } from '@/lib/prisma'
import { requireUser } from '@/lib/session'
import { buySchema } from '@/lib/validation'
export async function buyProduct(formData: FormData) {
const user = await requireUser() // userId ALWAYS comes from the session
const parsed = buySchema.safeParse({ productId: formData.get('productId') })
if (!parsed.success) redirect('/products')
const product = await prisma.product.findUnique({
where: { id: parsed.data.productId },
select: { id: true, price: true, published: true },
})
if (!product || !product.published) redirect('/products')
await prisma.order.create({
data: {
userId: user.id,
productId: product.id,
amount: product.price, // price from the database, not the form
},
})
revalidatePath('/orders')
redirect('/orders')
}On the product detail page, add this small form near the price:
// app/products/[slug]/page.tsx
import { buyProduct } from '@/app/actions/orders'
// ...inside the JSX, after the price
<form action={buyProduct}>
<input type="hidden" name="productId" value={product.id} />
<button type="submit" className="rounded-md bg-blue-600 px-4 py-2 font-medium text-white">
Buy {formatRupiah(product.price)}
</button>
</form>The form only sends productId. A hidden input can be changed by anyone, so we validate it and make sure the product exists and is published. What we do not accept from the browser is userId and amount. If both came from the form, an attacker could place orders on behalf of someone else or buy a Rp 500,000 product for Rp 1.
The /orders Page and the Danger of IDOR
// app/orders/page.tsx
import { Suspense } from 'react'
import type { Metadata } from 'next'
import Link from 'next/link'
import { prisma } from '@/lib/prisma'
import { formatRupiah } from '@/lib/format'
import { requireUser } from '@/lib/session'
export const metadata: Metadata = { title: 'My Orders' }
export default function OrdersPage() {
return (
<main className="mx-auto max-w-3xl px-4 py-10">
<h1 className="mb-6 text-2xl font-bold">My Orders</h1>
<Suspense fallback={<p className="text-gray-600">Loading orders...</p>}>
<OrderList />
</Suspense>
</main>
)
}
// Reads the session cookie, so it renders inside <Suspense> (Cache Components)
async function OrderList() {
const user = await requireUser()
const orders = await prisma.order.findMany({
where: { userId: user.id }, // filter MUST come from the session
orderBy: { createdAt: 'desc' },
select: {
id: true,
amount: true,
createdAt: true,
product: { select: { title: true, slug: true } },
},
})
if (orders.length === 0) {
return (
<p className="text-gray-600">
No orders yet. <Link href="/products" className="text-blue-600 underline">Browse products</Link>
</p>
)
}
return (
<ul className="divide-y rounded-lg border">
{orders.map((order) => (
<li key={order.id} className="flex items-center justify-between p-4">
<div>
<Link href={`/products/${order.product.slug}`} className="font-medium">
{order.product.title}
</Link>
<p className="text-sm text-gray-500">
{order.createdAt.toLocaleDateString('id-ID')}
</p>
</div>
<span className="font-semibold">{formatRupiah(order.amount)}</span>
</li>
))}
</ul>
)
}The heading and fallback go into the static shell; requireUser() and the query live in OrderList inside <Suspense>, for the same reason as in the Header. Never put this per-user data in a shared 'use cache' (Part 7).
What is IDOR?
IDOR (Insecure Direct Object Reference) happens when an app fetches data by an ID sent by the user without checking that the data belongs to them. Compare with this wrong version:
// WRONG: do not copy this
export default async function OrdersPage({
searchParams,
}: {
searchParams: Promise<{ userId?: string }>
}) {
const { userId } = await searchParams
const orders = await prisma.order.findMany({ where: { userId } })
// ...
}Anyone can simply change ?userId= in the URL to see someone else's orders. Worse, if the parameter is missing, userId is undefined and Prisma ignores that filter, so all orders are returned. The rule is simple: the user's identity always comes from the session on the server. For a detail page such as /orders/[id], use prisma.order.findFirst({ where: { id, userId: user.id } }), not findUnique({ where: { id } }).
Testing the Flow
- Run
npm run devand open/orderswithout logging in. The proxy redirects you to/login. - Register a new account at
/register, open a product, click "Buy", then make sure the order shows up in/orders. - Still as a regular user, open
/admin/products. You are redirected to the home page. - Open DevTools, the Application tab, then Cookies. The
sessioncookie is marked HttpOnly. Change one character and reload: you are treated as logged out. - Log out, then log in as the admin from the Part 6 seed (password from
SEED_ADMIN_PASSWORD) and make sure product CRUD still works.
Common Mistakes
- Relying only on the proxy. The proxy is a convenience. Authorization must be repeated in every Server Action, Route Handler and sensitive page.
- Trusting
userId,roleor prices from the client. Everything that comes from a form, URL or JSON body can be manipulated. - Storing plain-text passwords or using fast hashes such as MD5/SHA-256. Use bcrypt, which is deliberately slow.
- Forgetting
httpOnlyor storing the token inlocalStorage, which lets XSS steal it. - Writing the secret in code or giving it a
NEXT_PUBLIC_prefix. - Overly specific login messages such as "email not found", which leak which emails are registered.
Notes for Production
This implementation is fine for learning and small projects, but before handling real money, consider:
- Rate limiting on login and register (for example at most 5 attempts per minute per IP and per email) to slow down brute force. This can be done with Redis or your hosting platform's firewall features.
- Email verification and password reset.
- A battle-tested auth library if you need social login, MFA or session revocation.
Exercises
- Create
components/BuyButton.tsx(a Client Component) that usesuseFormStatusfromreact-domto show "Processing..." and disable the button while the purchase runs. - Build
app/orders/[id]/page.tsxshowing a single order. Make sure user A gets a 404 when opening an order ID that belongs to user B. - Add a
?next=/ordersparameter to the login page so users return to where they came from after logging in. Accept only relative paths starting with/(and not//) to prevent open redirects.
Summary
- Passwords are hashed with bcrypt; the session is a JWT signed with
josein an httpOnly, secure (production), sameSite=lax cookie. SESSION_SECRETcomes from an environment variable and is never sent to the browser.proxy.ts(the replacement for middleware in Next.js 16) only performs optimistic redirects.requireAdmin()is re-run in every admin Server Action and Route Handler, with the role read from the database.- Orders and the
/orderspage always use theuserIdfrom the session, which protects against IDOR.
DigiStore is now protected from unauthorized access. In Part 11 we will get it ready for production: tidy error handling, SEO with generateMetadata, a sitemap, robots.txt, reading the npm run build output, and security headers.
Related articles
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #8: Composer, Namespaces, PSR-4 Autoloading & Exceptions
Structure real PHP projects: organize code with namespaces, manage dependencies with Composer, autoload classes with PSR-4, and handle errors cleanly with exceptions.
Ruby on Rails Zero to Advanced #8: Forms, Strong Parameters & Full CRUD
Build a complete CRUD feature by hand with form_with and strong parameters, then compare it with what rails generate scaffold gives you for free.