Square CloudSquare Cloud

HTTP security headers: CSP, HSTS and the rest

HTTP security headers are instructions the server sends to the browser to limit attacks such as XSS, clickjacking and downgrades to HTTP. Start with CSP, HSTS, X-Content-Type-Options, Referrer-Policy and Permissions-Policy.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Know what each security header does and which ones are obsolete
  • Set the headers in Express with Helmet and in a Python middleware
  • Test the CSP in report-only mode and check the headers with curl
On this page

Besides the content, every HTTP response can carry instructions for the browser: load scripts only from this domain, never open this site over plain HTTP, don't let another page put me in an iframe. Those are security headers. They take a few lines of code and, on the browser side, limit how far attacks such as XSS and clickjacking can go.

They don't fix bugs in your code: a SQL query built by string concatenation is still vulnerable with any header. They are an extra layer that limits the damage when something slips through.

Which security headers should you use?#

Header Protects against Reference value
Content-Security-Policy XSS and injected scripts; with frame-ancestors, clickjacking default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
Strict-Transport-Security (HSTS) Plain HTTP access and interception on the first visit max-age=31536000; includeSubDomains
X-Content-Type-Options The browser "guessing" a file's type (MIME sniffing) nosniff
Referrer-Policy URL paths and query strings leaking to other sites strict-origin-when-cross-origin
Permissions-Policy Scripts and iframes using the camera, microphone and location camera=(), microphone=(), geolocation=()
X-Frame-Options Clickjacking in browsers without frame-ancestors support DENY

nosniff makes the browser block a script served with a non-JavaScript type and a stylesheet that isn't text/css, and stops a text file uploaded by a user from being treated as HTML. strict-origin-when-cross-origin is already the browsers' default when nothing is sent; OWASP recommends setting it anyway, so you don't depend on that. Permissions-Policy isn't enforced by every browser, so check MDN's compatibility table.

Which ones are obsolete?#

  • X-XSS-Protection: MDN marks it as deprecated and warns it can create XSS vulnerabilities. OWASP recommends not sending it or sending 0. The 1; mode=block from old tutorials should go.
  • Expect-CT and Public-Key-Pins: deprecated according to OWASP. Remove them.
  • X-Frame-Options: ALLOW-FROM: modern browsers ignore the whole header with this value. Use frame-ancestors.
  • X-Powered-By: not a security header, but it reveals the server's technology. Remove it.

X-Frame-Options with DENY or SAMEORIGIN still works, but the CSP specification says that when an enforced policy includes frame-ancestors, the browser ignores X-Frame-Options. Keeping it only helps old browsers.

How do you build a Content-Security-Policy?#

CSP tells the page where it may load each type of resource from. It's the browser's main defense against XSS: even if an attacker manages to inject a <script> tag, the browser won't run it unless it's allowed.

Directive Controls
default-src The fallback for every resource type without its own directive
script-src JavaScript, including inline scripts
style-src CSS
img-src Images
connect-src fetch, XHR and WebSocket
object-src Plugins (<object>, <embed>); use 'none'
base-uri The <base> tag, which changes the base of every relative URL
form-action Where forms may submit to
frame-ancestors Who may put the page in an iframe

Two details catch a lot of people. frame-ancestors doesn't fall back to default-src: a policy with default-src 'none' still lets any site embed the page. And without 'unsafe-inline', inline scripts and attributes like onclick stop running; to allow one specific inline script, use a nonce or a hash instead of 'unsafe-inline'.

A site that loads images from its own CDN and calls an API would look like this:

http
Content-Security-Policy: default-src 'self'; img-src 'self' data: https://cdn.example.com; connect-src 'self' https://api.example.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'

Start in report-only mode. The Content-Security-Policy-Report-Only header takes the same directives but blocks nothing: it only logs violations to the console and, if you ask, sends them to an endpoint. Run it like that for a few days, adjust the list and only then switch to Content-Security-Policy.

http
Reporting-Endpoints: csp="https://myapp.example.com/csp-reports"
Content-Security-Policy-Report-Only: default-src 'self'; report-to csp; report-uri /csp-reports

MDN uses report-to and the older report-uri together because the former doesn't work in every browser. On a static site with no server code, the CSP can go in a <meta http-equiv="Content-Security-Policy"> tag in the <head>, but without frame-ancestors, report-uri and sandbox, which only work as a header.

How do you turn on HSTS without locking yourself out?#

HSTS tells the browser the host must only be reached over HTTPS for max-age seconds. It closes the gap of the first http:// request, which a redirect alone leaves open (HTTP vs HTTPS has the details). Browsers ignore the header when it arrives over HTTP.

The risk runs the other way: once the browser has the header, it refuses HTTP and won't let the user click through a certificate error. That's why hstspreload.org recommends ramping up max-age in stages (5 minutes, one week, one month), fixing whatever breaks at each one, before reaching a year or more.

  • includeSubDomains only when every subdomain answers over HTTPS. An internal subdomain without a certificate becomes unreachable.
  • preload puts the domain on a list built into browsers. It requires a max-age of at least 31536000, includeSubDomains and every subdomain on HTTPS, and getting off the list takes months. Submit only when the whole domain is ready.

How do you set the headers in Express with Helmet?#

Helmet sets a batch of headers to safe values in one go and removes X-Powered-By. Its defaults already include a strict CSP, a one-year HSTS with includeSubDomains, nosniff, X-Frame-Options: SAMEORIGIN and X-XSS-Protection: 0. It doesn't set Permissions-Policy, so that one is manual.

bash
npm install express helmet

With "type": "module" in package.json:

js
import express from "express";
import helmet from "helmet";

const app = express();

app.use(
  helmet({
    // These directives are merged into Helmet's defaults and replace those with the same name
    contentSecurityPolicy: {
      directives: {
        "img-src": ["'self'", "data:", "https://cdn.example.com"],
        "connect-src": ["'self'", "https://api.example.com"],
        "frame-ancestors": ["'none'"],
      },
    },
    referrerPolicy: { policy: "strict-origin-when-cross-origin" },
    xFrameOptions: { action: "deny" },
  }),
);

// Helmet doesn't set Permissions-Policy
app.use((req, res, next) => {
  res.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
  next();
});

app.use(express.static("public"));

app.get("/health", (req, res) => {
  res.json({ status: "ok" });
});

app.listen(process.env.PORT ?? 3000);

Register Helmet before your routes and express.static: a middleware only changes the responses of routes registered after it. To test the CSP without blocking anything, add reportOnly: true inside contentSecurityPolicy.

How do you set them in Python (FastAPI, Flask or Django)?#

In FastAPI, an HTTP middleware adds the headers to every response:

python
from fastapi import FastAPI, Request

# the automatic docs (/docs and /redoc) load scripts from a CDN
app = FastAPI(docs_url=None, redoc_url=None)

SECURITY_HEADERS = {
    "Content-Security-Policy": (
        "default-src 'self'; object-src 'none'; base-uri 'self'; "
        "form-action 'self'; frame-ancestors 'none'"
    ),
    "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
    "X-Content-Type-Options": "nosniff",
    "Referrer-Policy": "strict-origin-when-cross-origin",
    "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
    "X-Frame-Options": "DENY",
}


@app.middleware("http")
async def security_headers(request: Request, call_next):
    response = await call_next(request)
    for name, value in SECURITY_HEADERS.items():
        response.headers[name] = value
    return response


@app.get("/health")
def health():
    return {"status": "ok"}

docs_url=None turns off the /docs page: by default, Swagger UI and ReDoc load their files from a CDN, and the CSP above would block them. If you need it in production, allow those origins only on the docs routes.

In Flask, the same dictionary goes into an @app.after_request function, which receives the response and returns it with the headers. In Django, SecurityMiddleware sets HSTS (SECURE_HSTS_SECONDS), nosniff and Referrer-Policy through settings, XFrameOptionsMiddleware handles X-Frame-Options, and ContentSecurityPolicyMiddleware applies the CSP set in SECURE_CSP (check that your Django version includes it).

How do you check the headers are arriving?#

bash
curl -sI https://myapp.example.com/

The response should list each one:

text
HTTP/2 200
content-security-policy: default-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff
referrer-policy: strict-origin-when-cross-origin
permissions-policy: camera=(), microphone=(), geolocation=()
x-frame-options: DENY

Check an error page and a static file too, not just the home page. In the browser, the DevTools console shows every resource the CSP blocked along with the directive responsible, and Mozilla's HTTP Observatory scans any public site.

What are the common mistakes?#

  • The CSP breaks the site. Inline scripts, analytics, fonts and third-party widgets stop loading. Start with Report-Only and read the console before enforcing.
  • Two CSPs on the same response. If the framework and another layer each send a policy, the browser enforces both, and a resource has to pass both. Set it in one place only.
  • Long HSTS too early. A year with includeSubDomains before every subdomain has HTTPS takes part of the domain offline for anyone who already got the header.
  • Headers in a meta tag. HSTS and X-Frame-Options in <meta> are ignored.
  • Copying old tutorials. X-XSS-Protection: 1; mode=block, ALLOW-FROM and Public-Key-Pins no longer protect anything.
  • Forgetting cookies. Headers don't replace the Secure, HttpOnly and SameSite attributes on Set-Cookie, which protect the session against theft and CSRF.

If you are moving a site to HTTPS, the CSP upgrade-insecure-requests directive helps with mixed content. For the rest of the list before going live, see the deploy security checklist.

How to do this on Square Cloud#

On Square Cloud, the headers your application sends pass through the proxy untouched. Every header in this guide, from the CSP to Permissions-Policy, comes from your code, through Helmet, the Python middleware or your framework's own feature, and reaches the browser exactly as you wrote it.

Every web application gets a *.squareweb.app subdomain with HTTPS, and HTTP requests are redirected to HTTPS. From the Standard plan, a custom domain also gets a certificate that is issued and renewed on its own. Before you turn on includeSubDomains or preload on your domain, make sure every one of its subdomains answers over HTTPS.

See how the network handles traffic, with a WAF and DDoS protection on every plan, in network and CDN.

Infrastructure

L3/L4/L7 DDoS mitigation and a WAF on every plan

DDoS-protected network

FAQs

Do I still need X-XSS-Protection?

No. MDN marks it as deprecated and warns it can create vulnerabilities in otherwise safe sites. OWASP recommends not sending it or sending X-XSS-Protection: 0, and relying on a CSP that blocks inline scripts.

X-Frame-Options or frame-ancestors?

Use the CSP frame-ancestors directive, which is more flexible and, when the policy is enforced, makes the browser ignore X-Frame-Options. Keeping X-Frame-Options: DENY alongside it only helps old browsers.

Can I set the CSP in a meta tag?

Yes, with a meta http-equiv="Content-Security-Policy" tag in the head, but frame-ancestors, report-uri and sandbox don't work there. HSTS and X-Frame-Options have no effect in a meta tag: they must be sent as HTTP headers.

How do I see a website's security headers?

Run curl -sI with the URL, or open DevTools, go to the Network tab, click the document request and look at Response Headers. Mozilla's HTTP Observatory also scans any public site.

Does a JSON-only API need these headers?

It needs fewer. OWASP says CSP might be meaningless on a REST API response that won't be rendered, but HSTS and X-Content-Type-Options: nosniff still apply to every response.

Next articleMalicious npm packages: how to spot them and what to doA malicious npm package steals credentials or runs code at install time. Learn how it gets in, how to tell if you were hit and what to do right now.

More in Security

See all 24 articles