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

typescript
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';

Wiring validation and Swagger docs in NestJS

validation openapi decorators
Intermediate 8 steps
javascript
const ROLE_PERMISSIONS = {
  admin: ['users:read', 'users:write', 'billing:read', 'billing:write'],
  manager: ['users:read', 'billing:read'],
  member: ['users:read'],

Role-based permissions middleware in Express

authorization middleware rbac
Intermediate 9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) {
  const formatter = new Intl.NumberFormat(locale);
  const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ',';
  const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';

Live thousand separators without losing the caret

dom intl caret-preservation
Advanced 8 steps
javascript
import { useReducer, useEffect } from "react";
 
const initialState = { status: "idle", data: null, error: null };
 

Building a data-fetching hook in React

custom-hooks usereducer data-fetching
Intermediate 9 steps
php
<?php
 
namespace App\Broadcasting;
 

Authorizing presence channels in Laravel

broadcasting authorization presence-channels
Intermediate 3 steps
javascript
const express = require('express');
const app = express();
 
app.get('/health', (req, res) => res.json({ status: 'ok' }));

Graceful shutdown in an Express server

graceful-shutdown signal-handling connection-tracking
Advanced 9 steps

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