SECURITYNEXT.JS 16SERVER ACTIONS

8 security holes in a Next.js app, and how to close each one

Open redirects, server actions anyone can call, forms with no limit, injected HTML, spreadsheet formulas, server requests into your own network, leaked secrets and missing headers. You’ll open each hole in a real Next.js 16 app, watch it work, then close it. Six of them were in this site’s own code.

Ali Murtaza · 27 min read ·

Tested step by step on with Next.js 16.4.6 and Prisma 7.10.1

Most security holes in web apps aren’t clever. They’re ordinary code that trusts something it shouldn’t: a URL, a form, a title someone typed, a link someone pasted. They pass every test you write, because your tests use your app the way you meant it to be used.

This guide walks through eight of them on a real Next.js 16 app. For each one you’ll write the code the way it’s usually written, prove the hole is there by attacking your own app from the terminal or the browser, then fix it and prove the attack fails. Six of the eight were in this site’s own code when we reviewed it in November 2026; the fixes below are the ones we shipped, simplified. Every step was run on a fresh create-next-app project and a fresh shadcn init project, with Next.js 16.4, Prisma 7.10 and Node.js 25.

Before you start

  • The tasks app from Next.js 16 + Prisma 7 + Postgres, steps 1 to 11. It has a /tasks page that lists, adds, ticks and deletes tasks from a database. This guide adds to that app.
  • Run every command from the project’s folder, and keep npm run dev running in its own terminal unless a step says to stop it. The curl commands go in a second terminal.
  • Only ever try these attacks on your own app, on your own computer.

1. Redirects that leave your site

Sign-in pages, “back” links and links in emails often take a destination from the URL, like /sign-in?next=/settings. If the check on that value can be fooled, your domain becomes a trusted-looking link to anywhere: a fake copy of your sign-in page, say. This is called an open redirect, and our own sign-in had one.

Here is the usual version. Create app/go/route.ts:

app/go/route.tsts
import { NextResponse, type NextRequest } from "next/server";// /go?to=/tasks sends the visitor to a page on this site.export function GET(request: NextRequest) { const to = request.nextUrl.searchParams.get("to") ?? "/"; // Looks safe: only paths that start with "/", and never "//other-site". if (!to.startsWith("/") || to.startsWith("//")) { return NextResponse.redirect(new URL("/", request.url)); } return NextResponse.redirect(new URL(to, request.url));}

Open http://localhost:3000/go?to=/tasks and you land on your tasks. The check refuses https://other-site and //other-site. Now try the one it misses, in the second terminal:

Terminalbash
curl -sI "http://localhost:3000/go?to=/%5Cexample.com" | grep -i location

It prints location: http://example.com/. %5C is a backslash, so the value is /\example.com: it starts with /, and it doesn’t start with //. But browsers (and new URL) read a backslash in a web address as a forward slash, so /\example.com means //example.com, which means another site. A tab character (/%09/example.com) works too. You can’t win by listing bad characters: there’s always one more.

The fix is to stop guessing and let the URL parser decide, exactly as the browser will. Resolve the value against your own address, and keep it only if the result is still on your site. Create lib/safe-path.ts:

lib/safe-path.tsts
// Turns a "where to go next" value from a URL into a path on this site,// or the fallback. Lets the URL parser decide, exactly as a browser would.export function safePath(to: string | null, base: string, fallback = "/") { if (!to) return fallback; let url: URL; try { url = new URL(to, base); } catch { return fallback; } // Another site ("/\evil.com" parses as https://evil.com), or a path that // starts with "//", which means another site wherever it's used next. if (url.origin !== new URL(base).origin || url.pathname.startsWith("//")) { return fallback; } return url.pathname + url.search + url.hash;}

And use it in app/go/route.ts:

app/go/route.tsts
import { NextResponse, type NextRequest } from "next/server";import { safePath } from "@/lib/safe-path";// /go?to=/tasks sends the visitor to a page on this site — and only this site.export function GET(request: NextRequest) { const to = safePath(request.nextUrl.searchParams.get("to"), request.url); return NextResponse.redirect(new URL(to, request.url));}
Terminalbash
curl -sI "http://localhost:3000/go?to=/%5Cexample.com" | grep -i location

Now it prints location: http://localhost:3000/, and /tasks still works. The // check matters too: /.//example.com resolves to the path //example.com on your site, which is harmless here but becomes another site the moment that path is used as a link. Use safePath everywhere you redirect to a value you didn’t write yourself.

2. Every export in a “use server” file is a public endpoint

A file that starts with "use server" turns every exported async function into a server action: something the browser calls with a POST request. A POST can come from anything, not just your form, and it doesn’t matter whether a page uses the function. It’s tempting to keep helpers next to the actions that use the same database. Add this at the end of app/tasks/actions.ts:

app/tasks/actions.ts (add at the end)ts
// A helper for an admin script, never used by any page.export async function deleteAllTasks() { await prisma.task.deleteMany();}

Now see what Next.js made of that file. Stop npm run dev (Ctrl+C), then build the app and list its server actions:

Terminalbash
npm run buildnode -e 'const m = require("./.next/server/server-reference-manifest.json"); for (const [id, a] of Object.entries(m.node)) console.log(id, a.exportedName)'

It prints one line per action: an ID (42 letters and numbers), then the name. deleteAllTasks is there, beside addTask, toggleTask and deleteTask. Start the built app with npm start, then call deleteAllTasks the way any program could. Paste its ID in place of PASTE_THE_ID:

Terminalbash
curl -s -X POST http://localhost:3000/tasks -H "Next-Action: PASTE_THE_ID" -H "Content-Type: text/plain" -d "[]" > /dev/null

The Next-Action header names the action, and the body [] is the list of arguments to call it with: none. Reload http://localhost:3000/tasks: “No tasks yet.” Every task is gone. No page, no button, no sign-in. To be fair to Next.js: an action that no page uses isn’t sent to the browser, so a stranger would first have to learn that ID. But the ID is the only thing protecting it, and the day a client component imports the function, the ID is in your JavaScript for anyone to read.

The fix is a rule: a "use server" file exports actions and nothing else. Helpers go in an ordinary file that starts with import "server-only", which makes the build fail if a client component ever imports it (step 7 shows that). Install the package:

Terminalbash
npm install server-only

Move the helper into lib/tasks-admin.ts:

lib/tasks-admin.tsts
import "server-only";import { prisma } from "@/lib/prisma";// For admin scripts. Not a server action: nothing outside the server can call it.export async function deleteAllTasks() { await prisma.task.deleteMany();}

And take it out of app/tasks/actions.ts, which goes back to exactly the three actions it had:

app/tasks/actions.tsts
"use server";import { revalidatePath } from "next/cache";import { prisma } from "@/lib/prisma";export type FormState = { error: string } | null;export async function addTask( _previous: FormState, formData: FormData,): Promise<FormState> { const title = String(formData.get("title") ?? "").trim(); if (!title) return { error: "Write a task first." }; if (title.length > 200) return { error: "Keep it under 200 characters." }; await prisma.task.create({ data: { title } }); revalidatePath("/tasks"); return null;}export async function toggleTask(formData: FormData) { const id = Number(formData.get("id")); const task = await prisma.task.findUnique({ where: { id } }); if (!task) return; await prisma.task.update({ where: { id }, data: { done: !task.done } }); revalidatePath("/tasks");}export async function deleteTask(formData: FormData) { const id = Number(formData.get("id")); await prisma.task.deleteMany({ where: { id } }); revalidatePath("/tasks");}

Stop npm start (Ctrl+C), build again and list the actions:

Terminalbash
npm run buildnode -e 'const m = require("./.next/server/server-reference-manifest.json"); for (const [id, a] of Object.entries(m.node)) console.log(id, a.exportedName)'

Three lines: deleteAllTasks is no longer something the outside world can call. Put the starting tasks back, and start npm run dev again:

Terminalbash
npx prisma db seed

Remember the other half of this rule. Every action is a public endpoint, so each one must check everything itself, inside the action: who is calling (in an app with accounts, read the session at the top of every action, as in the Better Auth guide), and every value it receives. addTask already checks its title on the server, because a POST doesn’t have to come from your form, and a form’s maxLength only stops people who use the form.

3. Forms anyone can hammer

Nothing stops a script from calling addTask ten thousand times a minute. Here it fills a table. On a newsletter form it sends ten thousand emails to someone who never asked (and gets your domain marked as spam); on a sign-in form it tries ten thousand passwords. Our newsletter and unlock forms had no limit until the review. The fix is a rate limit: count each visitor’s attempts, and refuse past a limit.

The count has to live somewhere every server shares. On a host like Vercel, each request may run on a different instance, so a count kept in memory resets constantly. You already have a database, so keep it there. Add a table at the end of prisma/schema.prisma:

prisma/schema.prisma (add at the end)prisma
model RateLimit { key String @id count Int resetAt DateTime}
Terminalbash
npx prisma migrate dev --name rate-limitsnpx prisma generate

Each row is one visitor doing one thing: a key like add-task:203.0.113.7, how many times they’ve done it, and when the count starts again. Create lib/rate-limit.ts:

lib/rate-limit.tsts
import "server-only";import { headers } from "next/headers";import { prisma } from "@/lib/prisma";// True while this visitor has done `action` at most `max` times in the// last `seconds`. One SQL statement, so two requests at the same instant// can't both read "9" and both be let through as the 10th.export async function allowed(action: string, max: number, seconds: number) { const ip = (await headers()).get("x-forwarded-for")?.split(",")[0].trim() || "unknown"; const key = `${action}:${ip}`; const now = new Date(); const resetAt = new Date(now.getTime() + seconds * 1000); const [row] = await prisma.$queryRaw<{ count: number }[]>` INSERT INTO "RateLimit" ("key", "count", "resetAt") VALUES (${key}, 1, ${resetAt}) ON CONFLICT ("key") DO UPDATE SET "count" = CASE WHEN "RateLimit"."resetAt" < ${now} THEN 1 ELSE "RateLimit"."count" + 1 END, "resetAt" = CASE WHEN "RateLimit"."resetAt" < ${now} THEN ${resetAt} ELSE "RateLimit"."resetAt" END RETURNING "count"`; return row.count <= max;}
  • The visitor is their IP address, from the x-forwarded-for header. On Vercel the platform sets it, so it can be trusted. If you host the app yourself, only trust it when your own proxy sets it, or anyone can send a different one with every request.
  • The SQL either starts a new count or adds one to the current count, and returns the result, in one statement. Reading the count, then writing it in a second query, would let two requests at the same moment both see 9 and both get through.
  • $queryRaw with a template string sends every ${…} value separately from the SQL, so nothing a visitor sends can change the query.

Then check the limit in addTask. The whole app/tasks/actions.ts:

app/tasks/actions.tsts
"use server";import { revalidatePath } from "next/cache";import { prisma } from "@/lib/prisma";import { allowed } from "@/lib/rate-limit";export type FormState = { error: string } | null;export async function addTask( _previous: FormState, formData: FormData,): Promise<FormState> { const title = String(formData.get("title") ?? "").trim(); if (!title) return { error: "Write a task first." }; if (title.length > 200) return { error: "Keep it under 200 characters." }; if (!(await allowed("add-task", 10, 60))) { return { error: "That’s a lot of tasks at once. Try again in a minute." }; } await prisma.task.create({ data: { title } }); revalidatePath("/tasks"); return null;}export async function toggleTask(formData: FormData) { const id = Number(formData.get("id")); const task = await prisma.task.findUnique({ where: { id } }); if (!task) return; await prisma.task.update({ where: { id }, data: { done: !task.done } }); revalidatePath("/tasks");}export async function deleteTask(formData: FormData) { const id = Number(formData.get("id")); await prisma.task.deleteMany({ where: { id } }); revalidatePath("/tasks");}

Restart npm run dev, then add eleven tasks quickly. The first ten are added; the eleventh says “That’s a lot of tasks at once. Try again in a minute.” and isn’t. Ten a minute is plenty for a person and useless for a script. Pick the limit for each form by asking what a real person would never exceed.

On your computer the key is add-task:::1 or add-task:127.0.0.1: both are your own machine. Rows aren’t deleted when they expire; they’re reused. For a busy app, delete old ones now and then with DELETE FROM "RateLimit" WHERE "resetAt" < now(). Wait a minute before the next steps, which add tasks too.

4. HTML from your users

Say tasks may use **bold**. The quick way is to turn the stars into HTML and hand it to React. Create app/tasks/task-title.tsx:

app/tasks/task-title.tsxtsx
// Lets a task title use **bold**.export function TaskTitle({ text }: { text: string }) { const html = text.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>"); return <span dangerouslySetInnerHTML={{ __html: html }} />;}

Use it in app/tasks/page.tsx. This is the page from the Prisma guide with one change, <TaskTitle text={task.title} /> in place of {task.title}:

app/tasks/page.tsxtsx
import { Suspense } from "react";import { connection } from "next/server";import { prisma } from "@/lib/prisma";import { AddTaskForm } from "./add-task-form";import { deleteTask, toggleTask } from "./actions";import { TaskTitle } from "./task-title";export default function TasksPage() { return ( <main className="mx-auto max-w-xl p-8"> <h1 className="text-2xl font-semibold">Tasks</h1> <AddTaskForm /> <Suspense fallback={<p className="mt-6">Loading tasks…</p>}> <TaskList /> </Suspense> </main> );}async function TaskList() { // Render on every request, so the list is always what's in the database. await connection(); const tasks = await prisma.task.findMany({ orderBy: { createdAt: "asc" } }); if (tasks.length === 0) { return <p className="mt-6 text-sm">No tasks yet. Add your first one above.</p>; } return ( <ul className="mt-6 divide-y rounded border"> {tasks.map((task) => ( <li key={task.id} className="flex items-center gap-3 px-3 py-2"> <form action={toggleTask}> <input type="hidden" name="id" value={task.id} /> <button type="submit" aria-label={task.done ? "Mark as not done" : "Mark as done"}> {task.done ? "☑" : "☐"} </button> </form> <span className={task.done ? "flex-1 line-through opacity-60" : "flex-1"}> <TaskTitle text={task.title} /> </span> <form action={deleteTask}> <input type="hidden" name="id" value={task.id} /> <button type="submit" className="text-sm text-red-600"> Delete </button> </form> </li> ))} </ul> );}

Add the task Ship the **landing page** and “landing page” is bold. Now add this one:

Task titlehtml
<img src=x onerror="alert('Hacked')">

An alert says “Hacked”, and it says it again every time anyone opens the page. That alert could have been any JavaScript: it runs as your site, in every visitor’s browser, so it can read the page, act as the signed-in visitor and send what it finds anywhere. This is cross-site scripting (XSS). Delete that task before going on.

React escapes every string you render with {…}, so {task.title} was safe all along; dangerouslySetInnerHTML is the one place that turns this off, and its name is the warning. The fix keeps the title as text, and makes only the parts between ** bold:

app/tasks/task-title.tsxtsx
// Lets a task title use **bold**. The title is split into plain strings,// and React escapes every string it renders, so a title can't become HTML.export function TaskTitle({ text }: { text: string }) { return text .split("**") .map((part, i) => (i % 2 === 1 ? <strong key={i}>{part}</strong> : part));}

Add the <img …> task again: no alert, and the title shows exactly the characters that were typed. If you ever must show HTML from users (the output of a rich-text editor, say), clean it with a sanitizer such as DOMPurify first, and never trust a link a user gave you without checking it starts with https://: a javascript: link runs code when clicked.

5. Spreadsheet formulas in your exports

Admins love a “Download CSV” button, and they open the file in Excel or Google Sheets. Create app/tasks/export/route.ts, which downloads every task:

app/tasks/export/route.tsts
import { connection } from "next/server";import { prisma } from "@/lib/prisma";// /tasks/export downloads every task as a CSV file, for a spreadsheet.export async function GET() { await connection(); const tasks = await prisma.task.findMany({ orderBy: { createdAt: "asc" } }); const rows = [ ["Title", "Done"], ...tasks.map((task) => [task.title, task.done ? "yes" : "no"]), ]; const csv = rows.map((row) => row.map(cell).join(",")).join("\r\n"); return new Response(csv, { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": 'attachment; filename="tasks.csv"', }, });}// Quotes a value and doubles any quotes inside it: the standard CSV rule.function cell(value: string) { return `"${value.replaceAll('"', '""')}"`;}

Add a task with this title:

Task titletext
=HYPERLINK("https://example.com","Click for details")

Then look at the file:

Terminalbash
curl -s http://localhost:3000/tasks/export

Its last line is "=HYPERLINK(""https://example.com"",""Click for details"")","no". The quotes are only CSV’s way of holding commas: a spreadsheet program reads the cell as =HYPERLINK(…) and treats it as a formula, so the admin sees a friendly “Click for details” link to wherever the visitor chose. Formulas can do worse than links. This is CSV injection (OWASP documents it under that name); our admin’s exports of subscribers and orders had it. We checked what goes into the file, not every spreadsheet program’s behaviour, so treat every cell as a possible formula.

The fix: a cell that starts with =, +, -, @, a tab or a return gets a ' in front, which spreadsheets show as plain text. Create lib/csv.ts:

lib/csv.tsts
// One CSV cell. Quoted, with quotes doubled — and if a spreadsheet would// read it as a formula (it starts with = + - @, a tab or a return), a '// goes in front, so it shows as text instead of running.export function csvCell(value: string) { const safe = /^[=+\-@\t\r]/.test(value) ? `'${value}` : value; return `"${safe.replaceAll('"', '""')}"`;}

And use it in the export:

app/tasks/export/route.tsts
import { connection } from "next/server";import { prisma } from "@/lib/prisma";import { csvCell } from "@/lib/csv";// /tasks/export downloads every task as a CSV file, for a spreadsheet.export async function GET() { await connection(); const tasks = await prisma.task.findMany({ orderBy: { createdAt: "asc" } }); const rows = [ ["Title", "Done"], ...tasks.map((task) => [task.title, task.done ? "yes" : "no"]), ]; const csv = rows.map((row) => row.map(csvCell).join(",")).join("\r\n"); return new Response(csv, { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": 'attachment; filename="tasks.csv"', }, });}
Terminalbash
curl -s http://localhost:3000/tasks/export

Now the line starts "'=HYPERLINK(: the spreadsheet shows the title as text. Use csvCell for every value in every CSV you make, including names and emails: anyone can sign up as =cmd….

6. Links your server fetches for you

A link preview, a “check my website” button, an image-from-URL upload, a webhook URL a user sets: all of them make your server fetch a URL someone else typed. Your server sits inside your network, where things trust it. Create app/api/preview/route.ts, which returns the title of a page:

app/api/preview/route.tsts
import { type NextRequest } from "next/server";// /api/preview?url=https://example.com returns that page's title,// to show a preview of a link someone pasted.export async function GET(request: NextRequest) { const url = request.nextUrl.searchParams.get("url"); if (!url) return Response.json({ error: "Add ?url=" }, { status: 400 }); const html = await (await fetch(url)).text(); const title = html.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.trim() ?? null; return Response.json({ title });}
Terminalbash
curl -s "http://localhost:3000/api/preview?url=https://example.com"curl -s "http://localhost:3000/api/preview?url=http://localhost:3000/no-such-page"

The first prints {"title":"Example Domain"}, as intended. The second prints {"title":"404: This page could not be found."}: the title of your own app’s “not found” page. Your server just fetched a page from its own machine for a stranger, and handed back what it said. On a cloud server, the same request to http://169.254.169.254/ reaches the provider’s metadata service, which hands out the machine’s credentials; on a company network, it reaches databases and admin panels that trust “inside” requests. This is server-side request forgery (SSRF).

Checking the address before calling fetch isn’t enough. fetch looks the name up again when it connects, and a name can answer “a public address” to your check and “127.0.0.1” a moment later. That’s DNS rebinding, and our capstone checker had exactly this gap until the review. The fix connects to the exact address that was checked: Node’s https.request lets you replace its DNS lookup with your own, so the check and the connection are the same step. Create lib/safe-fetch.ts:

lib/safe-fetch.tsts
import "server-only";import { lookup } from "node:dns";import { request } from "node:https";import { BlockList, isIP, type LookupFunction } from "node:net";// Addresses a stranger's link must never reach: this machine, private// networks, the cloud's metadata service (169.254.169.254) and the like.const blocked = new BlockList();for (const [network, bits] of [ ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.168.0.0", 16], ["198.18.0.0", 15], ["224.0.0.0", 3],] as const) blocked.addSubnet(network, bits, "ipv4");for (const [network, bits] of [ ["::", 127], ["64:ff9b::", 96], ["2002::", 16], ["fc00::", 7], ["fe80::", 10], ["ff00::", 8],] as const) blocked.addSubnet(network, bits, "ipv6");// (An IPv4 address written as IPv6, like ::ffff:127.0.0.1, is checked// against the IPv4 rules above by BlockList itself.)const isPublic = (address: string) => !blocked.check(address, isIP(address) === 6 ? "ipv6" : "ipv4");// The connection's own DNS lookup: if any address is not public, the// connection fails. Because the socket connects to the address checked// here, a name can't answer "public" to a check and "127.0.0.1" later.const publicLookup: LookupFunction = (hostname, options, callback) => { lookup(hostname, { ...options, all: true }, (error, addresses) => { if (error) return callback(error, "", 4); if (!addresses.length || !addresses.every((a) => isPublic(a.address))) { return callback(new Error(`${hostname} is not a public address`), "", 4); } if (options.all) return callback(null, addresses); callback(null, addresses[0].address, addresses[0].family); });};// Fetches a public https:// page: 5 seconds, 1 MB and 3 redirects at most,// each redirect checked again.export function fetchPublicPage(link: string, redirectsLeft = 3): Promise<string> { const url = new URL(link); const host = url.hostname.replace(/^\[|\]$/g, ""); if (url.protocol !== "https:" || url.port || url.username || url.password) { return Promise.reject(new Error("Only https:// links on the usual port")); } // An IP address in the link skips DNS, so check it here. if (isIP(host) && !isPublic(host)) { return Promise.reject(new Error(`${host} is not a public address`)); } return new Promise((resolve, reject) => { const req = request(url, { lookup: publicLookup, timeout: 5000 }, (res) => { const status = res.statusCode ?? 0; if (status >= 300 && status < 400 && res.headers.location) { res.resume(); if (redirectsLeft === 0) return reject(new Error("Too many redirects")); const next = new URL(res.headers.location, url).href; return resolve(fetchPublicPage(next, redirectsLeft - 1)); } let body = ""; res.setEncoding("utf8"); res.on("data", (chunk) => { body += chunk; if (body.length > 1_000_000) req.destroy(new Error("Page too large")); }); res.on("end", () => resolve(body)); }); req.on("timeout", () => req.destroy(new Error("Took too long"))); req.on("error", reject); req.end(); });}
  • https only, on the default port, with no username or password in the link. That alone shuts out most internal services, which speak plain http on unusual ports.
  • Every address the name resolves to must be public, checked in publicLookup, which is the lookup the connection itself uses. BlockList is built into Node; tested on Node 20, 22 and 25.
  • A link that is an IP address (https://127.0.0.1/) skips DNS, so it’s checked separately.
  • Redirects are followed by hand and each new address goes through the same checks, because a public page can redirect to an internal one.
  • Limits: 5 seconds and 1 MB, so a slow or endless page can’t tie up your server.

Use it in the route:

app/api/preview/route.tsts
import { type NextRequest } from "next/server";import { fetchPublicPage } from "@/lib/safe-fetch";// /api/preview?url=https://example.com returns that page's title,// to show a preview of a link someone pasted.export async function GET(request: NextRequest) { const url = request.nextUrl.searchParams.get("url"); if (!url) return Response.json({ error: "Add ?url=" }, { status: 400 }); try { const html = await fetchPublicPage(url); const title = html.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.trim() ?? null; return Response.json({ title }); } catch (error) { console.warn("Preview refused:", url, String(error)); return Response.json({ error: "That link can’t be previewed." }, { status: 400 }); }}
Terminalbash
curl -s "http://localhost:3000/api/preview?url=https://example.com"curl -s "http://localhost:3000/api/preview?url=http://localhost:3000/no-such-page"curl -s "http://localhost:3000/api/preview?url=https://localtest.me/"

The first still prints {"title":"Example Domain"}. The other two print {"error":"That link can’t be previewed."}, and the npm run dev terminal says why: “Only https:// links on the usual port”, and “localtest.me is not a public address”. localtest.me is a public domain whose address is 127.0.0.1; it’s a handy way to test that a guard checks the address, not the name. The visitor gets a plain refusal, and the details stay in your logs.

7. Secrets that reach the browser

Your database URL, API keys and signing secrets must never reach a browser. There are two ways they do:

  • The NEXT_PUBLIC_ prefix. Next.js copies every NEXT_PUBLIC_… variable your client code uses into the JavaScript it sends to every visitor. That’s right for a Stripe publishable key or an analytics ID, and a leak for anything else. A secret never gets the prefix, even if it makes an error go away.
  • Importing server code into a client component. A "use client" file takes everything it imports into the browser. That’s why lib/tasks-admin.ts starts with import "server-only": try using deleteAllTasks in app/tasks/add-task-form.tsx: add import { deleteAllTasks } from "@/lib/tasks-admin"; below its imports and console.log(deleteAllTasks); below that, then run npm run build. It stops with several errors. The one that says what happened is “'server-only' cannot be imported from a Client Component module”; ignore the others, which are side effects (one wrongly mentions the Pages Router, and pg can’t find dns, because database code was pulled towards the browser). Remove both lines again. Put import "server-only" at the top of every file that reads a secret, except files a plain Node script also uses, like lib/prisma.ts, which the seed script imports: outside Next.js, server-only throws.

After any change that touches secrets, check the files the browser downloads. They’re in .next/static after a build. Your database URL starts with postgresql://, so search for that:

Terminalbash
npm run buildgrep -rl "postgresql://" .next/static || echo "Not in the browser's files"

It prints “Not in the browser's files”. If it ever prints a file name instead, that file is sent to every visitor: find which import brought the secret in, and change the secret, because it has already been published. Do the same search for any key you add, using a piece of the key itself.

8. Security headers

A few response headers make whole kinds of attack impossible, and Next.js sends none of them by default. Check what your app sends now:

Terminalbash
curl -sI http://localhost:3000/tasks

Among Next.js’s own headers is X-Powered-By: Next.js, which tells attackers what to try first. Add these lines inside the nextConfig object in next.config.ts (after its opening {, keeping what’s already there):

next.config.ts (add inside nextConfig)ts
poweredByHeader: false, async headers() { return [ { source: "/:path*", headers: [ { key: "X-Content-Type-Options", value: "nosniff" }, { key: "X-Frame-Options", value: "DENY" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" }, { key: "Content-Security-Policy-Report-Only", value: [ "default-src 'self'", // npm run dev needs eval for React's debugging tools; a build doesn't. process.env.NODE_ENV === "development" ? "script-src 'self' 'unsafe-inline' 'unsafe-eval'" : "script-src 'self' 'unsafe-inline'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob:", "font-src 'self'", "connect-src 'self'", "object-src 'none'", "base-uri 'self'", "form-action 'self'", "frame-ancestors 'none'", ].join("; "), }, ], }, ]; },
  • poweredByHeader: false drops X-Powered-By.
  • X-Content-Type-Options: nosniff: the browser treats a file only as the type the server says, so a file uploaded as an image isn’t run as a script or shown as a page because of what its bytes look like.
  • X-Frame-Options: DENY (and frame-ancestors 'none' in the policy): no other site can show your pages inside a frame, where a hidden page can trick a click (“clickjacking”).
  • Referrer-Policy: other sites see only your domain when a visitor follows a link, never the full address, which may contain a token.
  • Permissions-Policy: no page may ask for the camera, microphone or location. Add any your app really uses.
  • Content-Security-Policy lists where scripts, styles, images and connections may come from, so an injected <script src="https://evil…"> is refused. 'unsafe-inline' is still needed, because Next.js puts small scripts in every page.

The policy is sent as -Report-Only: the browser obeys nothing yet, it only logs in the console what it would block. A wrong policy can break your own site (an analytics script, a payment form, fonts from another server), so watch it first. Restart npm run dev, then:

Terminalbash
curl -sI http://localhost:3000/tasks

The five headers are there, and X-Powered-By is gone. Click around your app with the browser’s console open: there should be no “violates the following Content Security Policy directive” messages. When a week in production has passed with none, rename Content-Security-Policy-Report-Only to Content-Security-Policy to enforce it. Every time you add a third-party script or service later, add its address to the policy in the same change. That’s what we do on this site.

A checklist for every new feature

  • Does it redirect to a value from the URL? Use safePath.
  • Is it a server action? Check the caller and every argument inside it. Is the file exporting anything that isn’t an action?
  • Can a script repeat it? Sending email, signing in, creating rows, anything that costs money: give it a rate limit.
  • Does it show text someone else wrote? Render it with {…}, never dangerouslySetInnerHTML without a sanitizer.
  • Does it export data? csvCell on every value.
  • Does your server fetch a URL a user gave? Only through fetchPublicPage.
  • Does it add a secret? No NEXT_PUBLIC_, server-only on the file, and search .next/static for it after a build.
  • Does it add a third-party script or service? Add it to the Content Security Policy.

If something goes wrong

  • curl in step 2 prints nothing and the tasks are still there. Check that you pasted the ID from the deleteAllTasks line, and that npm start (not npm run dev) is running: the IDs come from that build.
  • Cannot find module './.next/server/server-reference-manifest.json'. Run npm run build first; the file only exists after a build.
  • The table "public.RateLimit" does not exist. Run npx prisma migrate dev --name rate-limits (step 3), then restart npm run dev.
  • “That’s a lot of tasks at once” while doing steps 4 and 5. The limit from step 3 is working. Wait a minute.
  • “'server-only' cannot be imported from a Client Component module”. A client component imports a file marked server-only, directly or through another file (the build prints the chain under “Import traces”). Pass the data from a server component as props, or call an action, instead.
  • The preview refuses a real website. Only https:// links on the usual port are fetched, by design. The npm run dev terminal prints the reason for every refusal.
  • The console shows “Evaluating a string as JavaScript violates…”. Under npm run dev that means the NODE_ENV line in the policy is missing; in a build, something really uses eval, so find out what before allowing it.

Questions people ask

What is an open redirect?

A redirect that takes its destination from the URL and can be tricked into sending people to another site, so your domain becomes a trusted-looking link to anywhere. Checks like “starts with / but not //” miss tricks such as /\example.com. Let the URL parser resolve the value against your own address, and keep it only if it’s still on your site.

Are Next.js server actions public?

Yes. Every exported async function in a "use server" file is an endpoint anyone can call with a POST, whether a page uses it or not. So a "use server" file should export actions and nothing else, and every action should check who’s calling and every value it receives, inside the action itself.

Does React protect me from XSS?

Mostly. React escapes every string you render with {…}, so a title someone typed shows up as plain text. The exception is dangerouslySetInnerHTML, which hands raw HTML to the browser. Don’t use it for anything a user wrote, and if you really must show their HTML, clean it with a sanitizer like DOMPurify first.

How do I check no secrets end up in the browser?

Build the app, then search .next/static (the files the browser downloads) for a piece of each secret. Your database URL starts with postgresql://, so search for that. If a file name comes back, find the import that pulled it in, and change the secret too: it has already been published.

Where to go next

  • Add accounts with Better Auth, and check the session at the top of every server action.
  • If you take payments, the Stripe guide shows why webhooks must verify their signature, and why the success page must never grant access by itself.
  • The other holes from our review need accounts or uploads, so they’re not in this app: trusting a “passed” result the browser reports (check it again on the server), images decoded before their bytes were checked, admin checks reading a cached session (read it fresh), and admin accounts without two-factor sign-in.
  • OWASP’s Cheat Sheet Series covers each of these holes, and many more, in depth.
Found this useful? Give it a heart, or share it with someone who’d use it.
WRITTEN BY
Ali Murtaza

I build SaaS products with Next.js and teach them start to finish, in full courses here and free builds on YouTube.

KEEP READING
FREE BUILDS ON THIS STACK