Skip to content

Web

Security headers

The Worker puts a Content-Security-Policy and a set of hardening headers on every response it handles, and refuses API writes posted from other origins. You work here when a page needs something from another origin, such as images from a CDN or a script from a vendor.

How it works

layers/kit/server/middleware/security-headers.ts(Licensees only) runs on every request and sets:

HeaderValue
content-security-policyThe policy below, plus security.cspExtend
x-frame-optionsDENY
x-content-type-optionsnosniff
referrer-policystrict-origin-when-cross-origin, or what the page's route rule sets
permissions-policyaccelerometer=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), microphone=(), payment=(), usb=()
strict-transport-securitymax-age=31536000; includeSubDomains, over https only and never under pnpm dev

The values come from layers/kit/server/utils/security-headers.ts(Licensees only). The policy is built once when the Worker starts, since everything it reads is build-time config.

A header the response already carries is left as it is, HSTS aside, so a headers route rule for a page wins over the kit's value there. Of these headers, the kit's own route rules set only referrer-policy, on the sign-in and token pages (Keep tokens out of the Referer header).

The policy

With the shipped config the policy is:

default-src 'self'
script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://challenges.cloudflare.com
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com
img-src 'self' data: blob: https://imagedelivery.net
font-src 'self' data: https://fonts.gstatic.com
connect-src 'self'
frame-ancestors 'none'
base-uri 'self'
form-action 'self'
object-src 'none'
frame-src 'self' https://challenges.cloudflare.com
  • challenges.cloudflare.com is Turnstile. It is added while auth.enabled or contact.enabled is on.
  • imagedelivery.net is Cloudflare Images, which serves the blog covers. Avatars are R2 objects the app serves itself, under 'self'.
  • data: in img-src is for Nuxt Icon, which draws icons as data: SVG masks. blob: is for the previews Nuxt UI's UFileUpload shows.
  • 'wasm-unsafe-eval' lets @nuxt/content run its WebAssembly queries.
  • connect-src stays 'self' because analytics and marketing events are sent from the server, and every icon ships in the client bundle (Theme). A fetch from the browser to any other origin is blocked.

Allow another origin

Add sources per directive in starter.config.ts(Licensees only):

security: {
  headers: true,
  cspExtend: {
    'img-src': ['https://cdn.example.com'],
    'connect-src': ['https://api.example.com'],
  },
},

Each list is appended to the kit's sources for that directive, and repeats are dropped. A directive the kit doesn't set, such as media-src, is added as written; until you add it, it falls back to default-src 'self'. The policy is read at build, so a deploy needs a rebuild.

A blocked resource doesn't show up on the server. The page answers 200, the browser refuses the image or request, and the console logs a "Refused to load" line. Blog posts are checked for you: layers/kit/test/unit/content-image-origins.test.ts(Licensees only) reads every src and avatar in the frontmatter under content/ and fails when img-src would block one. It reads your policy, security.cspExtend included, and judges each source as the browser does, https:, *. hosts and paths included. It checks nothing while security.headers is off. A GitHub profile picture or a Gravatar URL as a post's author.avatar fails it.

Keep tokens out of the Referer header

Pages that receive a token in their URL (/auth/reset-password, /auth/magic-link, /auth/verify-email, /auth/restore-account and /invite) answer with Referrer-Policy: no-referrer and Cache-Control: no-store, and say no-referrer in a <meta> tag as well. /auth/login and /auth/register carry an invitation's token in ?redirect= when an invitee is sent to sign in, so they answer with strict-origin and no-store, and say strict-origin in their <meta> tag. The header covers everything the browser fetches before it reads the page, and the tag a visit that arrives without a page load. Each rule is set under every locale prefix.

A page of yours that reads a token from its query string needs the same three things. In the page:

useHead({ meta: [{ name: 'referrer', content: 'no-referrer' }] })

And in routeRules in your nuxt.config.ts(Licensees only), which Nuxt merges over the kit's. Name the path under every locale prefix you serve, or the prefixed page misses the rule:

export default defineNuxtConfig({
  routeRules: {
    '/claim': {
      headers: {
        'cache-control': 'no-store',
        'referrer-policy': 'no-referrer',
      },
      robots: false,
    },
    '/sr/claim': {
      headers: {
        'cache-control': 'no-store',
        'referrer-policy': 'no-referrer',
      },
      robots: false,
    },
  },
})

A page of yours that replaces app/pages/auth/login.vue or app/pages/auth/register.vue keeps the kit's tag:

useHead({ meta: [{ name: 'referrer', content: 'strict-origin' }] })

Accept a cross-site post

layers/kit/server/middleware/cross-site-writes.ts(Licensees only) answers 403 to any write under /api/ (anything but GET, HEAD and OPTIONS) whose Sec-Fetch-Site is present and is neither same-origin nor none: a page on another site, and a page on another subdomain of your own site, which the browser labels same-site. A request without that header, from a server or an old browser, passes, so provider webhooks and server-to-server calls are unaffected. Payment webhooks live under /webhooks/, outside the check anyway.

A write a page makes while it renders on the server, such as useFetch('/api/search', { method: 'POST' }) in setup, is not judged: the guard lets a write through when the request the Worker was invoked with is a read. pnpm dev hides that request, so there such a write is still refused when the page was opened from a link on another origin. pnpm preview behaves as production.

Two prefixes are allowed through: /api/auth/oauth/, where the OAuth state protects the callback, and /api/email/unsubscribe, which mail clients post to for one-click unsubscribe. An endpoint of yours that must accept a write from another origin's page, a sibling subdomain's included, goes in security.crossSiteWrites, by its path prefix under /api/:

security: {
  crossSiteWrites: ['/api/sso/callback'],
},

The build refuses a prefix outside /api/, which the guard never reads. The session cookie is SameSite=Lax: it never rides a cross-site post, but it does ride one from another subdomain of the same site, so a listed prefix is open to every such subdomain with the visitor's session. List one only when the endpoint authenticates the request itself, with a signature or a token. This check ignores security.headers.

Turn the headers off

Set security.headers: false and the middleware sets none of them, HSTS included. Do this only when something in front of the Worker, such as a Cloudflare Transform Rule, already sets them. A browser that receives two policies enforces both.

Configuration

KeyDefaultWhat it does
security.headerstrueSets the CSP and the hardening headers on every response.
security.cspExtend{}Extra sources per CSP directive, merged into the kit's policy.

There are no environment variables.

Good to know

  • HSTS carries includeSubDomains, so once a browser has seen it, every subdomain of the app's host has to serve https for a year.
  • HSTS is never sent under pnpm dev. Sent from localhost, it would force https on every project you run on localhost in that browser.
  • 'unsafe-inline' stays in script-src. Nuxt writes its hydration payload as an inline script, and /blog and /legal are served from the swr cache, where one HTML body answers many requests, so a per-request nonce can't work.
  • Nitro runs every middleware in your server/middleware/ before any in layers/kit/server/middleware/, each folder in file-name order. A middleware of yours that answers a request ends the chain before the kit's security-headers.ts runs, so its response goes out without the headers unless it sets them itself. One that sets a header and lets the request go on keeps its value, since the kit's middleware leaves a header the response already carries, HSTS aside. layers/kit/test/unit/middleware-order.test.ts(Licensees only) holds the kit's own middleware to their order.

A link with a lock opens the kit’s private repository, which every licensee can read.