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.
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
/taskspage 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 devrunning in its own terminal unless a step says to stop it. Thecurlcommands 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:
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:
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:
And use it in app/go/route.ts:
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:
Now see what Next.js made of that file. Stop npm run dev (Ctrl+C), then build the app and list its server actions:
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:
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:
Move the helper into lib/tasks-admin.ts:
And take it out of app/tasks/actions.ts, which goes back to exactly the three actions it had:
Stop npm start (Ctrl+C), build again and list the actions:
Three lines: deleteAllTasks is no longer something the outside world can call. Put the starting tasks back, and start npm run dev again:
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:
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:
- The visitor is their IP address, from the
x-forwarded-forheader. 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.
$queryRawwith 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:
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:
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}:
Add the task Ship the **landing page** and “landing page” is bold. Now add this one:
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:
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:
Add a task with this title:
Then look at the file:
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:
And use it in the 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:
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:
- https only, on the default port, with no username or password in the link. That alone shuts out most internal services, which speak plain
httpon unusual ports. - Every address the name resolves to must be public, checked in
publicLookup, which is the lookup the connection itself uses.BlockListis 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:
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 everyNEXT_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 whylib/tasks-admin.tsstarts withimport "server-only": try usingdeleteAllTasksinapp/tasks/add-task-form.tsx: addimport { deleteAllTasks } from "@/lib/tasks-admin";below its imports andconsole.log(deleteAllTasks);below that, then runnpm 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, andpgcan’t finddns, because database code was pulled towards the browser). Remove both lines again. Putimport "server-only"at the top of every file that reads a secret, except files a plain Node script also uses, likelib/prisma.ts, which the seed script imports: outside Next.js,server-onlythrows.
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:
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:
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):
poweredByHeader: falsedropsX-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(andframe-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-Policylists 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:
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
{…}, neverdangerouslySetInnerHTMLwithout a sanitizer. - Does it export data?
csvCellon every value. - Does your server fetch a URL a user gave? Only through
fetchPublicPage. - Does it add a secret? No
NEXT_PUBLIC_,server-onlyon the file, and search.next/staticfor it after a build. - Does it add a third-party script or service? Add it to the Content Security Policy.
If something goes wrong
curlin step 2 prints nothing and the tasks are still there. Check that you pasted the ID from thedeleteAllTasksline, and thatnpm start(notnpm run dev) is running: the IDs come from that build.Cannot find module './.next/server/server-reference-manifest.json'. Runnpm run buildfirst; the file only exists after a build.The table "public.RateLimit" does not exist. Runnpx prisma migrate dev --name rate-limits(step 3), then restartnpm 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. Thenpm run devterminal prints the reason for every refusal. - The console shows “Evaluating a string as JavaScript violates…”. Under
npm run devthat means theNODE_ENVline in the policy is missing; in a build, something really useseval, 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.