Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 72 ยท Deployment and Production

Security Headers and Content Security Policy

Add HSTS, X-Frame-Options, Referrer-Policy and Permissions-Policy with next.config headers(), then build a nonce-based Content Security Policy in the proxy file.

Browsers have many safety switches, but most of them are off until your server turns them on. They are switched on with response headers: small instructions that say "never show this page inside another site", "only talk to me over HTTPS" or "only run scripts that I vouch for". Adding them takes an afternoon and blocks whole families of attacks, such as clickjacking and injected scripts.

This lesson shows the two places where Next.js lets you set them. Static headers that are the same for every request go into headers() in next.config.ts. A Content Security Policy (CSP) that needs a fresh random value for every request is set in the proxy file. Next.js cannot run on this site, so the real configuration appears in read-only blocks. The runnable examples are Node.js stand-ins that apply header rules to request paths and build a nonce-based policy, so you can see exactly what the browser would receive.

This lesson builds on Configuring Next.js (the headers() option) and Middleware and the Proxy File. The earlier Observability and Scaling lesson mentions security headers briefly; here you set them up in full.

Two places for headers

next.config.ts Static. Same value for every request.
proxy.ts Dynamic. A new nonce for each request.

Pick the simplest place that works.

1 / 2

The static headers

These headers do not change from request to request, so they belong in next.config.ts. The headers() function returns a list of rules. Each rule has a source pattern and the headers to add to matching paths.

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const securityHeaders = [
  { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
  { 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 = {
  async headers() {
    return [{ source: "/:path*", headers: securityHeaders }];
  },
};

export default nextConfig;

What each one does:

Header Meaning
Strict-Transport-Security (HSTS) After one HTTPS visit the browser refuses plain HTTP to this site for max-age seconds (63,072,000 is two years). preload is a request to join browsers' built-in lists, so only add it when every subdomain really serves HTTPS.
X-Content-Type-Options: nosniff The browser must trust the Content-Type you send instead of guessing, which stops an uploaded text file from being run as a script.
X-Frame-Options: DENY Other sites cannot put your pages in an <iframe>, which blocks clickjacking. Use SAMEORIGIN if you frame your own pages.
Referrer-Policy Controls how much of the current URL is sent in the Referer header when someone follows a link. strict-origin-when-cross-origin sends the full URL inside your site and only the origin elsewhere.
Permissions-Policy Turns browser features off for your page and any embedded frames. camera=() means "nobody may use the camera".

The source uses the same pattern syntax as redirects. /:path* matches everything. If several rules match one path, their headers are merged, and a later rule wins for a header with the same key. The stand-in below applies rules the same way, with a small matcher for :name and :name* patterns, so you can try different paths.

Node.js Which headers does a path get?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at /embed/42: the general rule says DENY, then the more specific rule overrides it with SAMEORIGIN. Put general rules first and exceptions after them.

What a CSP is for

The headers above are all-or-nothing switches. A Content Security Policy is a small language. It is a list of directives, and each directive names a kind of resource and the sources the browser may load it from:

TEXT
default-src 'self';
script-src 'self' 'nonce-abc123';
img-src 'self' data: https://images.example.com;
frame-ancestors 'none'

This policy says: by default load things only from my own origin; run scripts only from my origin or inline scripts carrying the nonce abc123; allow images from my origin, from data: URLs and from one image host; and let nobody frame the page (frame-ancestors is the modern replacement for X-Frame-Options). If an attacker manages to inject <script>steal()</script> into your page, the browser refuses to run it because it carries no valid nonce. That is why a CSP is the strongest defense against cross-site scripting (XSS).

A nonce is a random, single-use value. It must be new for every response: if it were fixed, an attacker could read it from one page and reuse it. That is exactly why a nonce cannot live in next.config.ts.

A nonce-based CSP in the proxy file

Next.js adds small inline scripts for hydration and streaming. A strict script-src would block them, unless they carry the nonce. Next.js reads the nonce from the request's Content-Security-Policy header and attaches it to its own scripts automatically. So the proxy file has three jobs: create the nonce, put the policy on the request headers (so Next.js can read it) and on the response headers (so the browser enforces it).

TypeScript
// proxy.ts (read-only; named middleware.ts before Next.js 16)
import { NextResponse, type NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
  const isDev = process.env.NODE_ENV === "development";

  const csp = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDev ? " 'unsafe-eval'" : ""}`,
    `style-src 'self' 'nonce-${nonce}'`,
    "img-src 'self' blob: data:",
    "font-src 'self'",
    "object-src 'none'",
    "base-uri 'self'",
    "form-action 'self'",
    "frame-ancestors 'none'",
    "upgrade-insecure-requests",
  ].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).*)",
      missing: [{ type: "header", key: "next-router-prefetch" }],
    },
  ],
};

Notes on the policy:

  • 'strict-dynamic' means scripts that a nonced script loads are trusted too, so you do not need to list every host.
  • 'unsafe-eval' appears only in development, because React's debugging tools need it. Never ship it.
  • object-src 'none' and base-uri 'self' close two old attack routes. form-action 'self' stops forms from posting to other sites.
  • The matcher skips static assets, which do not need a policy, and prefetch requests.

Server Components can read the nonce for their own <Script> tags:

TSX
// app/layout.tsx (read-only)
import { headers } from "next/headers";
import Script from "next/script";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const nonce = (await headers()).get("x-nonce") ?? undefined;
  return (
    <html lang="en">
      <body>
        {children}
        <Script src="https://widgets.example.com/chat.js" nonce={nonce} strategy="afterInteractive" />
      </body>
    </html>
  );
}

Reading headers() makes the route dynamic, and a per-request nonce means a cached copy of the HTML would contain a stale nonce. A nonce-based CSP therefore turns off static generation for every page it covers, which costs you the CDN caching described in Rendering Strategies. If you want static pages, use a CSP based on 'self' and hashes, or limit the nonce policy to the pages that need it with the matcher.

The stand-in builds the same kind of policy and then plays the browser: it checks which inline scripts would be allowed to run.

Node.js Build a nonce CSP and test scripts against it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Roll out safely

A strict policy breaks things you forgot you had: an analytics script, an inline style attribute, a font from another host. Introduce it in stages:

  1. Send Content-Security-Policy-Report-Only with the same value. The browser reports violations (in the console, or to a report-to endpoint) but blocks nothing.
  2. Fix or allow each legitimate violation. Third-party tags that you load with next/script need the nonce.
  3. Switch the header name to Content-Security-Policy once the reports are quiet.
  4. Check the result with your browser's network panel, and re-test after every new third-party service.

Also remember that style-src with a nonce blocks inline style="..." attributes unless you allow 'unsafe-inline' for styles. Many teams accept 'unsafe-inline' for styles and spend the strictness budget on script-src, where the real danger is.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a nonce-based CSP not be set with headers() in next.config.ts?

    A nonce is a single-use random value. The config file runs once, so its values are the same for every response, which would let an attacker reuse the nonce.
  2. 2. What does a nonce-based CSP usually cost you in Next.js?

    Each response carries its own nonce in both the header and the HTML, so a cached copy would hold a stale nonce. The pages must be rendered dynamically.
  3. 3. Which directive is the modern replacement for X-Frame-Options?

    frame-ancestors says who may embed your page. frame-src controls what your page may embed, which is a different question.
  4. 4. How should you introduce a new strict CSP on a live site?

    Report-only mode shows what would break without breaking anything, so you can adjust the policy before enforcing it.

Summary

  • Static security headers (HSTS, nosniff, framing, referrer and permissions policies) go into headers() in next.config.ts.
  • Later matching rules override earlier ones for the same header, so put exceptions after general rules.
  • A Content Security Policy limits where scripts, styles and other resources may load from, and is the best protection against injected scripts.
  • A nonce is a per-request random value, so it is created in the proxy file, set on the request and response headers, and read in Server Components with headers().
  • Nonce policies make pages dynamic. Start in report-only mode and move to enforcement once the reports are clean.
  • Use frame-ancestors alongside or instead of X-Frame-Options, and never ship 'unsafe-eval' to production.

Next: Upgrading and Migrating from Pages Router