Rule
Set response security headers in the outermost server hook, repeat the same headers in a _headers file for static assets, and keep the two identical with a test.
Why
On Cloudflare Pages a request for a static file never reaches the Worker. Headers set in code cover rendered pages and API routes only. Your images, scripts, and prerendered HTML go out without them unless _headers adds them.
Must
- Put the header hook first in the hook sequence, so early returns from later hooks still get the headers.
- Send
X-Content-Type-Options: nosniff,Referrer-Policy, andStrict-Transport-Securityon every response. - Send
X-Frame-Options: SAMEORIGIN, orDENYif you never frame your own pages. - Let the framework write the Content Security Policy when it uses nonces. It knows the nonce and you do not.
- Keep comments out of rule blocks in
_headers. - Write a test that reads both sources and fails when they differ.
Pattern
# Comments go above a rule block, never inside one.
/*
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Referrer-Policy: strict-origin-when-cross-originexport const securityHeadersHandler: Handle = async ({ event, resolve }) => {
const response = await resolve(event);
for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
try {
response.headers.set(name, value);
} catch {
// Some responses have immutable headers. Copy the response to change them.
const copy = new Response(response.body, response);
copy.headers.set(name, value);
return copy;
}
}
return response;
};Should
- Leave
includeSubDomainsandpreloadoff the HSTS header until the owner of the domain decides. Both are hard to undo and affect every subdomain. - Redirect to one canonical host. A session cookie is bound to the host, so
wwwand the apex are two sign-ins. Use 301 for GET and HEAD and 308 for other methods, and exempt webhook and cron routes. - Mark non-canonical hosts, such as the
pages.devaddress, asnoindex.
Gotchas
- A comment inside a rule block makes Cloudflare drop the headers after it, with no warning.
- With the SvelteKit Cloudflare adapter,
_headersbelongs in the project root. The adapter rejects it instatic/. - The adapter already writes an immutable cache rule for hashed assets. A second rule of your own is redundant.
- Answer
Rangerequests on media routes with 206 andContent-Range. Safari will not play video from a server that ignores them.
Validation checklist
curl -Ion a page and on a static asset shows the same security headers.- The drift test fails when a header is added to only one source.
- The site loads in an iframe only where you intend.
wwwredirects to the apex, or the apex towww, and never both ways.