Skip to main content
DevTool House
Back to Blogs
Developer Guides

How to Add Security Headers in Nginx, Express and Next.js

Which security headers matter, and tested configurations for HSTS, CSP, X-Frame-Options and more in Nginx, Express with Helmet, and Next.js.

By Wali UllahNovember 25, 20267 min read
A shield with a green lock in front of a response card listing HSTS, CSP and X-Frame-Options

Security headers are a handful of HTTP response headers that tell the browser how to treat your site: always use HTTPS, never let other sites frame you, don't guess file types, and only run scripts from sources you trust. They take minutes to add, cost nothing in performance, and close whole classes of attacks. This guide shows which headers matter in practice, then exactly how to add them in Nginx, Express and Next.js, the three places I set them most often.

Before and after making changes, run your site through the HTTP Headers Checker. It fetches your live response headers and flags the important ones that are missing.

The headers worth adding

Header Recommended value What it prevents
Strict-Transport-Security max-age=31536000; includeSubDomains Downgrade to plain HTTP and cookie theft on public Wi-Fi
Content-Security-Policy Depends on your site (see below) Cross-site scripting (XSS) and injected third-party scripts
X-Frame-Options SAMEORIGIN (or DENY) Clickjacking: your page hidden inside a malicious <iframe>
X-Content-Type-Options nosniff The browser running an "image" upload as a script
Referrer-Policy strict-origin-when-cross-origin Leaking full URLs, including tokens in query strings, to other sites
Permissions-Policy camera=(), microphone=(), geolocation=() Embedded content using powerful browser features you never use

Two older headers deserve a note:

  • X-XSS-Protection is obsolete. Modern browsers removed the filter it controlled, and the old value 1; mode=block could itself be abused in older browsers. Current advice is to send X-XSS-Protection: 0 or leave it out, which is exactly what Helmet does.
  • X-Frame-Options is still worth sending for older browsers, but the modern equivalent is the CSP frame-ancestors directive. Send both.

Start HSTS carefully

Strict-Transport-Security makes browsers refuse plain HTTP for your domain for max-age seconds. That is exactly its job, and exactly why a mistake hurts: if any subdomain still needs HTTP when you add includeSubDomains, it breaks for every visitor who has seen the header, until the max-age runs out.

Roll it out in steps: start with max-age=300 (5 minutes), check every subdomain, then raise it to a day, a week and finally a year (31536000). Only add preload and submit the domain to the browser preload list once you are certain, because removal takes months.

Content-Security-Policy: report first, enforce later

CSP is the most powerful header and the one most likely to break your site, because it blocks every script, style, image or connection you did not list. The safe way to introduce it:

  1. Send it as Content-Security-Policy-Report-Only first. The browser enforces nothing, but reports every violation in the DevTools console.
  2. Browse every page type, fix or allow what is legitimately needed (your CDN, analytics, payment provider), and remove what is not.
  3. When the console stays clean, rename the header to Content-Security-Policy.

A strict starting point for a site that serves its own scripts:

default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'self'; object-src 'none'; base-uri 'self'; form-action 'self'

Every third-party service you use adds origins: Google Analytics or Tag Manager, AdSense, Stripe, a font CDN. Add them deliberately, one directive at a time.

Nginx

Put the headers in the server block that serves HTTPS:

server {
    listen 443 ssl;
    server_name example.com;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
    add_header Content-Security-Policy-Report-Only "default-src 'self'; object-src 'none'; base-uri 'self'" always;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

Two Nginx details catch almost everyone:

  • always. Without it, Nginx adds the headers only to successful responses (200, 204, 301, 302 and a few others), not to your 404 and 500 pages. Add always.
  • Inheritance. add_header directives are inherited from the outer level only if the inner level has no add_header of its own. The moment a location block adds a header (say Cache-Control for static files), every security header from the server block disappears for that location. Put the security headers in a file such as /etc/nginx/snippets/security-headers.conf and include it in every block that uses add_header.

After any change, run sudo nginx -t to test the configuration, then sudo systemctl reload nginx.

Express (Node.js)

Use Helmet. It is maintained, small, and sets sensible defaults with one line:

import express from 'express';
import helmet from 'helmet';

const app = express();
app.use(helmet());

With Helmet 8 and no options, every response gets these headers:

content-security-policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
cross-origin-opener-policy: same-origin
cross-origin-resource-policy: same-origin
origin-agent-cluster: ?1
referrer-policy: no-referrer
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-download-options: noopen
x-frame-options: SAMEORIGIN
x-permitted-cross-domain-policies: none
x-xss-protection: 0

For a JSON-only API, these defaults are usually fine as they are. For an Express app that renders pages with third-party scripts, customize the CSP rather than turning it off:

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        'script-src': ["'self'", 'https://www.googletagmanager.com'],
        'img-src': ["'self'", 'data:', 'https:'],
      },
    },
    referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
  })
);

Two things to watch:

  • cross-origin-resource-policy: same-origin stops other sites from loading your resources. If your API serves images or files that a frontend on another domain displays, set crossOriginResourcePolicy: { policy: 'cross-origin' }.
  • Behind Nginx, choose one place. If both Nginx and Helmet set the same header, browsers may receive it twice with different values. Decide which layer owns each header.

Next.js

In Next.js, set headers in next.config with the headers() function. It applies to pages, API routes and static files:

// next.config.ts
import type { NextConfig } from 'next';

const securityHeaders = [
  { key: 'Strict-Transport-Security', value: 'max-age=31536000; includeSubDomains' },
  { key: 'X-Frame-Options', value: 'SAMEORIGIN' },
  { key: 'X-Content-Type-Options', value: 'nosniff' },
  { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
  { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=()' },
];

const nextConfig: NextConfig = {
  async headers() {
    return [{ source: '/:path*', headers: securityHeaders }];
  },
};

export default nextConfig;

CSP in Next.js needs more care, because the framework injects inline scripts for hydration. A static script-src 'self' will break the page. The documented approach is a nonce: generate a random value per request in middleware (in newer Next.js versions the file is called proxy), put it in the CSP header, and Next.js adds it to its own script tags. Start with Content-Security-Policy-Report-Only here as well, and test that every page still hydrates.

Check the result

From a terminal:

curl -sI https://example.com | grep -iE "strict-transport|content-security|x-frame|x-content-type|referrer-policy|permissions-policy"

Or paste the URL into the HTTP Headers Checker for a readable report. Check a 404 page too, to confirm the headers are sent on error responses (the Nginx always problem).

FAQ

Which security headers should every website have?

At minimum Strict-Transport-Security, X-Content-Type-Options: nosniff, X-Frame-Options (or CSP frame-ancestors), and Referrer-Policy. Add a Content-Security-Policy next: it takes the most work, and it protects the most.

How do I add security headers in Nginx?

Use add_header with the always parameter in your HTTPS server block, keep them in a snippet you include wherever a block has its own add_header lines, then run nginx -t and reload.

Does Helmet add HSTS in Express?

Yes. app.use(helmet()) sends Strict-Transport-Security: max-age=31536000; includeSubDomains by default, along with a default CSP, X-Content-Type-Options, X-Frame-Options and several other headers.

Why did my site break after adding a Content-Security-Policy?

The policy blocked a script, style or connection you did not list, often analytics, a font or CDN, or inline scripts. Switch to Content-Security-Policy-Report-Only, read the violations in the browser console, add the sources you actually need, then enforce it again.

Is X-XSS-Protection still needed?

No. Modern browsers ignore it, and the old 1; mode=block value caused problems of its own. Send X-XSS-Protection: 0 or omit it, and rely on a Content-Security-Policy instead.

Try the related tools

Related articles