Security10 min read

HTTP Security Headers for Next.js SaaS: The 2026 Configuration Guide

Missing HTTP security headers leave Next.js SaaS apps open to clickjacking, XSS, and MITM attacks. Configure CSP, HSTS, and all 7 headers correctly in 2026.

HTTP security headers are the browser's last line of defense against a class of attacks that server-side code cannot prevent on its own. Content-Security-Policy blocks cross-site scripting at the browser level. HSTS forces every connection over HTTPS. X-Frame-Options and its modern replacement, CSP frame-ancestors, prevent clickjacking. These are not advanced hardening steps — they are baseline protections that every production SaaS application should have. The problem is that Next.js does not add any of them by default, and neither do the AI-assisted builders that generate most SaaS applications today.

Research published in mid-2026 scanned 100 production apps built with Lovable, Bolt.new, Cursor, and v0.dev and found that security headers were missing or misconfigured in roughly 20% of them. Apps built with full-stack AI builders scored lowest — Lovable averaged a 58/100 security score, Bolt.new 66/100 — while apps built with AI code editors that assist a developer (Cursor, Windsurf) scored higher because a developer was in the loop. The pattern is consistent with what we find in every Belsoft security audit: missing headers are almost never intentional. They are simply not generated by any tool in the vibe-coding stack, and developers don't miss what they never see.

This guide covers the seven headers every Next.js SaaS application needs, what each one prevents, how to configure them in next.config.ts, and how to verify they are set correctly before launch. If you are preparing a vibe-coded app for real users, read this alongside the SaaS pre-launch security checklist — headers are one layer of a broader set of controls that together define a defensible production posture.

Why Next.js SaaS Applications Ship Without Security Headers

Next.js does not set any HTTP security headers by default. Create-next-app produces a project with no headers() configuration in next.config.ts, and the framework's defaults include only the headers required for the protocol to function. This is a deliberate framework design choice: Next.js is a general-purpose framework used for everything from static marketing sites to complex multi-tenant platforms, and the right security headers for each are different.

  • →AI builders don't generate headers by default. Lovable, Bolt.new, v0, and Cursor generate functional applications but do not write security headers into the initial scaffold. When a developer or AI assistant adds authentication, billing, or multi-tenancy, headers don't come up — they aren't part of a feature.
  • →Missing headers don't cause visible errors. A misconfigured CSP will break your app. A missing CSP will not. This asymmetry means absent headers can persist through every sprint, every code review, and every test run without triggering anything that surfaces them as an issue.
  • →Security scanners run as a final step, if at all. Most early-stage SaaS teams add security review when they're responding to a customer questionnaire or preparing for a SOC 2 audit. By that point, headers may have been absent for a year or more.
  • →Deployment platforms don't add them either. Vercel, Netlify, and AWS Amplify do not inject security headers on behalf of the application. The application is responsible for its own headers. The platform is responsible for delivering them.

Content-Security-Policy: Preventing XSS at the Browser Level

Content-Security-Policy (CSP) is the most powerful security header and the hardest to configure for a Next.js application. It instructs the browser to only execute scripts, load stylesheets, and display images from sources you explicitly permit. When a cross-site scripting (XSS) vulnerability exists — an attacker injects a script into the page — the browser refuses to execute the injected script if the CSP would block it. CSP is not a replacement for fixing XSS vulnerabilities, but it is a critical second layer of defense when injection is possible.

  • →The challenge with Next.js is inline scripts. Next.js uses inline scripts internally for hydration, and third-party scripts loaded via next/script can inject inline code. A strict CSP with script-src 'self' will break both. The correct approaches are nonces (a per-request random value added to each allowed inline script tag, enforced at the HTTP header) or hashes (a base64 SHA-256 of the exact script content, listed in the CSP). Nonces require middleware that regenerates the value on each request; hashes require knowing the exact script content at build time.
  • →Start with Content-Security-Policy-Report-Only. Before enforcing a CSP, deploy it in report-only mode. The browser sends a JSON report every time a resource would have been blocked, without actually blocking it. Run the app for a week in report-only, collect the violations, and use them to refine the policy until there are no legitimate violations before switching to enforcement.
  • →default-src 'self' is the starting point. Set default-src to 'self' and then add explicit allowances for each required source. Common additions: script-src adds the per-request nonce for Next.js inline scripts; style-src adds 'unsafe-inline' for CSS-in-JS; img-src adds your CDN and data: for inline images; connect-src adds your API domain and any third-party endpoints your app calls.
  • →frame-ancestors 'none' replaces X-Frame-Options DENY. Add frame-ancestors 'none' to your CSP directive instead of relying only on X-Frame-Options. Modern browsers prefer the CSP directive, and it offers more granular control — you can allow specific trusted origins with frame-ancestors 'self' https://trusted-parent.example.com.
  • →Never add unsafe-eval or unsafe-inline to work around a violation. If your CSP is blocking something, diagnose the actual cause and fix it properly. unsafe-eval enables eval(), which is the primary execution surface for certain XSS payloads. unsafe-inline eliminates the XSS protection entirely. These are not acceptable workarounds for a production SaaS application.

HSTS: Ensuring Every Visit Uses HTTPS

HTTP Strict Transport Security (HSTS) tells the browser to never send an unencrypted request to your domain — not on the first visit (after the first HTTPS response), and not for any subdomain if you include includeSubDomains. Without HSTS, a browser that visits your app over HTTP before redirecting to HTTPS can be intercepted. The HTTPS redirect happens on the server, but a network-level attacker can intercept the initial HTTP request before the redirect occurs. HSTS eliminates that window.

  • →Set a max-age of at least 1 year (31536000 seconds) for production. The max-age tells the browser how long to cache the HSTS policy. During this period, the browser will refuse to connect to your domain over HTTP without first upgrading to HTTPS. A common starting value is 63072000 (2 years). Start lower — 86400 (1 day) — while testing to avoid locking out users if you need to roll back HTTPS.
  • →Add includeSubDomains if all your subdomains serve HTTPS. This extends HSTS protection to every subdomain. Only add this directive if every subdomain of your domain is on HTTPS — a subdomain that serves HTTP would become inaccessible to users who have cached the HSTS policy with includeSubDomains set.
  • →Consider preload for maximum protection. HSTS preloading submits your domain to a list that browsers ship with. Even users who have never visited your site before get HSTS enforced on the first connection. Requirements: max-age must be at least 1 year, includeSubDomains must be set, and you must add the preload directive. Preloading is effectively permanent within a browser release cycle — research the implications carefully before opting in.
  • →Avoid HSTS on staging and development domains. Setting HSTS on a staging domain that may switch between HTTP and HTTPS or be decommissioned can cause hard-to-diagnose access errors. Apply HSTS only on production domains with stable HTTPS.

X-Content-Type-Options, Referrer-Policy, and Permissions-Policy

Three shorter headers handle specific attack vectors and are low-risk to add immediately. Each targets a distinct browser behavior that becomes an attack surface when uncontrolled.

  • →X-Content-Type-Options: nosniff prevents MIME-type sniffing attacks. Without it, browsers may ignore the Content-Type you declare for a response and attempt to infer the type from the content — a behavior attackers can exploit to serve a malicious script as a plain text file. Setting this to nosniff tells the browser to trust the declared Content-Type and not guess. It is a one-liner with no downsides for a correctly-typed application.
  • →Referrer-Policy: strict-origin-when-cross-origin controls what URL the browser includes in the Referer request header. The default browser behavior sends the full URL as the referrer on cross-origin requests, which can leak sensitive path information (session IDs in query strings, internal admin routes, customer IDs) to third-party services you load. strict-origin-when-cross-origin sends only the origin (domain) on cross-origin requests — never the path — and sends the full URL only for same-origin requests.
  • →Permissions-Policy: restrict browser API access. Permissions-Policy lets you opt out of browser APIs your application doesn't use. If your SaaS app doesn't need to access the user's camera, microphone, or geolocation, declare that explicitly. An XSS payload or injected third-party script cannot request access to those APIs if the page has already declared them off-limits. A conservative starting policy: camera=(), microphone=(), geolocation=(), usb=(), interest-cohort=().
  • →X-Frame-Options: DENY or SAMEORIGIN. This header controls whether browsers allow your page to be embedded in an iframe on another origin. DENY prevents embedding anywhere. SAMEORIGIN allows embedding only from the same origin. Use DENY unless you have an explicit reason to allow framing. Modern browsers prefer the CSP frame-ancestors directive — set both for maximum browser compatibility.

Configuring All Headers in next.config.ts

In Next.js, HTTP headers are configured via the headers() async function in next.config.ts. This function returns an array of route pattern and header pairs. Apply a shared headers array to all routes by using the source pattern '/(.*)', which matches every URL. Next.js injects these headers on every server response, including HTML pages, API routes, and static assets. The same approach is part of the broader Next.js Server Actions security checklist — security headers and proper server-side validation are complementary layers.

  • →The headers() function takes a source (URL pattern) and headers (array of key/value name-value pairs). To apply headers globally, use a single entry with source: '/(.*)'.
  • →Security headers cannot be set via Edge Middleware for all response types. Middleware can add headers to HTML responses, but Next.js API routes and static assets served from the CDN require the next.config.ts headers() configuration. Use both if you need to generate a per-request nonce in middleware for CSP.
  • →Order matters for CSP and existing headers. If a response already sets a header in a specific route handler, the headers() configuration does not override it by default. Add key: 'Content-Security-Policy', value: '...', overriding: true to a header entry to force the override.
  • →API routes need a different header set. API routes that return JSON do not need a CSP — there is no browser rendering context. They do need CORS headers, X-Content-Type-Options, and appropriate Cache-Control. Use distinct source patterns in headers() to target /api/* routes with a narrower set and all other routes with the full security headers.
  • →Test locally before deploying. After adding headers, run your app locally and use the browser Network tab to verify each header is present on HTML page responses. Check that your app still functions — if CSP is blocking resources, the browser console will log which directives are responsible.

Cross-Origin Isolation: COOP, COEP, and CORP

Three additional headers are needed for applications that use cross-origin resource isolation — specifically required for SharedArrayBuffer (used by WebAssembly threads and some performance-sensitive features) and for protection against Spectre-style side-channel attacks in browser contexts. Most SaaS applications don't need these initially, but they're worth understanding and enabling as your security posture matures.

  • →Cross-Origin-Opener-Policy: same-origin isolates your browsing context from documents loaded in popups or iframes from other origins. Set to same-origin to prevent cross-origin windows from accessing your window object.
  • →Cross-Origin-Embedder-Policy: require-corp requires that all resources loaded by your page either declare they permit cross-origin loading (via CORP or CORS) or are same-origin. Setting this alongside COOP enables a crossOriginIsolated browsing context, which is required for SharedArrayBuffer.
  • →Cross-Origin-Resource-Policy: same-origin prevents other origins from embedding your resources. If your SaaS hosts API responses, images, or scripts that should only be consumable by your own application, same-origin prevents them from being loaded by third-party pages.
  • →Enabling COOP and COEP together may break third-party integrations. Many third-party scripts, analytics tags, and payment iframes do not set the CORP headers required to load in a require-corp context. Audit your third-party dependencies before enforcing COEP. Start with Cross-Origin-Embedder-Policy: unsafe-none (the default) and move to require-corp only once you have verified compatibility.

Verifying Your Headers with DeployReady and securityheaders.com

Headers added in next.config.ts are only effective if they reach the browser. CDN caching, edge rewrites, and reverse proxies can strip or modify headers between your Next.js server and the user. Always verify headers on the actual deployed production URL, not just on your local development server. The fastest way to run an automated check is DeployReady, Belsoft's open-source CLI. It includes header checks as part of its 30+ point security scan and returns a 0-100 readiness score with a breakdown of which headers are missing or set to insecure values.

  • →Run npx deployready against your staging URL before every release. DeployReady's header checks cover the presence of HSTS, X-Content-Type-Options, X-Frame-Options, CSP, and Referrer-Policy, and flags headers that are present but set to insecure values — such as X-Frame-Options: ALLOWALL or Referrer-Policy: unsafe-url.
  • →Use securityheaders.com for a human-readable grade. Enter your production URL and get an A through F grade with explanations of each header's status. It is a quick visual confirmation after deployment and a useful tool to include in a launch checklist.
  • →Add header verification to your CI/CD pipeline. Run DeployReady or a curl-based header check as a post-deployment smoke test. If a deployment strips a critical header, fail the check and alert before the change reaches traffic.
  • →Re-verify after every CDN configuration change. CDN rules, WAF policies, and edge middleware can inadvertently remove headers. Treat header verification as an ongoing concern, not a one-time setup task.

Frequently Asked Questions

Do HTTP security headers affect Next.js performance?

No. HTTP security headers are small additions to response headers and have no meaningful impact on performance. CSP adds some processing overhead in the browser as it validates resource loads, but this is negligible compared to the XSS prevention benefit. The only performance consideration is CSP with nonces, which requires server-side nonce generation on each request — equivalent to setting a session cookie and not a bottleneck.

What is the difference between X-Frame-Options and CSP frame-ancestors?

Both headers control whether your page can be embedded in an iframe on another origin. X-Frame-Options is the older header and supports only DENY, SAMEORIGIN, and ALLOW-FROM (which modern browsers have dropped). CSP frame-ancestors replaces it with a more flexible syntax that supports a whitelist of specific origins. Modern browsers prefer frame-ancestors over X-Frame-Options when both are set. For maximum compatibility with older browsers, set both: X-Frame-Options: DENY and a CSP directive including frame-ancestors 'none'.

Will adding a strict CSP break my Next.js application?

It may, initially. Next.js uses inline scripts for hydration and third-party scripts loaded via next/script can inject inline code. A strict CSP with script-src 'self' and no unsafe-inline will block these. The correct approach is to deploy in Content-Security-Policy-Report-Only mode first, run your app for several days, review the violation reports, and use them to build an allowlist. Once no legitimate violations remain, switch to enforcement. Never add unsafe-eval or unsafe-inline to work around a CSP violation — diagnose and fix the actual cause.

Do Vercel deployments set security headers automatically?

No. Vercel does not inject security headers on behalf of the application. You must configure them in next.config.ts headers() or in vercel.json under the headers field. Vercel sets platform-level headers for caching and routing but no security headers. Your next.config.ts headers() configuration is the authoritative source, and you should verify headers on the actual Vercel production URL using DeployReady or securityheaders.com after each deployment.

Should I set security headers on Next.js API routes?

API routes that return JSON for programmatic consumption do not need CSP (there is no browser rendering context) but do benefit from X-Content-Type-Options: nosniff and appropriate CORS headers. API routes that render anything a browser displays — SSE streams, redirects to pages, file downloads — should have the full security header set. Apply the full set to HTML-serving routes and a narrower set to /api/* routes, using distinct source patterns in next.config.ts headers().

How Belsoft Helps Harden Next.js SaaS Applications

Security headers are the fastest win in a Next.js security audit — a configuration change that can be deployed in an afternoon and immediately improve your security posture against XSS, clickjacking, and MITM attacks. But headers are one layer. What they don't cover: missing authentication on API routes, insufficient tenant isolation, exposed secrets in client bundles, and the authentication gaps common in vibe-coded apps that bypass your headers entirely. DeployReady catches the automated checks in seconds — headers, HTTPS enforcement, exposed secrets, and 25+ additional controls. A Belsoft audit goes deeper: engineers who know how Next.js applications break test your auth, data access controls, and AI features by hand, then help you fix what they find and retest to close the loop.

If you shipped a Next.js SaaS application without going through a formal security review — whether built with AI tools or not — start with our security audit and scalability review. It covers headers, auth, data access, API authorization, and AI-specific attack surfaces including prompt injection and tool call validation. The output is a prioritized fix list, support through the remediation, and a retest to confirm the issues are closed.

“Security headers are the seatbelt of web security: simple to add, nearly invisible when present, and painfully obvious in their absence when something goes wrong.”

Written by

Marco Silva

Security Engineer, Belsoft Solutions

Ready to partner?

Let's talk about your company.

30 minutes. No pitch. We talk through how you run today and where AI and automation would help.

Book a free audit
logo

Your AI & automation transformation partner: we audit, build, and train your team, then stay embedded as you grow.

Member ofNVIDIA Inception Program

Copyright Ⓒ 2026 BelSoft. All Rights Reserved.

BELSOFT, LDA · NIPC 517893258 · Lisbon, Portugal