State and browser security

Browser security headers

Add response headers that constrain scripts, framing, MIME sniffing, referrer data, and future connections made by the browser.

Security headers tell the browser which capabilities to allow when it handles your response. They do not fix bad application code, but they reduce the damage when something goes wrong.

The common ones:

  • Content-Security-Policy restricts where scripts, styles, images, and other resources may load from.
  • X-Content-Type-Options: nosniff tells the browser to respect declared content types instead of guessing.
  • Referrer-Policy limits referrer information sent to other sites.
  • Permissions-Policy controls selected browser features like camera and geolocation.
  • frame-ancestors inside CSP controls which pages may embed yours in an iframe.

Check what a live site sends:

curl -I https://flaviocopes.com/

Look for headers like content-security-policy, referrer-policy, or x-content-type-options. Not every site sends all of them, but production sites you trust usually send at least a few.

A strict CSP can break an existing site overnight. A policy that blocks inline scripts will stop ad-hoc <script> tags from working. Deploy carefully. Start by listing every script, style, and image source your pages need. Then write a policy that allows only those.

CSP can run in report-only mode first:

Content-Security-Policy-Report-Only: script-src 'self'; report-uri /csp-report

Violations get reported but nothing breaks. Watch the reports for a week before you switch to enforcing mode.

Headers reduce risk. They do not replace output escaping, input validation, secure authentication, or patched dependencies. Think of them as guardrails, not a substitute for writing safe code.

Be careful copying a CSP from a blog post verbatim. 'unsafe-inline' and 'unsafe-eval' weaken the policy significantly. I treat those as temporary exceptions with a plan to remove them.

Try this on a site you manage: add X-Content-Type-Options: nosniff first. It is low risk and blocks a class of MIME confusion attacks. Then tackle CSP one directive at a time.

Quick check

Result

You got of right.

Lesson completed