Next.js Security
Next.js Security: CSP Headers, Environment Secrets, and XSS Defense
Next.js security is about keeping your users and your backend data safe from Cross-Site Scripting (XSS), leaked credentials, and unauthorized Server Action calls. React escapes text in JSX by default, so ordinary string interpolation is safe. The risks sit around that default: HTTP headers, the boundary between server and client code, and any place where you bypass React's escaping. This lesson covers Content Security Policy (CSP) headers, environment variables, HTML sanitization, and the mistakes that most often cause leaks.
The guiding rule is to treat everything that crosses the browser boundary as untrusted. That includes form fields, query strings, cookies, and the arguments of Server Actions. If you validate and authorize on the server, most injection attacks never reach your database.
Setting Security and CSP Headers middleware.ts
Apply Content Security Policy (CSP) and frame protection headers in middleware.ts so browsers only execute approved scripts and cannot embed your app in hidden iframes.
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware() {
const response = NextResponse.next();
const csp = [
"default-src 'self'",
"script-src 'self' 'unsafe-inline'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"object-src 'none'",
"frame-ancestors 'none'",
].join('; ');
response.headers.set('Content-Security-Policy', csp);
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
return response;
}
How to Check Your Headers
Start the app and
run curl -I http://localhost:3000.You should seecontent-security-policy, x-content-type-options, andreferrer-policy in the output.Open the browser DevTools Console. Blocked resources are reported as CSP violations with the directive that caused them.
Test in a production build (
next buildthennext start), because development mode behaves differently.
Protecting Server Environment Variables
Next.js keeps environment variables on the server unless their name starts with NEXT_PUBLIC_. Variables with that prefix are inlined into the JavaScript bundle at build time, which means anyone can read them in the browser. Never add the prefix to database passwords, JWT secrets, or private API tokens.
DATABASE_URL="postgresql://user:pass@localhost:5432/app"
STRIPE_SECRET_KEY="sk_live_example_key"
NEXT_PUBLIC_SITE_URL="https://example.com"In this file, DATABASE_URL and STRIPE_SECRET_KEY stay on the server. NEXT_PUBLIC_SITE_URL is public by design, since a site URL is not a secret. Because public values are baked in at build time, changing one in production requires a rebuild.
To confirm a secret has not leaked, run a production build and search the client output:
grep -r "sk_live" .next/staticIf this finds a match, a secret has been bundled for the browser, and you need to find which file imported it.
Sanitizing Untrusted HTML Safely
Rendering plain text through JSX is safe. The danger starts when you must show HTML written by users or a third-party editor, which requires dangerouslySetInnerHTML. The name is a warning: React will insert whatever you give it, scripts included. Sanitize the markup first withisomorphic-dompurify, which works on both the server and the client:
// app/components/SafeRichText.tsx
import DOMPurify from 'isomorphic-dompurify';
export default function SafeRichText({ html }: { html: string }) {
const cleanHtml = DOMPurify.sanitize(html);
return <div dangerouslySetInnerHTML={{ __html: cleanHtml }} />;
}
A few practical points:
Sanitize right before rendering, and don't modify the string afterward. Changes after sanitizing can reintroduce unsafe content.
If you only need text, skip HTML entirely and render it as a normal JSX string.
Sanitizing does not cover everything. If you build links from user input, such as
<a href={userUrl}>, check that the URL starts withhttp:orhttps:, because javascript: URLs are a separate attack path.
Common Mistakes
Importing server helpers into
'use client'files: Install theserver-onlypackage and import'server-only'at the top of secret modules so builds fail fast if accidentally bundled for the browser.Trusting client-supplied user IDs in Server Actions: Always read the user ID from the verified server session rather than hidden form inputs.
Committing
.env.localfiles to Git: Keep.env*secrets out of version control and store production keys in your hosting provider's secret manager.
Frequently Asked Questions
Are Server Actions protected against CSRF attacks automatically?
Next.js verifies the Origin and Host headers on Server Action POST requests and restricts them to POST, helping mitigate CSRF by default.
Does server-only add anything to my runtime bundle?
No, server-only is a zero-runtime marker package that triggers a clear build error if a Client Component imports that file.
Should I serialize full ORM models into Client Components?
No, map database rows into explicit DTO objects containing only public fields before passing props to 'use client' components.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With