Loading…
Loading documentation...
What each OWASP Top 10 2025 risk looks like in a Next.js 16 app, the change that closes it, and a command that shows it is closed.
Commands checked on 2026-10-27 with Next.js 16, Node.js 24, OWASP Top 10 2025.
A Next.js app whose responses carry security headers and no X-Powered-By, whose API routes refuse a request without valid credentials and log the refusal, whose session cookie cannot be read by scripts or sent from other sites, and whose errors reach the log but never the visitor. You will also have checked its dependencies and know how to store passwords and make tokens. Each of the ten OWASP Top 10 2025 risks is named where it is closed.
~/nextapp, the service nextapp, the secrets in /etc/nextapp/env.Work in the app's folder:
cd ~/nextapp
mkdir -p app/api/notes app/api/session app/api/lookup
Next.js adds X-Powered-By: Next.js to every response unless you turn it off, which tells an attacker what to try. The headers below stop browsers guessing content types, keep the page out of other sites' frames, trim the referrer sent to other sites, and turn off device features the app does not use.
cat > next.config.ts <<'EOF'
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
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=()" },
],
},
];
},
};
export default nextConfig;
EOF
Behind HTTPS, add Strict-Transport-Security at the web server in front of the app. A Content-Security-Policy needs a nonce for the scripts Next.js writes into each page; Next.js documents that setup in its own Content Security Policy guide.
Route handlers and server actions are public addresses: anyone can call them without your pages. Each one checks who is asking before it does anything, and a refusal is written to the log so it can be counted. A lookup by id must also check that the record belongs to the caller; a guessable id is not a permission.
cat > app/api/notes/route.ts <<'EOF'
import { NextResponse, type NextRequest } from "next/server";
// Replace with your own session lookup. The demo accepts one bearer token from the environment.
function currentUser(request: NextRequest) {
const token = request.headers.get("authorization")?.replace(/^Bearer /, "");
return token && process.env.DEMO_TOKEN && token === process.env.DEMO_TOKEN ? { id: "demo-user" } : null;
}
export async function GET(request: NextRequest) {
const user = currentUser(request);
if (!user) {
console.warn(JSON.stringify({ event: "auth_failed", path: request.nextUrl.pathname }));
return NextResponse.json({ error: "Sign in first" }, { status: 401 });
}
return NextResponse.json({ owner: user.id, notes: [] });
}
EOF
sudo sh -c 'printf "DEMO_TOKEN=%s\n" "$(openssl rand -hex 16)" >> /etc/nextapp/env'
httpOnly keeps the cookie away from JavaScript, so a script injected into a page cannot steal it. secure sends it only over HTTPS, and sameSite: "lax" stops other sites' forms from sending it with a request.
cat > app/api/session/route.ts <<'EOF'
import { cookies } from "next/headers";
import { randomBytes } from "node:crypto";
export async function POST() {
const store = await cookies();
store.set("session", randomBytes(32).toString("base64url"), {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 8,
});
return new Response(null, { status: 204 });
}
EOF
Use a maintained sign-in library for the rest: password reset, rate limits on sign-in, and a second factor.
When something breaks, the answer is a refusal, never the success path by default, and the details go to the log, not to the visitor. A route that throws gets an empty 500 from Next.js in production while the error and its stack go to the journal.
cat > app/api/lookup/route.ts <<'EOF'
import { NextResponse, type NextRequest } from "next/server";
export async function GET(request: NextRequest) {
const id = request.nextUrl.searchParams.get("id");
if (!id || !/^\d+$/.test(id)) {
return NextResponse.json({ error: "id must be a number" }, { status: 400 });
}
// A failed dependency must never fall through to "allowed". Throwing ends the request with a 500.
throw new Error("order lookup failed: the database did not answer");
}
EOF
The same release steps as the systemd guide, then a restart so the app reads DEMO_TOKEN.
npm run build
sudo cp -a .next/standalone/. /srv/nextapp/
sudo cp -a .next/static /srv/nextapp/.next/
sudo chown -R root:root /srv/nextapp
sudo chown nextapp:nextapp /srv/nextapp/.next/cache
sudo systemctl restart nextapp
Most of the code in your app is other people's. npm audit reports known vulnerabilities in what is installed, and npm audit signatures checks that each package's registry signature is valid, so a tampered download is caught. npm ci installs exactly the lockfile, and refuses a package whose content does not match the checksum recorded there.
npm audit --omit=dev --audit-level=high
npm audit signatures
The first ends with found 0 vulnerabilities when nothing is known, and exits with an error when a high or critical one is found. The second reports how many packages have verified registry signatures. For what to do with a finding, see Read an npm audit report and decide what to do.
A password is stored only as a slow, salted hash, so a copied database does not give the passwords away. scrypt is in Node.js itself. Tokens and session ids come from randomBytes, never Math.random, which can be predicted.
node -e '
const { scryptSync, randomBytes, timingSafeEqual } = require("node:crypto");
const salt = randomBytes(16);
const stored = scryptSync("correct horse battery staple", salt, 64);
const check = (attempt) => timingSafeEqual(stored, scryptSync(attempt, salt, 64));
console.log(check("correct horse battery staple"), check("wrong guess"));
console.log(randomBytes(32).toString("base64url").length);
'
It prints true false, then 43: a 32-byte token is 43 characters in base64url. Store the salt next to the hash, and use HTTPS for every page, so nothing travels in clear text.
Injection happens when input becomes part of a command. Pass values to the database as parameters (query("SELECT * FROM notes WHERE id = $1", [id]) with node-postgres), never by joining strings. React escapes what you render, so the risk in a Next.js app is dangerouslySetInnerHTML; this lists every use, and each one must render only HTML you have sanitised:
grep -rn "dangerouslySetInnerHTML" app || echo "no raw HTML"
A new app prints no raw HTML.
Some risks are not one bad line but a missing rule: a sign-in form with no limit on attempts, a coupon that can be applied twice, an export with no cap on rows. For each feature, write down who may use it, how often, and what it must never allow, then make the server enforce each rule. Limit requests per address at the web server in front of the app, and limit each user's actions in the app itself.
With the new version running, ask it as a visitor would:
curl -sI --retry 5 --retry-connrefused --retry-delay 1 http://127.0.0.1:3000/ | grep -i -E '^(x-powered-by|x-content-type-options|x-frame-options|referrer-policy|permissions-policy):'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:3000/api/notes
TOKEN=$(sudo sed -n 's/^DEMO_TOKEN=//p' /etc/nextapp/env)
curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:3000/api/notes; echo
curl -s -i -X POST http://127.0.0.1:3000/api/session | grep -i '^set-cookie:'
curl -s -w '\n%{http_code}\n' 'http://127.0.0.1:3000/api/lookup?id=abc'
curl -s -w '\n%{http_code}\n' 'http://127.0.0.1:3000/api/lookup?id=42'
sudo journalctl -u nextapp -n 30 --no-pager | grep -c -E 'auth_failed|order lookup failed'
In order: the four headers and no x-powered-by; 401 without a token; {"owner":"demo-user","notes":[]} with it; a cookie ending in Secure; HttpOnly; SameSite=lax; {"error":"id must be a number"} and 400 for input that is not an id; an empty body and 500 when the lookup fails; and a count of at least 2, because the refusal and the error are both in the journal.
X-Powered-By is still there. The running copy was built before the change. Build again and put the new .next/standalone in place, then restart.401 even with the token. The app started before DEMO_TOKEN was in its environment. Restart it, then check with sudo cat /proc/$(systemctl show nextapp -p MainPID --value)/environ | tr '\0' '\n' | grep -c '^DEMO_TOKEN=', which prints 1.Secure, or the browser drops it. A secure cookie is only stored by a browser over HTTPS. That is correct in production; on a plain http:// development address the browser ignores it.NODE_ENV=production.npm audit in CI.Every Servers Are Up virtual machine and container includes an integrated HTML5 browser-based SSH, RDP, and VNC console in your dashboard, default-off inbound firewall rules with per-IP allow-lists, and full programmatic control via REST API v1 and Model Context Protocol (MCP). Explore our Virtual Datacenter Plans or reach out to Servers Are Up Support.