In 06-01 we left a table of open questions about each Server Action: who calls it, what it can do, what happens if it's repeated. Almost all of them now have an answer. What's missing is the one that brings them together: what happens when the caller doesn't use our interface.

In this lesson you'll see what Next.js protects on its own and, above all, where that protection ends. Then you'll go over the mistakes that come up most often in applications with Server Components and how to keep up with vulnerabilities in the framework itself, and you'll close the module by auditing all of AgendaViva with a checklist you can use on any project. Everything here is defensive, and whatever you test, test it only on your own application and your own machine: doing it on other people's systems without written authorization is a crime. Before publishing a real system, have it reviewed by a professional.

  1. What Next.js does for you

Protection What it achieves Where it ends
Encrypted identifiers for each action, which change with every build They can't be guessed or kept forever They're in the HTML of whoever uses it: they aren't a secret
Removal of unused actions What nobody calls isn't published "Unused" means "unreferenced", not "unauthorized"
POST only A link or an image doesn't run them A form does
Origin check Another website can't submit them from the victim's browser A request without Origin isn't checked
Body limit, 1 MB by default Huge bodies It's per request, not per person
Encryption of closures The browser can't read what the action captured It doesn't hide it from whoever invokes it
Errors without details in production The exception message doesn't reach the client What you return does

None of them asks who you are. They all reduce the attack surface, and permission decisions are yours.

1.1. The origin

Cross-site request forgery (CSRF) means another website getting your browser, with your cookies, to send something here. Three barriers prevent it for a Server Action: it's a POST, the cookie is SameSite=Lax (08-01), and Next.js compares the host in the Origin header with X-Forwarded-Host, or with Host if the former is missing. If they don't match, it rejects it.

Behind a reverse proxy that doesn't forward the public name, that comparison fails and actions stop working. The right fix is for the proxy to send X-Forwarded-Host. If that isn't possible:

// Example only: next.config.ts. AgendaViva doesn't need it
experimental: {
  serverActions: {
    bodySizeLimit: '2.2mb',
    allowedOrigins: ['agendaviva.example'],
  },
},

You write the domain as it appears in the address bar, with its port if it has one. * replaces one label and ** several: *.agendaviva.example accepts any subdomain, including the one someone manages to open tomorrow. List the minimum.

Route Handlers don't have this check. Ours that write don't depend on the cookie (webhooks and tasks use their own key), and that's why they can't be forged. If one ever uses the session, it must check Origin or require application/json, which forces the CORS preflight request (07-01).

1.2. Closures and the key

An action written inside a component captures variables, and these travel to the browser and back (06-01). Next.js encrypts them with a key it generates on each build. Two consequences follow:

  • A tab opened before a deployment can call an action that no longer exists. The error is "Failed to find Server Action", and the interface should offer to reload.
  • With several instances built separately, each would have its own key. It's fixed with NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, which must be a base64 AES key and be defined at build time. It ends up included in the output: treat the .next folder and the Docker image as things that contain a secret (11-05).
openssl rand -base64 32

The documentation warns against relying solely on that encryption to hide values. Our convention avoids it: actions in actions/, no closures, and data is read again on the server.

  1. Anatomy of a secure action

Any AgendaViva action can be read with this template. If a step is missing, there should be a reason:

flowchart TD
    A["1. Identity<br/>checkRole / getCurrentUser"] --> B["2. Input<br/>Zod schema, bind arguments too"]
    B --> C["3. Frequency<br/>withinLimits"]
    C --> D["4. Permission on the data<br/>ownership in the where"]
    D --> E["5. Rules and writing<br/>in a transaction"]
    E --> F["6. Cache notifications and audit"]
    F --> G["7. Minimal response<br/>and errors without details"]

Four ideas explain almost every flaw:

  • Arguments can't be trusted, none of them. Not the bind ones, not hidden fields, not TypeScript-typed ones. eventId: string can arrive as an object: Server Actions accept anything serializable. That's why identifier.safeParse(eventId) is there even where it seems absurd.
  • Take references, not objects. The browser says which event and which change; the rest is read from the database. An action that receives the whole event lets the caller choose its owner and its status.
  • The schema decides the fields. z.object discards what it doesn't declare, and { ...data } is only spread after validating. Spreading Object.fromEntries(formData) over an UPDATE lets anyone write any column (mass assignment).
  • Return just what's needed. The value goes back to the browser in full, whether you render it or not. A returning() without columns on the last line of an action sends the row.

  1. Rate limiting

06-01 left open what happens if someone repeats an action a thousand times. consumeAttempt, from 08-02, works for any expensive or annoying operation:

// lib/security/rate-limits.ts (added)
export function writeLimits(userId: string): RateLimit[] {
  return [
    { key: `write:${userId}`, max: 30, seconds: 60 },
    { key: `write-day:${userId}`, max: 500, seconds: 24 * 60 * 60 },
  ]
}

// actions/bookings.ts, in bookSpots, after checking the user
if (!(await withinLimits(writeLimits(user.id)))) {
  return { status: 'error', message: "You're going too fast. Please wait a minute.", errors: {}, values }
}

With a session, the key is the person and there's no doubt about the IP. Apply it to saveEvent and uploadImage too: each poster takes up disk space until it's cleaned up. Public reads (suggestions, availability, the v1 API) are limited on the platform or the load balancer: counting each one in PostgreSQL would cost more than serving it.

A limit doesn't replace a business rule. If nobody should have more than ten active bookings, that's checked in the transaction, not with a time window.

  1. Common pitfalls

4.1. IDOR

Changing an identifier and getting someone else's data. In 08-04 we closed it by putting ownership in the where. There are three places where it reappears:

  • New functions. The first time someone writes getBookingById(id), without an owner, the problem is back.
  • Files. /images/events/<uuid>.png is public even if the event is a draft: anyone with the URL sees the poster. With posters that's acceptable; with personal documents, the Route Handler must check the session and respond with private, no-store.
  • Relationships. When editing your own event you choose a venueId. Checking that it exists isn't checking that it can be used, if venues ever had owners.

A UUID isn't a permission. It gets shared, logged and shows up in screenshots.

4.2. Leaks through props

Everything a Client Component receives is in the HTML and in the payload (03-03). To audit it, look for the boundaries and check their types:

# Client components and what they receive
grep -rl "^'use client'" app components | xargs grep -nE 'interface Props|: \{ .* \}: \{'

# What actually travels: look for something that shouldn't be there
curl -s localhost:3000/events | grep -cE 'organizerId|@example\.com'

With recognizable test data, the second one is a good test: if an email address appears, there's a leak. An action's response is inspected the same way in the network tab.

And there are leaks that aren't props: the error messages you return (error.message with SQL), the parameters of a 'use cache' function (which are stored as readable text), URLs with personal data that end up in logs, and request identifiers, which are harmless, versus a console.log(user), which isn't.

4.3. HTML injection (XSS)

React escapes everything it renders as text, so <p>{event.description}</p> is safe with any content. The ways out of that protection are few:

Way out Risk What to do
dangerouslySetInnerHTML Runs whatever is there Constants only; if it's content, sanitize it on the server with a maintained library and an allowlist of tags
JSON inside a <script> </script> in a value closes the tag Escape < (you'll do it in 09-04)
href with an external URL javascript:… React 19 blocks that scheme; validate that it's https: anyway
Markdown or HTML from users The same as the first Convert with HTML disabled and sanitize afterwards
A file served from your domain An SVG or an HTML file can carry scripts Types allowed by signature, nosniff, sandbox (06-05, 08-05)
Inline styles with data Little, but it allows loading URLs Don't interpolate data into CSS

AgendaViva uses the first only once, with THEME_SCRIPT, which interpolates nothing external. The consequence of an XSS isn't an alert box: it's acting with the session of whoever is viewing. HttpOnly prevents stealing the cookie, not calling reviewEvent from the administrator's page.

4.4. Server-side requests (SSRF)

If the server requests a URL chosen by the visitor, the visitor gains access to the internal network: databases, dashboards, cloud metadata services. It sneaks in through innocent features, like "import the image from a URL".

Our fetch calls always go to URLs from the configuration, with redirect: 'error' and a timeout: the forecast, email, the identity provider and the proxy's check, which is why it uses INTERNAL_URL and not the Host header (07-02). If you ever have to accept a URL: an allowlist of domains, https: only, no following redirects, resolve the name and reject private addresses at connection time, and better still, from a service with no access to the internal network. The same goes for the image optimizer: remotePatterns with hostname: '**' turns your server into anyone's proxy (09-02).

4.5. Injection in queries and other formats

Drizzle passes values as parameters, also inside sql. The danger is sql.raw and building text by hand: if a column name comes from outside (sort by…), it's chosen from a list. Remember the other formats we've already escaped: LIKE patterns (04-02), the calendar and the CSV (07-01), and logs, with JSON.stringify.

4.6. Secrets in the code

A module with 'use server' doesn't reach the browser, and yet it isn't a place for a hard-coded key. In December 2025 a flaw was published, CVE-2025-55183, that made it possible to obtain the compiled code of server functions. Those who read their secrets from process.env at runtime exposed logic; those who had written them into the file exposed their keys.

  1. Staying up to date

Your code can be flawless and the application still vulnerable: the framework interprets requests before you do. The Server Components protocol is complex and gets a lot of scrutiny. These are some cases from the last two years:

When Advisory What it was
March 2025 CVE-2025-29927 Bypassing middleware with a header (07-02)
December 2025 CVE-2025-66478 (React: CVE-2025-55182) Unauthenticated code execution in the RSC protocol. Maximum severity
December 2025 CVE-2025-55184 and CVE-2025-67779 Hanging the process with one request. The first fix was incomplete
December 2025 CVE-2025-55183 Exposure of function code
October 2026 GHSA-673q-mjm6-r5xr Code execution in 'use cache' functions that return several typed arrays. Fixed in 16.4.1 and 15.5.28
October 2026 CVE-2026-96889 Code execution in the image optimizer with SVG, through a library that sharp uses
November 2026 Several (16.4.5 and 15.5.29) Among others, 'use cache' entries shared between different binary arguments

Three lessons. None of them depended on a slip by whoever was programming the application: only updating protected you. Several affected precisely what this course uses, Server Actions and Cache Components. And the number is growing (the team itself counted 51 advisories in 2026 up to November, compared with 14 the previous year) because they're being looked for more carefully today: it's not a reason for alarm, but for having a procedure.

npx next --version            # The one that runs, not the one in package.json
npm install [email protected]          # The latest 16.4 patch; minor versions, with their guide (11-06)
npm audit --omit=dev          # Known advisories in what goes to production
npm audit signatures          # The packages are the ones the registry published
npm outdated
  • Subscribe to the advisories. Next.js publishes them at nextjs.org/blog/security, and since July 2026 it schedules batches on announced dates. The one for December 15, 2026 has already been announced, and it will be released on the 16.5 line.
  • Practice updating on the same day: automated tests and one-click deployment (11-06). If updating is scary, it won't get done.
  • Also update the major version before it reaches end of life. Version 15 stops receiving patches on January 31, 2027.
  • After a code execution vulnerability, rotate the secrets if you were exposed. The December 2025 advisory explicitly asked for it.
  • Install with npm ci and the lockfile in the repository. Every dependency is code that runs with your permissions, at install time and afterwards: before adding one, check who maintains it and whether you could do without it.
  • A firewall rule buys hours; it doesn't replace the patch.

  1. Auditing AgendaViva

The Next.js guide suggests reviewing the data layer, the 'use client' and 'use server' boundaries, bracketed parameters, proxy.ts and route.ts. Applied to our project, everything that accepts something from outside:

Entry point Identity Validation Ownership or rule Frequency
saveDistrict Not needed Against listDistricts Only their own cookie Not needed
bookSpots, cancelMyBooking Session Zod Transaction; owner in the where Per person
createEvent, editEvent organizer Zod and rules isEditableBy Per person
uploadImage, removeImage organizer Byte signature, size isEditableBy Per person
reviewEvent admin Zod Only from review Very few people
signIn, requestSignUp, completeSignUp It's what they establish Zod; safe destination Single-use token IP and account
signOut, linkAccount, signOutOtherSessions Session No input Only their own Not needed
/api/v1/*, availability, suggestions, calendar, existence Public Zod or type Published only; DTO Platform
/api/webhooks/venues Signature Zod, after the signature Idempotency Platform
/api/tasks/* Key No input Repeatable Scheduler
/api/sign-in/oidc/* state, PKCE and nonce Zod (provider, sub) Platform
/api/csp Public Zod, size Only logs IP
/images/* Public isImageKey Unguessable name CDN
Pages /dashboard, /admin, /my-bookings, /account requireRole or requireUser Parameters Data layer

A table like this is reviewed with every change: a new row left blank is an unanswered question. To find the missing ones:

grep -rlE "^'use server'" actions app            # All the actions
find app -name 'route.ts'                         # All the endpoints
grep -rnE '(userId|organizerId): string' lib/data # Only sessions and accounts
grep -rLE "server-only" lib/data                  # No results
grep -rnE "from '@/lib/db/" app components actions # No results: only lib/ touches the database
grep -rn 'dangerouslySetInnerHTML' app components # One: the theme
grep -rn 'sql.raw' lib                            # None

6.1. The checklist

Actions and endpoints

  • Each one identifies the caller, or is documented as public.
  • Every argument goes through a schema, including the bind ones.
  • Ownership is in the query, not in the interface.
  • It returns the minimum and doesn't echo exception messages.
  • Anything expensive or annoying has a limit.
  • No GET writes, except the external provider's callback.

Data

  • Only lib/data/ and lib/tasks/ run queries; everything has server-only.
  • No exported function receives the identifier of whoever is asking, except those that establish identity (sessions and accounts).
  • select with columns on tables with private data.
  • Nothing personal in cache keys or tags.

Accounts

  • Passwords with scrypt or Argon2id; hashed tokens; revocable sessions.
  • Messages and timings that don't reveal who has an account.
  • Changing the password or the role ends sessions.

Browser and configuration

  • Cookies with HttpOnly, Secure, SameSite and __Host-.
  • CSP and the other headers checked on the production build.
  • Secrets only in the environment, different per environment and with a plan for rotating them.

Operations

  • Dependencies up to date and advisories that reach someone.
  • Encrypted backups that have been restored at least once.
  • Logs without personal data, with a retention period.
  • Someone knows what to do, and whom to notify, if there's an incident.

The last block isn't code and it's usually the one that fails. A personal data breach comes with legal obligations on very short deadlines: decide beforehand, with compliance, who takes them on.

  1. Try it

A check is only worth something if you've seen it fail. With two browsers, on your own machine, using "Copy as cURL" or "Edit and Resend" in the developer tools:

  1. As organizer A, save a draft. Resend the request changing the identifier to that of one of B's events. Expected: "This event can no longer be edited."
  2. Resend reviewEvent with a visitor's cookie. Expected: "You don't have permission".
  3. Resend a booking with spots set to -1, 1e3 and empty; and with the cookie removed.
  4. Change the Origin to https://other.example. Expected: an error, and nothing written.
  5. As B, cancel A's booking, using its identifier. Expected: nothing changes.
  6. Delete your session row and click any button.
  7. Go to /dashboard with JavaScript disabled and without a cookie.

Write the ones that fail as automated tests: 10-03 and 10-04 show you how. A security check without a test disappears in the first refactoring.

Common Mistakes and Tips

  • Believing an action's encrypted identifier protects it.
  • Validating the form but not the bind arguments.
  • Checking the session in the page and not in the action.
  • Exporting a helper function from a 'use server' file: it gets published.
  • Receiving the whole object instead of its identifier and the change.
  • Returning error.message.
  • Using allowedOrigins with broad wildcards to get around a proxy error.
  • Not fixing the encryption key with several instances, or storing the image that contains it in a public registry.
  • Sanitizing HTML with regular expressions.
  • Requesting URLs chosen by the visitor.
  • Leaving updates "for the next sprint".
  • An audit that's done once.

Exercises

Exercise 1: reviewing an action

List the problems with this action and rewrite it with the pieces from this module.

'use server'

export async function updateProfile(user: User, formData: FormData) {
  const changes = Object.fromEntries(formData)
  if (user.role === 'visitor' && changes.role) throw new Error('No')
  try {
    const [row] = await db
      .update(users)
      .set({ ...user, ...changes })
      .where(eq(users.id, user.id))
      .returning()
    return { ok: true, user: row }
  } catch (error) {
    return { ok: false, error: String(error) }
  }
}

Solution

  1. It receives the identity from the browser: anyone can be anyone, with whatever role they like.
  2. Mass assignment: role, email or passwordHash can be written.
  3. It validates nothing; formData can contain files.
  4. It returns the row, with the password hash.
  5. It returns the error, which may contain SQL.
  6. No limit or audit, and the action touches the database directly.
// lib/data/accounts.ts
export async function changeMyName(name: string): Promise<void> {
  const user = await ensureUser()
  const db = await getDb()
  await db.update(users).set({ name }).where(eq(users.id, user.id))
}

// actions/account.ts
const profileSchema = z.object({ name: text({ min: 2, max: 80 }) })

export async function updateProfile(
  _previous: FormState<'name'>,
  formData: FormData,
): Promise<FormState<'name'>> {
  const values = readTextFields(formData, ['name'])
  const reject = (message: string, name?: string[]): FormState<'name'> => ({
    status: 'error',
    message,
    errors: { name },
    values,
  })

  const user = await getCurrentUser()
  if (!user) return reject('Please sign in.')

  const result = profileSchema.safeParse(values)
  if (!result.success) {
    return reject('Check the name.', z.flattenError(result.error).fieldErrors.name)
  }
  if (!(await withinLimits(writeLimits(user.id)))) {
    return reject("You're going too fast. Please wait a minute.")
  }

  await changeMyName(result.data.name)
  refresh()
  return { status: 'success', message: 'Name updated.' }
}

The email is left out on purpose: changing it requires confirming the new one and notifying the old one, as in sign-up.

Exercise 2: importing a poster from a URL

Organizers ask to be able to paste an image URL instead of uploading the file. List the risks, write the minimum defenses and say what you'd recommend.

Solution

// Practice only, and insufficient on its own
const DOMAINS = new Set(['posters.example.com'])

async function downloadPoster(text: string): Promise<Uint8Array | null> {
  if (!URL.canParse(text)) return null
  const url = new URL(text)
  if (url.protocol !== 'https:' || !DOMAINS.has(url.hostname) || url.port) return null

  const response = await fetch(url, {
    redirect: 'error',
    signal: AbortSignal.timeout(5000),
  })
  if (!response.ok || !response.body) return null

  const chunks: Uint8Array[] = []
  let total = 0
  for await (const chunk of response.body) {
    total += chunk.byteLength
    if (total > MAX_IMAGE_SIZE) return null // Cuts the download short
    chunks.push(chunk)
  }
  const bytes = new Uint8Array(Buffer.concat(chunks))
  return detectImageType(bytes) ? bytes : null
}

Risks: accessing the internal network, following a redirect into it, huge or extremely slow downloads, content that isn't an image, and using our server to attack others. The domain allowlist is the main defense, and even so an allowed domain can resolve to a private address. If any domain were to be accepted, it would have to be done from an isolated service with no internal access. The recommendation: don't do it. The organizer's browser can download the image and upload it with the form that already exists.

Exercise 3: advisory day

It's Tuesday, 9:00 a.m. An unauthenticated code execution vulnerability affecting your version of Next.js is published, attacks are already happening and a fixed version exists. Put in order what you'd do until the end of the day. What would you be glad to have prepared?

Solution

  1. Confirm with the official advisory (not a social media thread) that the deployed version is affected: npx next --version in the environment, not on your laptop.
  2. Mitigate: if the provider or the firewall offers a rule, enable it. If the risk is high and the patch can't go out in minutes, consider maintenance mode (07-02)… knowing that the proxy is part of the same application: better to do it at the load balancer.
  3. Update only next and whatever it requires, with the lockfile; run the tests; deploy.
  4. Check the version in production and that no old instances remain.
  5. Assume the worst if you were exposed: rotate secrets starting with the database and the OIDC client, end all sessions (one statement, thanks to having them in a table), review logs and the audit trail since publication, preserve evidence.
  6. Notify whoever needs to know: managers, compliance and, if personal data was accessed, the authority and those affected, within the deadline.
  7. Write down what was hard and fix it: next time will be similar.

You'll be glad to have: advisories that reach someone, trustworthy tests, a short deployment, secrets that can be swapped on the fly (07-03), logs stored outside the affected machine and a contact list.

Conclusion

Next.js encrypts action identifiers, checks their origin, limits their size and hides errors; the rest is yours. A secure action identifies the caller, validates all its arguments, limits frequency, keeps ownership in the query and returns just what's needed. The common pitfalls (IDOR, leaks through props, unescaped HTML, requests to external URLs, secrets in the code) are found with a table of entry points and a few commands, and the framework's own are countered by updating on the same day. AgendaViva has passed that review, which must be repeated with every change, and before going live it would need one by someone from outside the project.

That concludes module 8. The application knows who each person is, what they can do and how to defend itself when someone doesn't follow the script. What it still lacks is a polished look: the styles are minimal, posters are served unoptimized and search engines barely know what each page is about. Module 9, UI, SEO and Internationalization, deals with what you see, and it starts with Styling: CSS Modules, Tailwind CSS and Sass.

© Copyright 2026. All rights reserved