Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Domains, HTTPS and Redirects

Response Headers and Security

Set custom HTTP response headers on Vercel and Netlify: Content-Security-Policy, HSTS, X-Content-Type-Options, CORS and cache headers, using vercel.json, _headers and netlify.toml.

Every response your site sends carries headers: small name and value pairs that tell the browser how to treat the content. Static hosts add sensible defaults, but security and caching headers are yours to choose. Both platforms let you attach headers to URL patterns with a config file, no server code needed.

The platforms cannot run on this site. The config files are read-only examples taken from documented syntax, and the runnable code is a JavaScript stand-in that audits a header set. Verify real headers with curl -I https://your-site or the browser's Network panel.

Where headers are configured

Netlify reads a _headers file in the publish directory. A path line is followed by indented headers:

TEXT
/*
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin

/assets/*
  Cache-Control: public, max-age=31536000, immutable

The same can be written in netlify.toml under [[headers]] with for = "/*" and a [headers.values] table.

Vercel uses vercel.json:

JSON
{
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        { "key": "X-Content-Type-Options", "value": "nosniff" },
        { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }
      ]
    },
    {
      "source": "/assets/(.*)",
      "headers": [
        { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }
      ]
    }
  ]
}

Frameworks also set headers in their own config (for example Next.js headers()), and functions can set headers on the Response they return. When several sources set the same header the more specific pattern or the later definition usually wins; test it on a preview.

The headers worth setting

Header Purpose
Strict-Transport-Security force HTTPS for a time period (see HTTPS and Certificates)
Content-Security-Policy whitelist where scripts, styles, images and frames may load from; the strongest defense against injected scripts
X-Content-Type-Options: nosniff stop browsers guessing a file's type
Referrer-Policy limit how much of your URL is sent to other sites
Permissions-Policy switch off browser features such as camera or geolocation
X-Frame-Options or CSP frame-ancestors stop other sites embedding yours (clickjacking)
Cache-Control control caching (see Caching and the CDN)
Access-Control-Allow-Origin CORS: which other origins may call your resources

Content-Security-Policy in practice

A CSP is a list of directives. A strict starter for a static site might be default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'. Roll it out as Content-Security-Policy-Report-Only first: the browser reports violations without blocking, so you learn what your pages really load (analytics, fonts, embeds) before enforcing. Avoid 'unsafe-eval' and wildcard sources such as * for scripts.

CORS

CORS is a browser rule, not a server firewall. If a page on https://app.example.com calls your API on https://api.example.com, the API must answer with Access-Control-Allow-Origin: https://app.example.com. Use a specific origin, not *, for anything with credentials. A OPTIONS preflight request may also need Access-Control-Allow-Methods and Access-Control-Allow-Headers.

A safe baseline

HSTS HTTPS only, ramp up max-age.
CSP Say where code may load from.
nosniff Trust the declared content type.
frame-ancestors Block unwanted embedding.

Start with Report-Only, then enforce.

1 / 2

Auditing a header set

The stand-in below takes a headers object, checks it against a baseline and gives a score. It mirrors the checklist above; the thresholds are teaching choices.

JS Header audit stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Matching a path to headers

Path patterns decide which headers a response gets. This stand-in applies Netlify-style /* and /assets/* blocks and merges them, later blocks overriding earlier ones for the same header name.

JS Header rules stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Setting Access-Control-Allow-Origin: * together with cookies. Browsers reject that combination.
  • A strict CSP that breaks your own analytics or fonts. Use Report-Only first.
  • Long HSTS too early on a site with an HTTP-only subdomain.
  • Headers on redirects. Check which response (the redirect or the final page) gets the header.
  • Assuming headers apply to functions. Function responses set their own headers in code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the safest way to introduce a new Content-Security-Policy?

    Report-Only shows what would be blocked without breaking pages, so you can fix the policy before enforcing.
  2. 2. Which Netlify file holds simple per-path headers?

    A _headers file in the publish directory lists a path and its indented headers. Vercel uses vercel.json instead.
  3. 3. What does X-Content-Type-Options: nosniff do?

    It prevents MIME sniffing, which can turn an uploaded text file into executed script.
  4. 4. Why is Access-Control-Allow-Origin: * a poor choice for an API that uses cookies?

    Credentialed CORS requires the exact origin to be named.

Summary

  • Headers are set per path in vercel.json, _headers or netlify.toml.
  • A baseline: HSTS, nosniff, a Referrer-Policy, a CSP and framing protection.
  • Roll out CSP in Report-Only mode first.
  • CORS is enforced by browsers; name exact origins.
  • Check results with curl -I or the Network panel.

Next: Object Storage and Blobs