Security headers and CSP

Intermediate · 8 min

The browser-enforced headers worth setting, how to build a nonce-based Content Security Policy in proxy.ts, and why nonces force dynamic rendering.

Before thisThe proxy fileStatic and dynamic rendering

ByteMonk · 8 min

Security headers and CSP

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by ByteMonkReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Security headers tell the browser to be stricter than its defaults, so a hole in your code does less damage.
  • Static headers such as `nosniff`, `Referrer-Policy` and HSTS can be set with `headers()` in `next.config.ts` without losing static rendering.
  • A nonce-based CSP generates a random value per request in `proxy.ts`, and Next.js applies it to its own scripts and `<Script>` components.
  • Nonces require dynamic rendering of every page and are incompatible with Partial Prerendering, so choose them deliberately.

Defense that lives in the browser

Everything so far protected your server. But some attacks target the person using your site. The classic one is cross-site scripting (XSS): an attacker gets a <script> tag into a page, say through a comment field you forgot to escape or a compromised third-party script, and it runs with the full power of your site, reading cookies that are not httpOnly and calling your API as the user.

Security headers are instructions your server sends along with the page that tell the browser to be stricter than it would be by default. The browser enforces them, so even if your code has a hole, the damage is limited. They are a seat belt: you hope not to need them.

The headers worth setting

  • Content-Security-Policy (CSP): an allowlist of where scripts, styles, images, frames and connections may come from. The strongest defense against XSS, and the one with real complexity.
  • Strict-Transport-Security: tells the browser to use HTTPS only for your domain from now on.
  • X-Content-Type-Options: nosniff: stops the browser guessing a file’s type and executing something you served as text.
  • Referrer-Policy: controls how much of your URL is sent to other sites when users click away.
  • Permissions-Policy: turns off browser features such as camera or geolocation that your site does not use.
  • frame-ancestors (a CSP directive, replacing the older X-Frame-Options): who may embed your site in an iframe, to prevent clickjacking.

Setting static headers

For headers that are the same on every response, use the headers() function in next.config.ts:

const nextConfig = {
  async headers() {
    return [
      {
        source: "/(.*)",
        headers: [
          { key: "X-Content-Type-Options", value: "nosniff" },
          { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
          { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains" },
        ],
      },
    ];
  },
};
export default nextConfig;

This keeps pages static. It is also where the docs put a CSP that does not use nonces, with 'unsafe-inline' allowed for scripts and styles, which is easy but weaker.

CSP with a nonce

The strict version drops 'unsafe-inline'. Next.js itself emits small inline scripts, so how do you allow those and nothing else? With a nonce: a random value generated per request. The CSP says “run only scripts carrying this nonce”, and the server stamps the same nonce on the scripts it trusts. An attacker cannot guess a value that changes every request.

The docs generate it in the proxy:

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

export function proxy(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' 'nonce-${nonce}';
    img-src 'self' blob: data:;
    object-src 'none';
    base-uri 'self';
    frame-ancestors 'none';
  `.replace(/\s{2,}/g, " ").trim();

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

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

During server rendering Next.js reads the nonce out of the CSP header and applies it to its own scripts, to <Script> components, and to inline styles and scripts. In development you must also allow 'unsafe-eval', because React uses eval to rebuild server-side error stacks in the browser; the docs say it is not needed in production.

The price of nonces

A nonce is per request, and a statically generated page has no request at build time. So the Next.js docs are blunt: using nonces means every page must be dynamically rendered. Static optimization and ISR are off, CDN caching of pages needs extra work, and Partial Prerendering is incompatible because the static shell cannot know the nonce. The failure is quiet, so I tested it. In a Next.js 16.4.6 app with the docs’ proxy.ts, a page with no dynamic API was prerendered as static, and next start still sent a Content-Security-Policy header carrying a nonce, but the HTML contained zero nonce= attributes. A strict policy with 'strict-dynamic' would then block that page’s scripts in a real browser. Adding await connection() from next/server to the page made it dynamic (ƒ in the build output), and the same request returned HTML with 16 nonce= attributes, including on the framework’s <script> tags. The static headers from next.config.ts (nosniff, Referrer-Policy, HSTS, Permissions-Policy) were present on every response either way.

Decide deliberately. For a content site, a header-based CSP or the experimental Subresource Integrity mode, which keeps static generation, may be the right trade. For an app handling sensitive data, nonces are worth it.

Test before you enforce

A CSP that is too strict breaks your own site in ways that look like random bugs. Ship it first as Content-Security-Policy-Report-Only, which logs violations in the console without blocking, fix what it reports, then enforce.

What the video covers

ByteMonk’s “HTTP Secure Headers for Web App Security” is an 8-minute chaptered tour of CSP, HSTS, X-Content-Type-Options, Referrer-Policy, CORS and Permissions-Policy. It is not about Next.js, so how to set these in next.config.ts and the nonce setup in proxy.ts come from this lesson and the official CSP guide. Two Next.js-specific videos are linked under “deeper”, and the first has a caveat: Nijat Aliyev’s 18-minute CSP configuration video has no caption track, so I could not confirm its audio language from metadata; the title and description are in English. Jan Marshal’s longer security video has one chapter on headers.

Where this fits

That finishes authentication and security. The next group is about making the app fast and keeping it correct. Next: bundle analysis and lazy loading.

Check yourself

  1. 01Why does a nonce-based CSP force dynamic rendering?

    A nonce must be unique per request, and a statically generated page is built before any request exists, so no nonce can be injected.

  2. 02Why does the docs example add `'unsafe-eval'` only in development?

    React uses `eval` in development to rebuild server-side error stacks in the browser, and it is not needed in production.

  3. 03How should you roll out a strict CSP safely?

    Ship it first as `Content-Security-Policy-Report-Only` to log violations without blocking, fix what it reports, then enforce it.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark