Next.js Zero to Advanced #8: Mutating Data with Server Actions & Forms
In Part 7 the DigiStore pages started reading real data from PostgreSQL. But adding a product still means opening Prisma Studio. In Part 8 we build an admin area at /admin/products to create, edit, and delete products. We use Server Actions (server functions called straight from a form), zod validation in lib/validation.ts, useActionState for per-field errors and a pending state, and updateTag, revalidatePath, and redirect so the UI is fresh right after data changes.
Important: until Part 10 these admin pages and actions are not protected by a login. A Server Action is a public HTTP endpoint: anyone who knows how to call it can change your data. Work through this part on
localhostonly, and do not deploy before Part 10 addsrequireAdmin().
What Is a Server Action?
A Server Action is an async function marked with the 'use server' directive. It always runs on the server, yet you can pass it straight to a <form>'s action prop. When the form is submitted, React sends the FormData to the server in a POST request, runs the function, and Next.js returns the updated UI in a single round trip. No hand-written API or fetch needed.
That has a security consequence: because it can be called via POST, a Server Action is a public endpoint. Next.js helps with a CSRF check (the Origin header is compared with Host), but three things remain our job:
- Validate every input on the server. HTML validation like
requiredorminis easy to bypass. - Check authorization inside every action. Not only on the page, because an action can be called without ever opening the page. We add this in Part 10.
- Never return internal error details to the client.
The files we are going to create:
app/admin/products/
βββ actions.ts # Server Actions: create, update, delete
βββ page.tsx # product table
βββ new/page.tsx # create form
βββ [id]/edit/page.tsx # edit form
components/admin/
βββ ProductForm.tsx # Client Component, useActionState
βββ DeleteProductButton.tsx
lib/
βββ validation.ts # zod productSchema
βββ db-errors.ts # Prisma error helperValidation with zod
Install zod:
npm install zodThen create lib/validation.ts. The code uses core zod APIs (z.object, z.string, z.number, z.enum, refine, safeParse) that behave the same in zod 3.25 and zod 4.
// lib/validation.ts
import { z } from 'zod'
// Allowed: a local file in /public (e.g. /products/cover.jpg) or the remote
// prefix allowed by images.remotePatterns in next.config.ts (Part 4)
const REMOTE_IMAGE_PREFIX = 'https://cdn.example.com/digistore/'
function isAllowedImageUrl(value: string) {
if (value.startsWith('/') && !value.startsWith('//')) {
return /^[\w./-]+$/.test(value) && !value.includes('..')
}
try {
return new URL(value).href.startsWith(REMOTE_IMAGE_PREFIX)
} catch {
return false
}
}
export const productSchema = z.object({
title: z
.string()
.trim()
.min(3, 'Judul minimal 3 karakter')
.max(120, 'Judul maksimal 120 karakter'),
slug: z
.string()
.trim()
.toLowerCase()
.min(3, 'Slug minimal 3 karakter')
.max(80, 'Slug maksimal 80 karakter')
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'Slug hanya boleh huruf kecil, angka, dan tanda hubung'),
description: z
.string()
.trim()
.min(20, 'Deskripsi minimal 20 karakter')
.max(5000, 'Deskripsi maksimal 5000 karakter'),
price: z
.number({ message: 'Harga harus berupa angka' })
.int('Harga harus bilangan bulat')
.min(0, 'Harga tidak boleh negatif')
.max(100_000_000, 'Harga terlalu besar'),
category: z.enum(['EBOOK', 'SOURCE_CODE', 'TEMPLATE'], {
message: 'Pilih kategori yang valid',
}),
imageUrl: z
.string()
.trim()
.max(500, 'URL terlalu panjang')
.refine(isAllowedImageUrl, 'Gunakan path lokal (/products/...) atau URL dari cdn.example.com/digistore/')
.optional(),
published: z.boolean().optional(),
})
export type ProductInput = z.infer<typeof productSchema>Some design decisions:
trim()andtoLowerCase()normalise input before checking it, so " Ebook-Next " becomesebook-next.priceuses a strictz.number(). We convert form text to a number ourselves in the action, so the same schema can be reused for the JSON API in Part 9.- The
categoryvalues match the PrismaCategoryenum exactly. imageUrlaccepts only two forms: a local path from thepublicfolder (like/products/ebook-belajar-nextjs.jpgin the Part 6 seed), or a URL matchingimages.remotePatternsfrom Part 4 (https://cdn.example.com/digistore/...). The reason:next/imagethrows for hosts that are not configured, and we do not want one bad URL to break the storefront. If you changeremotePatterns, updateREMOTE_IMAGE_PREFIXtoo.- Keys not in the schema, such as
idorcreatedAt, are stripped byz.objectautomatically. That protects against mass assignment.
In the same file, add the form state types and a helper that turns a zod error into per-field messages:
// lib/validation.ts (continued)
// Raw form values, sent back to the form when validation fails
export type ProductFormValues = {
title: string
slug: string
description: string
price: string
category: string
imageUrl: string
published: boolean
}
export type ProductFormState = {
message?: string
fieldErrors?: Record<string, string[]>
values?: ProductFormValues
}
export type DeleteProductState = {
error?: string
}
// { title: ['Judul minimal 3 karakter'], price: [...] }
export function toFieldErrors(error: z.ZodError): Record<string, string[]> {
const fieldErrors: Record<string, string[]> = {}
for (const issue of error.issues) {
const key = issue.path.length > 0 ? String(issue.path[0]) : 'form'
;(fieldErrors[key] ??= []).push(issue.message)
}
return fieldErrors
}A Prisma error helper
Some database errors are normal conditions that deserve a friendly message: a duplicate slug (P2002), a product that was already deleted (P2025), or a product still referenced by orders (P2003). Create lib/db-errors.ts:
// lib/db-errors.ts
import { Prisma } from '@prisma/client'
// P2002 = unique constraint, P2003 = foreign key, P2025 = record not found
export function getPrismaErrorCode(error: unknown): string | null {
return error instanceof Prisma.PrismaClientKnownRequestError ? error.code : null
}Also add two admin queries to lib/products.ts. Both are deliberately not 'use cache': admins must always see current data, including hidden products.
// lib/products.ts (add below the Part 7 functions)
// Admin queries: no 'use cache'. Admins need fresh data,
// including unpublished products.
export async function getAdminProducts() {
return prisma.product.findMany({
select: {
id: true,
title: true,
slug: true,
price: true,
category: true,
published: true,
},
orderBy: { updatedAt: 'desc' },
})
}
export async function getProductById(id: string) {
return prisma.product.findUnique({
where: { id },
select: {
id: true,
title: true,
slug: true,
description: true,
price: true,
category: true,
imageUrl: true,
published: true,
},
})
}Writing the Server Actions
Create app/admin/products/actions.ts. The 'use server' directive on the first line turns every exported async function into a Server Action.
// app/admin/products/actions.ts
'use server'
import { revalidatePath, updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
import { prisma } from '@/lib/prisma'
import { getPrismaErrorCode } from '@/lib/db-errors'
import {
productSchema,
toFieldErrors,
type DeleteProductState,
type ProductFormState,
type ProductFormValues,
} from '@/lib/validation'
function readProductForm(formData: FormData): ProductFormValues {
const text = (name: string) => {
const value = formData.get(name)
return typeof value === 'string' ? value : ''
}
return {
title: text('title'),
slug: text('slug'),
description: text('description'),
price: text('price'),
category: text('category'),
imageUrl: text('imageUrl'),
published: formData.get('published') === 'on',
}
}
function validateProduct(values: ProductFormValues) {
return productSchema.safeParse({
...values,
price: values.price.trim() === '' ? Number.NaN : Number(values.price),
imageUrl: values.imageUrl.trim() === '' ? undefined : values.imageUrl,
})
}
function refreshProductPages() {
updateTag('products') // expire the 'use cache' data from Part 7
revalidatePath('/admin/products') // refresh the admin table
}readProductForm pulls raw values from FormData. A checked checkbox sends "on"; an unchecked one sends nothing. validateProduct converts the price to a number (an empty string becomes NaN so zod rejects it) and turns an empty URL into undefined.
refreshProductPages shows how Next.js refreshes caches after a mutation:
| Function | What it does in DigiStore |
|---|---|
updateTag('products') | Immediately expires all products-tagged data from Part 7 (list, detail, featured). The next request waits for fresh data, so the admin sees the change right away. Server Actions only. |
revalidatePath('/admin/products') | Marks the admin page for re-rendering and refreshes the browser's router cache. |
redirect(...) | Navigates elsewhere after success. redirect works by throwing a special exception, so call it outside try/catch and after revalidating. |
Create
export async function createProduct(
_prevState: ProductFormState,
formData: FormData,
): Promise<ProductFormState> {
// TODO(Part 10): await requireAdmin()
// Until then this action is a PUBLIC HTTP endpoint. Do not deploy it yet.
const values = readProductForm(formData)
const parsed = validateProduct(values)
if (!parsed.success) {
return {
message: 'Periksa kembali isian yang ditandai.',
fieldErrors: toFieldErrors(parsed.error),
values,
}
}
try {
await prisma.product.create({ data: parsed.data })
} catch (error) {
if (getPrismaErrorCode(error) === 'P2002') {
return { fieldErrors: { slug: ['Slug sudah dipakai produk lain'] }, values }
}
console.error('createProduct failed', error)
return { message: 'Gagal menyimpan produk. Coba lagi.', values }
}
refreshProductPages()
redirect('/admin/products?status=created')
}The pattern is always the same: read β validate β save β revalidate β redirect. Expected errors (failed validation, duplicate slug) are returned as values, not thrown, so the form can display them. Unexpected errors are logged on the server while the user sees a generic message. Note the TODO(Part 10) comment: that is where await requireAdmin() goes.
Update
The update action needs the product id. We will "bind" the id with .bind() on the edit page, so it becomes the first argument.
export async function updateProduct(
id: string,
_prevState: ProductFormState,
formData: FormData,
): Promise<ProductFormState> {
// TODO(Part 10): await requireAdmin()
// Until then this action is a PUBLIC HTTP endpoint. Do not deploy it yet.
const values = readProductForm(formData)
const parsed = validateProduct(values)
if (!parsed.success) {
return {
message: 'Periksa kembali isian yang ditandai.',
fieldErrors: toFieldErrors(parsed.error),
values,
}
}
try {
await prisma.product.update({
where: { id },
data: {
...parsed.data,
imageUrl: parsed.data.imageUrl ?? null, // empty field removes the image
},
})
} catch (error) {
const code = getPrismaErrorCode(error)
if (code === 'P2002') {
return { fieldErrors: { slug: ['Slug sudah dipakai produk lain'] }, values }
}
if (code === 'P2025') {
return { message: 'Produk tidak ditemukan. Mungkin sudah dihapus.', values }
}
console.error('updateProduct failed', error)
return { message: 'Gagal menyimpan perubahan. Coba lagi.', values }
}
refreshProductPages()
redirect('/admin/products?status=updated')
}A bound value still travels through the client, so do not treat it as trusted. Prisma returns P2025 if the id does not exist, and in Part 10 the admin check ensures only admins can change products.
Delete
export async function deleteProduct(
_prevState: DeleteProductState,
formData: FormData,
): Promise<DeleteProductState> {
// TODO(Part 10): await requireAdmin()
// Until then this action is a PUBLIC HTTP endpoint. Do not deploy it yet.
const id = formData.get('id')
if (typeof id !== 'string' || id === '') {
return { error: 'ID produk tidak valid.' }
}
try {
await prisma.product.delete({ where: { id } })
} catch (error) {
const code = getPrismaErrorCode(error)
if (code === 'P2025') return { error: 'Produk sudah tidak ada.' }
if (code === 'P2003') {
return { error: 'Produk sudah punya pesanan. Nonaktifkan saja (hilangkan centang Tampilkan).' }
}
console.error('deleteProduct failed', error)
return { error: 'Gagal menghapus produk.' }
}
refreshProductPages()
return {}
}In our schema, Order has a required relation to Product with no onDelete, so PostgreSQL refuses to delete a product that already has orders (P2003). That is the right behaviour, since transaction history must not disappear. The fix is to hide the product with published: false.
The Form with useActionState
The form must show per-field errors and a "saving" state, so it is a Client Component. React 19's useActionState(action, initialState) returns [state, formAction, pending]: state is the action's last return value, formAction goes on <form action>, and pending is true while the action runs.
// components/admin/ProductForm.tsx
'use client'
import { useActionState, type InputHTMLAttributes } from 'react'
import { Button } from '@/components/ui/Button'
import { CATEGORY_LABELS } from '@/lib/format'
import type { ProductFormState, ProductFormValues } from '@/lib/validation'
type ProductFormProps = {
action: (state: ProductFormState, formData: FormData) => Promise<ProductFormState>
initialValues?: ProductFormValues
submitLabel: string
}
const emptyValues: ProductFormValues = {
title: '',
slug: '',
description: '',
price: '',
category: 'EBOOK',
imageUrl: '',
published: true,
}
const initialState: ProductFormState = {}
export function ProductForm({ action, initialValues = emptyValues, submitLabel }: ProductFormProps) {
const [state, formAction, pending] = useActionState(action, initialState)
const values = state.values ?? initialValues
const errors = state.fieldErrors ?? {}
return (
<form action={formAction} noValidate className="mt-6 space-y-5">
{state.message && (
<p role="alert" className="rounded-lg bg-red-50 p-3 text-sm text-red-700">
{state.message}
</p>
)}
<Field label="Judul" name="title" defaultValue={values.title} errors={errors.title} />
<Field
label="Slug (untuk URL)"
name="slug"
defaultValue={values.slug}
errors={errors.slug}
placeholder="contoh: ebook-belajar-nextjs"
/>
<div>
<label htmlFor="description" className="block text-sm font-medium">Deskripsi</label>
<textarea
id="description"
name="description"
rows={6}
defaultValue={values.description}
aria-invalid={errors.description ? true : undefined}
aria-describedby={errors.description ? 'description-error' : undefined}
className="mt-1 w-full rounded-lg border px-3 py-2"
/>
<FieldError id="description-error" errors={errors.description} />
</div>
<Field
label="Harga (Rp)"
name="price"
type="number"
inputMode="numeric"
min={0}
step={1}
defaultValue={values.price}
errors={errors.price}
/>
<div>
<label htmlFor="category" className="block text-sm font-medium">Kategori</label>
<select
id="category"
name="category"
defaultValue={values.category}
aria-invalid={errors.category ? true : undefined}
aria-describedby={errors.category ? 'category-error' : undefined}
className="mt-1 w-full rounded-lg border px-3 py-2"
>
{Object.entries(CATEGORY_LABELS).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
<FieldError id="category-error" errors={errors.category} />
</div>
<Field
label="URL gambar (opsional)"
name="imageUrl"
inputMode="url"
defaultValue={values.imageUrl}
errors={errors.imageUrl}
placeholder="/products/cover.jpg"
/>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="published" defaultChecked={values.published} />
Tampilkan di toko
</label>
<Button type="submit" disabled={pending}>
{pending ? 'Menyimpan...' : submitLabel}
</Button>
</form>
)
}
type FieldProps = InputHTMLAttributes<HTMLInputElement> & {
label: string
name: string
errors?: string[]
}
function Field({ label, name, errors, ...inputProps }: FieldProps) {
const errorId = `${name}-error`
return (
<div>
<label htmlFor={name} className="block text-sm font-medium">{label}</label>
<input
id={name}
name={name}
aria-invalid={errors ? true : undefined}
aria-describedby={errors ? errorId : undefined}
className="mt-1 w-full rounded-lg border px-3 py-2"
{...inputProps}
/>
<FieldError id={errorId} errors={errors} />
</div>
)
}
function FieldError({ id, errors }: { id: string; errors?: string[] }) {
if (!errors?.length) return null
return (
<p id={id} className="mt-1 text-sm text-red-600">
{errors[0]}
</p>
)
}Details that are easy to miss (the UI text stays in Indonesian because DigiStore targets Indonesian buyers):
- React 19 resets the form after an action completes. Without handling it, the user's input disappears every time validation fails. That is why the action returns
valuesand the form usesdefaultValue={values.title}. noValidateturns off the browser's built-in messages so the server's messages show consistently. Server validation is required either way.aria-invalidandaria-describedbylink each input to its error message, so screen readers announce the error.- The button is disabled while
pending, so the form cannot be submitted twice.
The Admin Pages
Create product
// app/admin/products/new/page.tsx
import Link from 'next/link'
import { ProductForm } from '@/components/admin/ProductForm'
import { createProduct } from '@/app/admin/products/actions'
export default function NewProductPage() {
return (
<main className="mx-auto max-w-2xl px-4 py-8">
<Link href="/admin/products" className="text-sm underline">β Kembali</Link>
<h1 className="mt-4 text-2xl font-bold">Produk Baru</h1>
<ProductForm action={createProduct} submitLabel="Simpan produk" />
</main>
)
}A Server Action can be imported in a Server Component and passed as a prop to a Client Component.
Edit product
// app/admin/products/[id]/edit/page.tsx
import { Suspense } from 'react'
import Link from 'next/link'
import { notFound } from 'next/navigation'
import { ProductForm } from '@/components/admin/ProductForm'
import { updateProduct } from '@/app/admin/products/actions'
import { getProductById } from '@/lib/products'
type Params = Promise<{ id: string }>
export default function EditProductPage({ params }: { params: Params }) {
return (
<main className="mx-auto max-w-2xl px-4 py-8">
<Link href="/admin/products" className="text-sm underline">β Kembali</Link>
<h1 className="mt-4 text-2xl font-bold">Edit Produk</h1>
<Suspense fallback={<p className="mt-6 text-gray-600">Memuat produk...</p>}>
<EditProductForm params={params} />
</Suspense>
</main>
)
}
async function EditProductForm({ params }: { params: Params }) {
const { id } = await params
const product = await getProductById(id)
if (!product) notFound()
const updateProductWithId = updateProduct.bind(null, product.id)
return (
<ProductForm
action={updateProductWithId}
submitLabel="Simpan perubahan"
initialValues={{
title: product.title,
slug: product.slug,
description: product.description,
price: String(product.price),
category: product.category,
imageUrl: product.imageUrl ?? '',
published: product.published,
}}
/>
)
}As in Part 7, params is read inside <Suspense>. updateProduct.bind(null, product.id) creates a new action with the id pre-filled, so its shape matches what useActionState expects.
Delete button with confirmation
// components/admin/DeleteProductButton.tsx
'use client'
import { useActionState } from 'react'
import { deleteProduct } from '@/app/admin/products/actions'
import type { DeleteProductState } from '@/lib/validation'
const initialState: DeleteProductState = {}
export function DeleteProductButton({ id, title }: { id: string; title: string }) {
const [state, formAction, pending] = useActionState(deleteProduct, initialState)
return (
<form
action={formAction}
onSubmit={(event) => {
if (!window.confirm(`Hapus "${title}"? Tindakan ini tidak bisa dibatalkan.`)) {
event.preventDefault()
}
}}
>
<input type="hidden" name="id" value={id} />
<button
type="submit"
disabled={pending}
className="text-sm font-medium text-red-600 hover:underline disabled:opacity-50"
>
{pending ? 'Menghapus...' : 'Hapus'}
</button>
{state.error && (
<p role="alert" className="mt-1 text-xs text-red-600">{state.error}</p>
)}
</form>
)
}onSubmit runs before the action. If the user clicks "Cancel" in the confirm dialog, event.preventDefault() stops the submission and the action is never called. Errors such as P2003 appear right below the button.
The product table
// app/admin/products/page.tsx
import { Suspense } from 'react'
import Link from 'next/link'
import { DeleteProductButton } from '@/components/admin/DeleteProductButton'
import { formatCategory, formatRupiah } from '@/lib/format'
import { getAdminProducts } from '@/lib/products'
type SearchParams = Promise<Record<string, string | string[] | undefined>>
export default function AdminProductsPage({ searchParams }: { searchParams: SearchParams }) {
return (
<main className="mx-auto max-w-6xl px-4 py-8">
<div className="flex flex-wrap items-center justify-between gap-4">
<h1 className="text-2xl font-bold">Kelola Produk</h1>
<Link
href="/admin/products/new"
className="rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white"
>
+ Produk baru
</Link>
</div>
<Suspense fallback={<p className="mt-6 text-gray-600">Memuat produk...</p>}>
<ProductTable searchParams={searchParams} />
</Suspense>
</main>
)
}
async function ProductTable({ searchParams }: { searchParams: SearchParams }) {
const { status } = await searchParams
const statusMessage =
status === 'created' ? 'Produk berhasil dibuat.'
: status === 'updated' ? 'Perubahan berhasil disimpan.'
: null
const products = await getAdminProducts()
return (
<>
{statusMessage && (
<p role="status" className="mt-6 rounded-lg bg-green-50 p-3 text-sm text-green-800">
{statusMessage}
</p>
)}
{products.length === 0 ? (
<p className="mt-6 text-gray-600">
Belum ada produk. <Link href="/admin/products/new" className="underline">Tambah produk pertama</Link>.
</p>
) : (
<div className="mt-6 overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="border-b text-gray-500">
<tr>
<th className="py-2">Judul</th>
<th>Kategori</th>
<th>Harga</th>
<th>Status</th>
<th><span className="sr-only">Aksi</span></th>
</tr>
</thead>
<tbody>
{products.map((product) => (
<tr key={product.id} className="border-b">
<td className="py-3 font-medium">{product.title}</td>
<td>{formatCategory(product.category)}</td>
<td>{formatRupiah(product.price)}</td>
<td>{product.published ? 'Tampil' : 'Disembunyikan'}</td>
<td>
<div className="flex items-start gap-4">
<Link href={`/admin/products/${product.id}/edit`} className="text-sm underline">
Edit
</Link>
<DeleteProductButton id={product.id} title={product.title} />
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
)
}The success banner is driven by ?status=, but only two known values are recognised. Text from the URL is never rendered as-is. The table is wrapped in overflow-x-auto so it stays usable on phones.
Trying the Flow
- Open
http://localhost:3000/admin/products. Result: a table with the 6 seeded products. - Click "+ Produk baru" (new product), leave every field empty, and submit. Result: the message "Periksa kembali isian yang ditandai." (please check the highlighted fields) plus a red message under each field.
- Fill in a title, use a slug that another product already has (for example
ebook-belajar-nextjs), and submit. Result: the error "Slug sudah dipakai produk lain" (slug already taken), and the other fields keep their values. - Fix the slug and submit. Result: you land on the table with the green banner "Produk berhasil dibuat." Open
/productsin another tab: the new product appears immediately thanks toupdateTag. - Edit that product, uncheck "Tampilkan di toko" (show in store), and save. Result: it disappears from
/productsbut stays in the admin table. - Click Hapus (delete) and choose Cancel. Result: nothing happens. Repeat and choose OK. Result: the row disappears.
Common Mistakes
- Calling
redirect()insidetry.redirectthrows a special exception that yourcatchwill swallow. Call it after thetry/catchblock. - Forgetting to revalidate. The data is saved, but the store still shows the old cache. Call
updateTag(orrevalidatePath) beforeredirect. - Relying on HTML validation only.
requiredandminare trivial to bypass. AlwayssafeParseon the server. - Assuming the admin page is safe because nothing links to it. Server Actions can still be called directly. Authorization must live inside every action (Part 10).
- Returning raw
error.messageto the client. Prisma messages can leak table and column names. Log on the server, show a generic message. - Exporting non-functions from a
'use server'file. A file with'use server'at the top may only export async functions. Put shared constants and helpers inlib/. TypeScript types are fine because they are erased at compile time.
Exercises
- Generate the slug from the title (lowercase, spaces to hyphens) when the slug field is left empty. Do it on the server, before
safeParse. - Add a "Show/Hide" button to the admin table that calls a new
togglePublishedServer Action, with id validation andupdateTag. - Replace
window.confirmwith your own keyboard-accessible confirm dialog (a<dialog>element), then callformActioninsidestartTransition.
Summary
- A Server Action is a
'use server'function invoked from<form action>, and technically a public HTTP endpoint. productSchemainlib/validation.tsvalidates and normalises input on the server, andtoFieldErrorsturns zod errors into per-field messages.- Expected errors are returned as state; unexpected ones are logged and replaced with a generic message.
useActionStategives youstate,formAction, andpending. Returnvaluesso input survives the automatic form reset.updateTag('products')expires the Part 7 cache,revalidatePathrefreshes the admin page, andredirectcomes last, outsidetry/catch.- Deleting asks for confirmation and handles P2003 when a product already has orders.
Admins can now manage products from the browser. But what if a mobile app or another service wants to read and change the catalog? In Part 9 we build a REST API with Route Handlers in app/api/products, reusing the same productSchema, with proper status codes and curl tests.
Related articles
PostgreSQL Zero to Advanced #5: Aggregation, GROUP BY & HAVING
Turn raw orders into business numbers: total revenue, average order value, sales per month and top customers using COUNT, SUM, AVG, GROUP BY, HAVING and FILTER.
PHP Zero to Advanced #5: Arrays & Array Functions
Master PHP arrays: indexed and associative arrays, nested data, destructuring, and the essential functions array_map, array_filter, array_reduce, usort, and friends.
Ruby on Rails Zero to Advanced #5: Routing, Controllers & Views
Follow a request through Rails: define routes, use resources, read params in controllers, and render dynamic HTML with ERB views and partials.