← All guides

Next.js Security Headers and Content Security Policy: A Copy-Paste Setup

Updated 2026-11-03

Short answer: add security headers in next.config.ts with the headers() function: Strict-Transport-Security, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, X-Frame-Options: DENY (or frame-ancestors 'none'), Permissions-Policy, and a Content-Security-Policy that allowlists only the domains your app actually uses, such as Supabase and Stripe. Start the CSP in report-only mode, fix what breaks, then enforce it. If you use output: "export" or a Vite app from Lovable or Bolt, set headers in your host's config instead, because next.config headers don't apply there.

Most apps built with Lovable, Bolt, v0, Cursor or Replit ship with none of these headers. That isn't a vulnerability on its own, but headers are your second line of defense: a good CSP can stop an XSS bug from turning into stolen sessions, and frame protection stops clickjacking. Scanners, security questionnaires and enterprise buyers check for them too.

What each header does

Header Recommended value Protects against
Content-Security-Policy See below XSS, injected scripts, data sent to attacker domains
Strict-Transport-Security max-age=63072000; includeSubDomains; preload Downgrade to plain HTTP
X-Content-Type-Options nosniff Browsers treating uploads as scripts
X-Frame-Options DENY Clickjacking in old browsers
Referrer-Policy strict-origin-when-cross-origin Leaking full URLs (and tokens in them) to other sites
Permissions-Policy camera=(), microphone=(), geolocation=() Third party scripts using device features

Only add preload to HSTS if every subdomain serves HTTPS and you plan to submit the domain to the preload list. Leaving it out is fine.

Step 1: Static headers in next.config.ts

This works for apps deployed to Vercel, Node servers and most Next.js hosts:

// next.config.ts
import type { NextConfig } from "next";

const csp = [
  "default-src 'self'",
  "script-src 'self' 'unsafe-inline' https://js.stripe.com",
  "style-src 'self' 'unsafe-inline'",
  "img-src 'self' data: blob: https://*.supabase.co",
  "font-src 'self'",
  "connect-src 'self' https://*.supabase.co wss://*.supabase.co https://api.stripe.com",
  "frame-src https://js.stripe.com https://hooks.stripe.com",
  "frame-ancestors 'none'",
  "base-uri 'self'",
  "form-action 'self'",
  "object-src 'none'",
].join("; ");

const securityHeaders = [
  { key: "Content-Security-Policy-Report-Only", value: csp },
  { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains" },
  { 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=()" },
];

const nextConfig: NextConfig = {
  poweredByHeader: false,
  async headers() {
    return [{ source: "/:path*", headers: securityHeaders }];
  },
};

export default nextConfig;

Notes on the policy:

Step 2: Report first, then enforce

Breaking your own login page with a CSP is easy. The config above uses Content-Security-Policy-Report-Only, which logs violations in the browser console without blocking anything.

  1. Deploy with the report-only header.
  2. Click through every flow: sign up, log in, OAuth redirects, checkout, file uploads, anything with a third party widget.
  3. Open the browser console and note each "violates the following Content Security Policy directive" message.
  4. Add the missing domains (only ones you recognize and use).
  5. Rename the header key to Content-Security-Policy to enforce it.

In local development, React needs 'unsafe-eval' for some debugging features. Add it only when process.env.NODE_ENV === "development", never in production.

Step 3: Strict CSP with nonces (optional)

For a policy without 'unsafe-inline', Next.js supports per request nonces set in middleware. The App Router picks up the nonce from the CSP header and applies it to its own scripts:

// middleware.ts
import { NextResponse, type NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
  const csp = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,
    "style-src 'self' 'unsafe-inline'",
    "connect-src 'self' https://*.supabase.co wss://*.supabase.co",
    "frame-ancestors 'none'",
    "object-src 'none'",
    "base-uri 'self'",
  ].join("; ");

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-nonce", nonce);
  requestHeaders.set("Content-Security-Policy", csp);

  const response = NextResponse.next({ request: { headers: requestHeaders } });
  response.headers.set("Content-Security-Policy", csp);
  return response;
}

export const config = {
  matcher: [{ source: "/((?!api|_next/static|_next/image|favicon.ico).*)" }],
};

The tradeoff: nonces require rendering each page per request, so pages can't be statically generated or cached at the CDN. For most small apps, the next.config version from Step 1 is the better balance. Remove the CSP from next.config if you set it here, so you don't send two conflicting policies.

Static exports, Lovable and Bolt apps

headers() in next.config only runs when Next.js serves the request. It does nothing with output: "export", and Lovable and Bolt apps are usually Vite single page apps with no Next.js server at all. Set headers on the host instead.

Netlify or Cloudflare Pages (public/_headers, copied into the build output):

/*
  Content-Security-Policy: default-src 'self'; script-src 'self'; connect-src 'self' https://*.supabase.co wss://*.supabase.co; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'; object-src 'none'
  Strict-Transport-Security: max-age=63072000; includeSubDomains
  X-Content-Type-Options: nosniff
  X-Frame-Options: DENY
  Referrer-Policy: strict-origin-when-cross-origin

Vercel (vercel.json):

{
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        { "key": "X-Content-Type-Options", "value": "nosniff" },
        { "key": "X-Frame-Options", "value": "DENY" },
        { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }
      ]
    }
  ]
}

Vite production builds don't need inline scripts, so a Vite SPA can often use script-src 'self' without nonces.

Check your headers

curl -sI https://yourapp.com | grep -iE "content-security|strict-transport|x-frame|x-content-type|referrer-policy|permissions-policy"

Check a few paths, not just the home page, and check your API routes too. If a header is missing on some routes, your source pattern or middleware matcher probably doesn't cover them.

What headers don't fix

Headers reduce the damage from bugs. They don't replace fixing them:

Get an automated check

PreflightPR reviews AI-built apps for missing security headers, unprotected API routes, leaked keys, missing Supabase RLS and other launch blockers. Run a free scan on a public repo for a launch score and a prioritized fix list, or install the PreflightPR GitHub App to check every pull request before it merges. For everything else to check before launch, see the pre-launch security checklist for AI-built apps.

Check your repo in about a minute

Paste a public GitHub URL and get a free launch score.

Run a free scan

More guides