Everything we've done in this module happens on the server. The browser, however, is where attacks that exploit someone else's page actually run: an injected script acting with your session, an invisible frame over a button, a Wi-Fi network that swaps HTTPS for HTTP. The browser knows how to defend against much of this, but only if the site asks it to, and the way to ask is through the response headers.
They're a second line of defense. They don't fix a query without a permission check or badly built HTML; they reduce what can be done when one of those fails. In this lesson you'll set up the ones every site should have, and you'll spend most of the time on the most powerful and the most delicate one: the Content Security Policy. With Next.js it has an important peculiarity, because the strictest policy and the prerendered shell get in each other's way.
- Where they go
| Place | Use it for |
|---|---|
headers in next.config.ts |
What's the same for everyone. It's fixed at build time and doesn't run code |
proxy.ts |
What changes on every request, like a nonce |
| The Route Handler | What's specific to one response: type, caching, download |
| The load balancer or the CDN | The same as the first, if there are several services behind it |
Write each header in a single place. If the CDN and Next.js send two CSP policies, the browser applies both at once, and the result is more restrictive than either of them and hard to debug.
Headers in the configuration accept path patterns like those of redirects (07-02). If two rules match and set the same header, the last one wins: that lets you put a general rule first and exceptions below it.
- The headers that almost never get in the way
| Header | Value | What it achieves |
|---|---|---|
X-Content-Type-Options |
nosniff |
The browser obeys the Content-Type and doesn't guess. Without it, an uploaded file could be interpreted as HTML |
Referrer-Policy |
strict-origin-when-cross-origin |
When leaving for another site, only the domain is sent, not the path or the parameters |
Permissions-Policy |
camera=(), microphone=(), geolocation=() |
Nobody on the page, not even a third-party frame, can request those permissions |
Cross-Origin-Opener-Policy |
same-origin |
A window opened from another site doesn't keep a reference to ours |
Strict-Transport-Security |
max-age=… |
For that period, the browser won't use HTTP with this domain |
X-Frame-Options |
DENY |
Nobody can frame us. frame-ancestors replaces it; it's kept for older browsers |
One more that gets removed: X-Powered-By: Next.js, with poweredByHeader: false. It isn't a defense, but there's no reason to advertise it either.
2.1. HSTS, take it slowly
The first visit to http://agendaviva.example travels unencrypted before the server redirects to HTTPS, and whoever controls that network can block the redirect. Strict-Transport-Security makes the browser remember that this domain is HTTPS only, and not even try otherwise.
Its strength is its danger: it can't be withdrawn until it expires in each browser. If the certificate fails one day, there'll be no "proceed anyway"; and with includeSubDomains, an old subdomain that only serves HTTP stops existing for anyone who has visited the main one. Start with a day, move to a week, and then to a year or two. preload, which includes the domain in a list built into browsers, is practically irreversible: only when you're sure the entire domain supports it.
It only takes effect when served over HTTPS. We don't send it in development, so as not to drag localhost into HTTPS.
- Content Security Policy
The CSP is a list of permissions: where the page can load each type of resource from and which scripts it can run. Whatever isn't on it, the browser blocks. This is ours:
| Directive | Value | Reason |
|---|---|---|
default-src |
'self' |
Whatever isn't specified separately, only from this origin |
script-src |
'self' 'unsafe-inline' |
Section 4 |
script-src-attr |
'none' |
Not a single onclick="…" in the HTML; React doesn't use them |
style-src |
'self' 'unsafe-inline' |
Inline styles from Next.js and from style attributes |
img-src |
'self' blob: data: |
blob: for the poster preview (06-05) |
font-src |
'self' |
Fonts will be served from here (09-02) |
connect-src |
'self' |
fetch, SWR and Server Actions |
object-src |
'none' |
No plugins |
base-uri |
'self' |
An injected <base> would redirect every relative path |
form-action |
'self' |
An injected form can't send data to another site |
frame-ancestors |
'none' |
Nobody frames us (clickjacking) |
upgrade-insecure-requests |
http: URLs on the page are requested over HTTPS |
Three directives, base-uri, form-action and frame-ancestors, don't inherit from default-src: if they aren't written, there's no limit. They're the ones most often forgotten.
connect-src deserves a note: with the direct upload to object storage we sketched in 06-05, you'd have to add that storage's domain, because the PUT is made by the browser.
3.1. The code
// lib/security/headers.ts — next.config.ts imports it with a relative path
const IS_DEVELOPMENT = process.env.NODE_ENV === 'development'
const IS_HTTPS = (process.env.NEXT_PUBLIC_SITE_URL ?? '').startsWith('https://')
const DIRECTIVES: Record<string, string[]> = {
'default-src': ["'self'"],
// In development, React uses eval to rebuild error stack traces
'script-src': ["'self'", "'unsafe-inline'", ...(IS_DEVELOPMENT ? ["'unsafe-eval'"] : [])],
'script-src-attr': ["'none'"],
'style-src': ["'self'", "'unsafe-inline'"],
'img-src': ["'self'", 'blob:', 'data:'],
'font-src': ["'self'"],
'connect-src': ["'self'"],
'object-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
'frame-ancestors': ["'none'"],
...(IS_HTTPS ? { 'upgrade-insecure-requests': [] } : {}),
'report-uri': ['/api/csp'],
'report-to': ['csp'],
}
const CSP = Object.entries(DIRECTIVES)
.map(([name, values]) => [name, ...values].join(' '))
.join('; ')
export const SECURITY_HEADERS = [
{ key: 'Content-Security-Policy', value: CSP },
{ key: 'Reporting-Endpoints', value: 'csp="/api/csp"' },
{ 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=()' },
{ key: 'Cross-Origin-Opener-Policy', value: 'same-origin' },
// One day to start with; extend it when everything works
...(IS_HTTPS ? [{ key: 'Strict-Transport-Security', value: 'max-age=86400' }] : []),
]// next.config.ts (added)
import { SECURITY_HEADERS } from './lib/security/headers'
// In nextConfig
poweredByHeader: false,
async headers() {
return [
{ source: '/:path*', headers: SECURITY_HEADERS },
{
// The URL carries a token: keep it out of Referer, even toward our own site
source: '/sign-up/confirm',
headers: [{ key: 'Referrer-Policy', value: 'no-referrer' }],
},
{
// Uploaded files: even if opened on their own, they can't run anything
source: '/images/:key*',
headers: [{ key: 'Content-Security-Policy', value: "default-src 'none'; sandbox" }],
},
]
},- The HTTPS decision depends on the public URL, not on
NODE_ENV: that way you can trynpm run build && npm run startonhttp://localhostwithout resources being requested over HTTPS. And since everything is fixed at build time,NEXT_PUBLIC_SITE_URLmust be defined when building (03-05). - The single quotes are part of the syntax:
'self'is a keyword, andselfwithout quotes would be a server with that name. - The two exceptions are at the end because the last one wins. The
/imagesone replaces the general policy; if someone managed to upload something that could be interpreted as a document,sandboxwould leave it with no origin and no scripts. form-actionalso covers redirects in some browsers.linkAccount(08-03) ends up on another domain; with JavaScript it's a request and not a form submission, so it works. If it had to work without JavaScript, you'd have to add the provider's origin.- In development, hot reloading opens a WebSocket to the same server. Current browsers consider it
'self'; if yours blocks it, addws:toconnect-srcin development only.
- The inline script problem
'unsafe-inline' in script-src allows any <script> written in the HTML, and therefore also one injected by an attacker. That's exactly what a CSP should prevent. So why do we include it?
Because Next.js HTML contains inline scripts: the ones that carry the RSC Payload and the ones that place each Suspense hole when it arrives (04-04). There's also our own, the theme script (03-04). There are three ways to allow those without allowing everything:
| Technique | How it works | With Next.js |
|---|---|---|
| Nonce | A random value per response, in the header and on every legitimate <script> |
Works on pages rendered on every request |
| Hash | The header lists the hash of each allowed script | Next.js's scripts change with every page and every piece of data |
| Files with SRI | External scripts carry the hash of their content | Experimental; section 5 |
4.1. The nonce-based policy
// Example only: proxy.ts for an application without a static shell
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}'`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
].join('; ')
const headers = new Headers(request.headers)
headers.set('x-nonce', nonce)
headers.set('Content-Security-Policy', csp) // Next.js reads the nonce from here
const response = NextResponse.next({ request: { headers } })
response.headers.set('Content-Security-Policy', csp) // And the browser, from here
return response
}Next.js extracts the nonce from the request header and adds it to all its scripts. Yours read it with (await headers()).get('x-nonce'). 'strict-dynamic' extends trust to whatever those scripts load. It's an excellent policy: an injected <script> doesn't have the nonce and doesn't run.
The price is in the first sentence of this section: a different value in every response. The HTML of a static page is the same for everyone and was generated before the request existed, so it can't carry one. The documentation is categorical:
- Every page must be rendered on every request.
- Partial prerendering is incompatible: the shell's scripts wouldn't have the nonce and the browser would block them.
- Incremental regeneration and CDN caching are lost.
AgendaViva is almost entirely shell: it's the decision module 5 was built on. Adopting nonces would in practice mean giving up Cache Components, and reading headers() in the root layout for the theme script would block every route.
4.2. The decision
| With nonce | Without nonce (ours) | |
|---|---|---|
| Injected inline script | Blocked | Runs |
| Script loaded from another domain | Blocked | Blocked |
onclick, onerror… attributes |
Blocked | Blocked, with script-src-attr 'none' |
Sending data with fetch to another site |
Blocked | Blocked |
| Injected form pointing to another site | Blocked | Blocked |
| Being framed | Blocked | Blocked |
| Static shell and CDN | No | Yes |
For a public events guide whose HTML is always escaped by React, with no rich HTML written by users and no third-party scripts, the second column is a reasonable balance. For an application that handles health or money, or that displays someone else's HTML, the first. It isn't a matter of taste, but of what's being protected: have someone with security judgment decide it, and get it written down.
There's a middle way: splitting the sensitive area off into another application, with a nonce. If the dashboard grew, that would be the option.
4.3. The hash trap
It's tempting to allow the theme script by its hash and keep 'unsafe-inline' for the rest. It doesn't work: as soon as script-src contains a hash or a nonce, browsers ignore 'unsafe-inline'. The page would end up with the right theme and without hydrating. It's a failure that's hard to diagnose, because everything looks fine until you click a button.
The theme script, meanwhile, follows the other rule: it's a constant in the code. It doesn't interpolate anything that comes from outside.
- SRI
Subresource Integrity adds the hash of its file to each <script src>; if the content doesn't match, it doesn't run. Next.js computes it at build time with an experimental option:
It's compatible with static pages, because the hashes are known at build time. It protects against someone changing the files on the CDN or in transit. The official guide also presents it as an alternative to nonces, with script-src 'self' and no 'unsafe-inline'.
Before adopting that policy, test it on your application with the mode from the next section: SRI covers files, and the streamed HTML also includes inline scripts. If your version still emits them, they'll be blocked. It's an option that may change, which is why AgendaViva doesn't use it; it's worth looking at again with each version.
- Rolling it out without breaking anything
A badly tuned CSP breaks the application for everyone. The Content-Security-Policy-Report-Only header makes the browser report without blocking. The prudent path:
- Publish the policy in report-only mode and see what it would have blocked.
- Fix or allow what's legitimate.
- Switch it to blocking, and leave the next, stricter version in report-only. The two headers can coexist.
Reports arrive through report-uri (the older, more widespread mechanism) and through report-to with Reporting-Endpoints (the newer one). Each with its own format:
// app/api/csp/route.ts
import * as z from 'zod'
import { withinLimits } from '@/lib/security/rate-limits'
import { getIp } from '@/lib/security/ip'
const short = z.string().max(500)
const schema = z.union([
z
.object({
'csp-report': z.object({
'effective-directive': short,
'blocked-uri': short,
'document-uri': short,
}),
})
.transform(({ 'csp-report': report }) => [
{
directive: report['effective-directive'],
blocked: report['blocked-uri'],
page: report['document-uri'],
},
]),
z
.array(
z.object({
body: z.object({ effectiveDirective: short, blockedURL: short, documentURL: short }),
}),
)
.max(20)
.transform((reports) =>
reports.map(({ body }) => ({
directive: body.effectiveDirective,
blocked: body.blockedURL,
page: body.documentURL,
})),
),
])
// Without parameters: they could carry a token or personal data
function withoutParams(address: string): string {
return URL.canParse(address) ? new URL(address).origin + new URL(address).pathname : address
}
export async function POST(request: Request) {
const limit = { key: `csp-ip:${await getIp()}`, max: 20, seconds: 60 }
if (!(await withinLimits([limit]))) return new Response(null, { status: 429 })
if (Number(request.headers.get('content-length')) > 32 * 1024) {
return new Response(null, { status: 413 })
}
const reports = schema.safeParse(await request.json().catch(() => null))
for (const { directive, blocked, page } of reports.data ?? []) {
console.warn('CSP', JSON.stringify({
directive,
blocked: withoutParams(blocked),
page: withoutParams(page),
}))
}
return new Response(null, { status: 204 })
}It's a public endpoint that anyone can write to, so it's treated as such: a limit, a size cap, a schema, and JSON.stringify so that a line break can't forge log entries. Reports are clues, not evidence. You'll see plenty that aren't yours: browser extensions, antivirus software and translators inject things into pages.
6.1. Checking it
npm run build && npm run start
curl -sI localhost:3000 | grep -iE 'content-security|x-content|referrer|permissions|opener|powered'
curl -sI localhost:3000/sign-up/confirm | grep -i referrer # no-referrer
curl -sI localhost:3000/api/v1/filters | grep -i content-security # the API tooWith the browser's developer tools open, go through the entire application: theme, favorites, live availability, poster preview, sign-in with a password and with the provider, modal. Every block shows up in the console with the directive responsible. Also try pasting into the console:
// All of this must fail
fetch('https://example.com')
document.head.append(Object.assign(document.createElement('script'), { src: 'https://example.com/a.js' }))
document.body.insertAdjacentHTML('beforeend', '<img src=x onerror="alert(1)">')Once the site is published, there are scanners that score the headers, like MDN's HTTP Observatory. Use them as a checklist of things you forgot, not as a goal: they penalize 'unsafe-inline', and you know why it's there. Once there are end-to-end tests (10-04), a CSP failure will show up in them as a console error; it's not a bad idea to make them treat it as a failure.
- What headers don't do
- They don't replace escaping. The first defense against injection is React rendering text (08-06).
- They don't protect an API.
curlignores all of them. X-XSS-Protectionhas been removed from browsers and even introduced bugs: don't add it.- A CORS header isn't a security header in this sense: it opens, it doesn't close (07-01).
- Allowing a domain means trusting everything it serves. A list with a public package CDN allows loading any package, including the attacker's.
Common Mistakes and Tips
- Starting in blocking mode instead of with
Report-Only. - Forgetting
base-uri,form-actionandframe-ancestors, which don't inherit. - Adding a hash or a nonce and keeping
'unsafe-inline'thinking it's still active. - Adopting nonces without giving up the shell: the page doesn't hydrate.
- A fixed nonce in the configuration. It's a password printed on every page.
'unsafe-eval'in production because it was needed in development.https:or*inscript-src. It allows almost everything.- HSTS with
preloadon day one. - Two policies in two layers that add up.
- Unquoted keywords.
- Defining
NEXT_PUBLIC_SITE_URLonly at runtime: the headers were fixed at build time. - Testing only the home page.
Exercises
Exercise 1: reading a policy
A site sends the following policy. What could someone who manages to inject HTML into a page do? Also point out what's done right.
default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com; img-src *; object-src none
Solution
- Run an inline script, because of
'unsafe-inline', or load any file fromcdn.example.com; if it's a public CDN, that means anything. 'unsafe-eval'broadens what those scripts can do.- Send data out with an image:
img-src *allowshttps://other.example/?data=….connect-srcis fine, inherited fromdefault-src, but it's of little use with that door open. object-src noneis misspelled: without quotes it's a server callednone. By chance it blocks almost the same thing.base-uriandform-actionare missing: an injected<base>or form has no limit.frame-ancestorsis missing: the page can be framed.
Done right: a restrictive default-src.
Exercise 2: a third party comes in
The city council wants a map from https://maps.example.com on the venue page, inside an <iframe>, and analytics that loads https://metrics.example.com/m.js and sends data to the same domain. Say what changes and what else needs to be asked.
Solution
'script-src': [..., 'https://metrics.example.com/m.js'],
'connect-src': ["'self'", 'https://metrics.example.com'],
'frame-src': ['https://maps.example.com'],- The file is allowed in
script-src, not the whole domain. There's no need to touchdefault-src. - The
<iframe>getssandboxwith the bare minimum,loading="lazy"andreferrerPolicy="no-referrer".Permissions-Policystill denies it geolocation; if the map needs it, it's granted to that origin. - A third-party script runs with all the page's permissions: it can read what's displayed and act with the session. Is it needed in the dashboard? It can be loaded only in the public part, and the policy for
/dashboardand/admin, in a separate rule, can disallow it. - It's data processing: consent, contract and privacy policy. Ask compliance beforehand.
- Alternative: a map image generated by us and our own metrics.
Exercise 3: allowing embedding
The district websites want to embed the list of upcoming events in a frame. Allow it only on /embed/events, for https://northside.example.com. Why wouldn't relaxing the general policy be enough? What must that page not have?
Solution
// lib/security/headers.ts: the policy, as a function of who can frame
export function createCsp(ancestors: string[]): string {
return Object.entries({ ...DIRECTIVES, 'frame-ancestors': ancestors })
.map(([name, values]) => [name, ...values].join(' '))
.join('; ')
}
// next.config.ts, at the end of the list
{
source: '/embed/events',
headers: [
{ key: 'Content-Security-Policy', value: createCsp(['https://northside.example.com']) },
],
},
// X-Frame-Options leaves SECURITY_HEADERS and gets its own rule
{
source: '/((?!embed/).*)',
headers: [{ key: 'X-Frame-Options', value: 'DENY' }],
},Relaxing the general one would allow framing /admin: someone could place a button of their own over "Publish". The rule is limited to a path that has nothing to click with consequences: only links that open in another tab, no session, no booking and no header with the person's name. A later header can replace another, but not remove it; that's why X-Frame-Options, which can't say "only this site", is taken out of the general rule and excludes that path. Finally, the SameSite=Lax cookie wouldn't be sent inside a third-party frame.
Conclusion
Security headers are instructions to the browser: don't guess types, don't say where I came from, don't frame me, don't use HTTP. The CSP adds what the page can load and run. Its strictest version needs a nonce per response and thereby gives up the static shell; ours keeps Cache Components in exchange for allowing inline scripts, and closes off everything else. It's rolled out in report-only, tested by going through the application, and reviewed with every third party that comes in.
There's one surface left that no header protects, because it receives hand-crafted requests: Server Actions and everything they accept. The module ends by going through them one by one, along with the most common mistakes and Next.js's own security advisories, in Server Action Security and Common Pitfalls.
