javascript 35 lines · 7 steps

How a Next.js Server Action updates a post

A server-side form handler that authenticates, validates, authorizes, writes to the database, and revalidates cached pages.

Explained by highlit
1'use server'
2 
3import { revalidatePath } from 'next/cache'
4import { redirect } from 'next/navigation'
5import { db } from '@/lib/db'
6import { getCurrentUser } from '@/lib/auth'
7 
8export async function updatePost(postId, formData) {
9 const user = await getCurrentUser()
10 if (!user) {
11 throw new Error('Unauthorized')
12 }
13 
14 const title = formData.get('title')?.toString().trim()
15 const body = formData.get('body')?.toString().trim()
16 
17 if (!title || !body) {
18 return { error: 'Title and body are required.' }
19 }
20 
21 const post = await db.post.findUnique({ where: { id: postId } })
22 if (!post || post.authorId !== user.id) {
23 throw new Error('Not found')
24 }
25 
26 const updated = await db.post.update({
27 where: { id: postId },
28 data: { title, body, updatedAt: new Date() },
29 })
30 
31 revalidatePath('/blog')
32 revalidatePath(`/blog/${updated.slug}`)
33 
34 redirect(`/blog/${updated.slug}`)
35}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Server Actions let you run trusted, server-only mutations directly from a form submission without a separate API route.
  2. 2Always re-check authentication and ownership on the server, since client-side checks can be bypassed.
  3. 3After mutating data, revalidate every affected path so cached pages reflect the change.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a Next.js Server Action updates a post — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code