惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
量子位
小众软件
小众软件
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
I
InfoQ
Jina AI
Jina AI
The Cloudflare Blog
Recorded Future
Recorded Future
Recent Announcements
Recent Announcements
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
G
Google Developers Blog
Stack Overflow Blog
Stack Overflow Blog
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Martin Fowler
Martin Fowler
T
Tailwind CSS Blog
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
F
Fortinet All Blogs
WordPress大学
WordPress大学
P
Proofpoint News Feed
D
DataBreaches.Net
爱范儿
爱范儿
雷峰网
雷峰网
D
Docker
B
Blog
Engineering at Meta
Engineering at Meta
腾讯CDC
N
Netflix TechBlog - Medium
C
Check Point Blog
博客园 - 【当耐特】
Apple Machine Learning Research
Apple Machine Learning Research
T
Tenable Blog
GbyAI
GbyAI
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 三生石上(FineUI控件)
T
The Blog of Author Tim Ferriss
博客园 - 聂微东
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
SecWiki News
SecWiki News
S
Security @ Cisco Blogs
S
Security Affairs
V
V2EX
Application and Cybersecurity Blog
Application and Cybersecurity Blog
云风的 BLOG
云风的 BLOG
C
CERT Recently Published Vulnerability Notes
Y
Y Combinator Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Next.js 16 Server Actions Security: The Auth Check Most Developers Miss
Shubhra Pokhariya · 2026-06-25 · via DEV Community

I keep seeing it on code reviews. Proxy solid. Auth on every Server Component. Header direction correct.

Then I look at the Server Actions.

No auth check. Not one. The page that renders the button is protected. The action behind the button accepts whatever the caller sends -- any valid session, any resource ID, no ownership verification anywhere.

'use server' doesn't add authentication. It exposes an HTTP endpoint. Anyone with a valid session cookie and a cURL command can call it directly, no UI required.

That's what this post covers.

What "use server" does, and what it does not do

When you add 'use server' to a file or a function, you're telling Next.js to move that code to the server and expose it as a callable endpoint. That's all it does.

It does not add authentication. It does not check who is calling. It does not verify that the caller has any session at all. From the official Next.js 16 docs:

Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation.

Public-facing API endpoints. That's exactly what they are. Anyone who can construct a POST request to the right URL can call your Server Action. No browser required. No UI required. A cURL command with a valid session cookie is enough.

The shift that matters: when you write a Server Action, you're not writing an internal helper that only runs when a user clicks a specific button. You're writing a public HTTP endpoint that also happens to be invokable from a button. Completely different from a security standpoint.

Next.js does give you two protections out of the box worth knowing about. Action IDs are encrypted and non-deterministic, recalculated between builds, so old IDs stop working after a deploy. Unused Server Actions are removed from the client bundle entirely through dead code elimination. Both things help reduce your attack surface. Neither one is authentication.

The gap that looks fine until it isn't

This is the pattern I keep finding on code reviews:

// app/dashboard/posts/[id]/page.tsx
import { verifySession } from '@/app/lib/dal'
import { deletePostAction } from './actions'

export default async function PostPage({ params }) {
  const session = await verifySession()  // Page is protected

  return (
    <div>
      <h1>Edit Post</h1>
      <form action={deletePostAction}>
        <input type="hidden" name="postId" value={params.id} />
        <button type="submit">Delete</button>
      </form>
    </div>
  )
}

// app/dashboard/posts/[id]/actions.ts
'use server'

import { db } from '@/lib/db'

export async function deletePostAction(formData: FormData) {
  const postId = formData.get('postId') as string

  // No auth check. The page already verified the user.
  await db.post.delete({ where: { id: postId } })
}

The page check runs at render time and confirms the user is authenticated before the UI appears. The action check never runs because nobody added one. The action will accept a delete request from anyone with any valid session, for any post ID, with no verification that the caller owns the post.

The fix is treating the action as its own entry point with its own verification:

// app/dashboard/posts/[id]/actions.ts
'use server'

import { verifySession } from '@/app/lib/dal'
import { db } from '@/lib/db'

export async function deletePostAction(formData: FormData) {
  const session = await verifySession()
  const postId = formData.get('postId') as string

  const post = await db.post.findUnique({ where: { id: postId } })

  if (!post || post.authorId !== session.userId) {
    throw new Error('Not found')
  }

  await db.post.delete({ where: { id: postId } })
}

Two changes. verifySession() runs first, independent of whether the page ran it. The ownership check runs before the delete.

Same error for "not found" and "not authorized" is intentional. Different error messages let a caller figure out which post IDs exist in your system. One generic error closes that.

The Data Access Layer: why it exists

Once you start adding auth checks, ownership checks, and business logic inside every action, the actions get long and hard to audit. I used to copy-paste the ownership check into every action that touched posts. Then I changed the logic in one place and forgot the other four. A user found the gap before I did. The Data Access Layer pattern fixed that permanently.

Centralize all auth logic and database access in a separate module marked with server-only. Keep your actions thin. Actions receive input, call DAL functions, handle Next.js-specific things like cache revalidation. That's it.

// app/lib/dal.ts
import 'server-only'
import { cookies } from 'next/headers'
import { decrypt } from '@/app/lib/session'
import { cache } from 'react'
import { redirect } from 'next/navigation'

export const verifySession = cache(async () => {
  const cookie = (await cookies()).get('session')?.value
  const session = await decrypt(cookie)

  if (!session?.userId) {
    redirect('/login')
  }

  return { isAuth: true, userId: session.userId as string }
})

server-only at the top is not decoration. It causes a build error if this module ever gets imported from a Client Component. The auth logic physically cannot reach the browser because the build won't allow it. That's stronger than any code review convention.

The cache() wrapper from React is worth understanding too. When verifySession() gets called multiple times during the same render pass, once from the page, once from a leaf component, once from a data function, React deduplicates those calls automatically. One cookie read, one JWT verification, one result shared across the render. No repeated work.

Now the DAL functions:

// app/lib/dal.ts (continued)
import { db } from '@/lib/db'

export const getUserPost = cache(async (postId: string) => {
  const session = await verifySession()

  const post = await db.post.findUnique({
    where: { id: postId },
    select: { id: true, title: true, content: true, authorId: true }
  })

  if (!post || post.authorId !== session.userId) {
    return null
  }

  return post
})

export const deleteUserPost = async (postId: string) => {
  const session = await verifySession()

  const post = await db.post.findUnique({ where: { id: postId } })

  if (!post || post.authorId !== session.userId) {
    throw new Error('Not found')
  }

  await db.post.delete({ where: { id: postId } })
}

And the action becomes thin:

// app/dashboard/posts/[id]/actions.ts
'use server'

import { deleteUserPost } from '@/app/lib/dal'
import { revalidatePath } from 'next/cache'

export async function deletePostAction(formData: FormData) {
  const postId = formData.get('postId') as string
  await deleteUserPost(postId)
  revalidatePath('/dashboard/posts')
}

The action does two things: call the DAL function and handle cache invalidation. Everything else lives in the DAL where it's reviewable and testable in one place.

The Layout trap that catches everyone once

A lot of developers put their auth check in a shared Layout component because it feels efficient. One check, covers everything under that route segment. The official docs have a specific warning about this:

Due to Partial Rendering, be cautious when doing checks in Layouts as these don't re-render on navigation, meaning the user session won't be checked on every route change.

What that means in practice: a user navigates to /dashboard, the Layout checks their session. They then navigate to /dashboard/billing. The Layout does not re-render. No session check runs for that navigation. If that user's session was revoked between those two navigations, the billing page renders anyway.

The fix is straightforward. Layouts fetch user data for display purposes, name in the nav, avatar, that kind of thing. The authorization check belongs in the page component or the DAL function it calls, not in the Layout.

// app/dashboard/layout.tsx
import { getUser } from '@/app/lib/dal'

export default async function DashboardLayout({ children }) {
  const user = await getUser()  // For display only, not auth enforcement

  return (
    <div>
      <nav>Welcome, {user.name}</nav>
      {children}
    </div>
  )
}

// app/dashboard/billing/page.tsx
import { verifySession } from '@/app/lib/dal'
import { getUserPermissions } from '@/app/lib/dal'
import { redirect } from 'next/navigation'

export default async function BillingPage() {
  const session = await verifySession()  // Runs on every navigation to this page
  const permissions = await getUserPermissions(session.userId)

  if (!permissions.includes('billing:read')) {
    redirect('/unauthorized')
  }

  // render billing content
}

Because verifySession() lives in the DAL and gets called from the page component directly, it runs on every navigation to that page regardless of what the Layout did or did not do.

Roles vs permissions inside actions

Roles are coarse and stable. They live in the session payload. Checking a role inside a DAL function costs nothing extra because the session is already decrypted:

// app/lib/dal.ts
export const verifyAdminSession = cache(async () => {
  const session = await verifySession()

  if (session.role !== 'admin') {
    redirect('/unauthorized')
  }

  return session
})

Permissions are granular and they change independently of session rotation. If you revoke a user's billing:export permission at 2pm, you want that to take effect immediately, not when their session next expires. That means a database call:

// app/lib/dal.ts
export const getUserPermissions = cache(async () => {
  const session = await verifySession()

  const permissions = await db.permission.findMany({
    where: { userId: session.userId },
    select: { name: true }
  })

  return permissions.map(p => p.name)
})

Because getUserPermissions is wrapped in cache(), if it gets called from both the page component and a leaf component during the same render, the database query runs once. Covered in Part 2 briefly, but the DAL pattern is where this actually becomes useful because the cache wrapper lives in one place and applies everywhere the function is called.

What to return from Server Actions

Server Action return values get serialized and sent to the client. If you return a raw database record, the client gets every column including ones it should never see. This happens by accident more than people realize:

// This sends passwordHash, stripeCustomerId, internalNotes to the browser
'use server'
export async function updateProfile(formData: FormData) {
  const session = await verifySession()

  return db.user.update({
    where: { id: session.userId },
    data: { name: formData.get('name') as string }
  })
}

// Return only what the UI needs
'use server'
export async function updateProfile(formData: FormData) {
  const session = await verifySession()

  await db.user.update({
    where: { id: session.userId },
    data: { name: formData.get('name') as string }
  })

  return { success: true, name: formData.get('name') }
}

When your DAL functions use explicit select statements, this is mostly handled automatically. The action returns what the DAL gives it. The DAL selects only the columns it needs. Nothing extra reaches the client.

Before you ship

  • Every Server Action calls verifySession() before touching data
  • Every mutation checks ownership before executing, not after
  • DAL functions use server-only and explicit select statements
  • Auth checks live in page components, not Layouts
  • Return values are DTOs, not raw database records
  • Test every action directly with cURL or a REST client before deploying, not just through the UI

That last one is the test. If hitting an action endpoint directly with a valid session cookie returns data or executes a mutation it should not, the UI protecting it does not matter.

Where this series ends

Part 1 was the invoice incident. One missing ownership check in a data function. Technically correct auth at every layer that actually existed, and one layer that did not exist.

Part 2 was the proxy.ts gate. The matcher failures that happen silently, the header direction bug, and getVerifiedUser() to close the header trust boundary.

This post is the layer that catches mutations. verifySession() in every Server Action independent of the page that rendered the button. Ownership checks before every mutation. The DAL pattern so the auth logic lives in one place. DTOs so the client only gets what it needs.

Three independent checks. One bug doesn't open the door.

I still see the missing action check on almost every code review I do. Not in the proxy. Not in the page. In the action, quietly accepting whatever the caller sent.

Full implementation with all three layers at Next.js 16 Authentication: The 3-Layer Security Model That Catches What proxy.ts Misses. Loading states, error handling, useActionState, and cache invalidation patterns in Server Actions are covered in Next.js 16 Server Actions: The Bugs That Only Show Up in Production.

Note: I use AI for editing and image generation, but the technical substance is from my own work.