The GET /api/v1/users/42 endpoint in your API already works: the data is right, and the status is 200. But the browser that receives that response can still take a wrong step. The browser can guess the content is a script, show it inside another site's frame, or open it over plain HTTP.
What prevents that is security headers: headers in a response that tell the browser how to treat that response. For example: don't guess what kind of content it is, don't show it inside another site's frame, and always use HTTPS. An API gateway is a server standing in front of all your API services (API programs that run separately), such as nginx. Every response passes through the gateway, so the headers only need to be set once, there. Picture a label on a parcel: "Contents: documents. Do not display in another shop's window." The courier follows that label. The shipping desk at the front of the building sticks the same label on every parcel going out, whichever department sent it. In your API, the parcel is the response, the label is the security headers, the courier is the browser, the shipping desk is the gateway, and the departments are the services.
The headers every API response gets
| Header | Value | What it does |
|---|---|---|
X-Content-Type-Options |
nosniff |
the browser must trust Content-Type and may not guess the kind of content |
X-Frame-Options |
DENY or SAMEORIGIN |
the response may not show inside another site's <iframe> |
Referrer-Policy |
strict-origin-when-cross-origin |
to other sites, the Referer header (the address of the page you came from) holds only the origin, not the full URL (HTTPS to HTTP: not sent) |
Strict-Transport-Security |
max-age=31536000; includeSubDomains |
the browser always uses HTTPS for 1 year |
Cache-Control |
no-store |
a response with personal data isn't kept in any cache |
There are also headers to remove: X-Powered-By: Express and the version in Server: nginx/1.27.0. Those two headers tell an attacker which software and version you run. The attacker only has to look for the holes in that version.
nosniff: trust the label, don't guess
MIME sniffing is the browser's habit of guessing the kind of content (the MIME type) from the content itself, not from the Content-Type header (the label for the kind of content, for example text/plain for plain text). Attackers can abuse that guess. Say the endpoint GET /api/v1/notes/7 returns a note a user wrote, with Content-Type: text/plain. A page on another site loads that note as a script:
<script src="https://api.myapp.com/api/v1/notes/7"></script>
If the note happens to be valid JavaScript, a browser without nosniff will run it as a script. With X-Content-Type-Options: nosniff, the browser keeps to the text/plain label and refuses. Chrome writes in the console:
Refused to execute script from 'https://api.myapp.com/api/v1/notes/7' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.
The same rule covers stylesheets: with nosniff, a file whose Content-Type isn't text/css isn't used as CSS. This header has only one value: nosniff.
X-Frame-Options: DENY or SAMEORIGIN
X-Frame-Options controls who may show your response inside an <iframe>:
DENY: nobody may frame it, your own site included. This is the right value for an API.SAMEORIGIN: only pages from the same origin (same scheme, host, and port) may frame it.
In the Clickjacking lesson you met its modern version in CSP: frame-ancestors 'none' (same as DENY) and frame-ancestors 'self' (same as SAMEORIGIN). Setting both is safe: modern browsers use frame-ancestors, old ones use X-Frame-Options.
Setting them on the nginx gateway
On the nginx gateway, you set headers with add_header. Server details are hidden with two lines, server_tokens and proxy_hide_header:
server {
listen 443 ssl;
server_name api.myapp.com;
server_tokens off;
proxy_hide_header X-Powered-By;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location /api/ {
proxy_pass http://backend:8000;
}
}
Guess before you read on: if the word always is dropped, leaving add_header X-Content-Type-Options "nosniff";, a 200 OK response still carries that header. Does a 404 Not Found response carry it too?
server_tokens off;turnsServer: nginx/1.27.0intoServer: nginx, with no version.proxy_hide_header X-Powered-By;removes theX-Powered-Byheader the backend sends, before the response reaches the browser. The backend is the application behind the gateway, whereproxy_passpasses the requests on.add_header ... always;attaches a header to the response. The wordalwaysmakes the header go on error responses such as 404 and 500 too. Withoutalways, nginx only adds it to codes 200, 201, 204, 206, 301, 302, 303, 304, 307, and 308. So withoutalways, a 404 response does not carrynosniff.
The result: GET /api/v1/users/42 and GET /api/v1/users/999 (a 404) both arrive with these headers:
Server: nginx
Content-Type: application/json; charset=utf-8
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Strict-Transport-Security: max-age=31536000; includeSubDomains
At the application level: Express middleware
With no gateway, set the same headers in the application. This is Express middleware that runs first, before every route:
app.disable("x-powered-by"); // drop X-Powered-By: Express
app.use((req, res, next) => {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
res.setHeader("Cache-Control", "no-store");
next();
});
app.disable("x-powered-by")turns off Express's built-inX-Powered-Byheader.res.setHeader(name, value)attaches one header to the response, andnext()passes the request on to the next route.Cache-Control: no-storefits best in the application, because the application knows which endpoints hold personal data.
The helmet package sets most of these headers at once with app.use(helmet()).
💡 The gateway also handles rate limits and request size
The gateway is also a good place to limit the number of requests (you learned why in the Rate Limiting lesson) and the body size. Mind where it goes: limit_req_zone must be in the http block. Put it in a server block and nginx refuses to start, with the message "limit_req_zone" directive is not allowed here.
http {
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
server_name api.myapp.com;
location /api/ {
limit_req zone=api burst=20 nodelay;
client_max_body_size 10m;
proxy_pass http://backend:8000;
}
}
}
limit_req_zonesets up a rule namedapi, thenlimit_req zone=apiuses that rule inlocation /api/.rate=10r/smeans 10 requests per second per IP address.burst=20still accepts a spike of up to 20 extra requests, before nginx answers 503.client_max_body_size 10mrefuses a body over 10 MB with 413.
⚠️ Headers that go missing or get ignored
- Forgetting
always. The security headers are only on 200 responses, then disappear on 404 and 500. Browsers read error responses too, so addalwaysto everyadd_header. - An
add_headerinsidelocationremoves the ones inserver. nginx only inheritsadd_headerfrom the level above (for exampleserver) when the level below it (for examplelocation) has noadd_headerat all. A singleadd_header Cache-Control "no-store" always;inlocation /api/makes every security header fromserverdisappear in thatlocation. Repeat the headers in thelocation, for example through anincludefile (a file of lines you reuse). - Misspelled values.
nosnif(a typo), or the old valueX-Frame-Options: ALLOW-FROM https://..., are ignored by browsers. The values must be exactlynosniff,DENY, orSAMEORIGIN. - Setting
X-XSS-Protection: 1; mode=block. This header turned on an old XSS filter in browsers, and that filter has been removed from modern browsers. OWASP recommendsX-XSS-Protection: 0, or not setting it at all. The real XSS defence is escaping and CSP.
TL;DR: Security headers are instructions to the browser inside a response. An API gateway (a server in front of all your API services) such as nginx sets them once for every service. Set X-Content-Type-Options: nosniff (the browser may not guess the content type, so text/plain can't run as a script), X-Frame-Options: DENY (or SAMEORIGIN when your own origin may show it in a frame), Referrer-Policy: strict-origin-when-cross-origin (send only the origin to other sites), and Strict-Transport-Security (always HTTPS). Remove X-Powered-By and the version in the Server header with proxy_hide_header and server_tokens off. In nginx, write always so the headers also go on 404 and 500 responses. Also remember: an add_header in a location block removes the headers inherited from the server block. In Express, set the headers with res.setHeader in middleware, and turn off x-powered-by.
⚡ Instructions for the browser
Meaning: Security headers are headers in a response that tell the browser how to treat that response. The ones to set: X-Content-Type-Options: nosniff (don't guess the kind of content), X-Frame-Options: DENY (don't show it in a frame), Referrer-Policy (limit the address sent to other sites), Strict-Transport-Security (always HTTPS), and Cache-Control: no-store for personal data. X-Powered-By and the version in Server are removed, so attackers don't learn your software.
⚡ nosniff: trust the label
Meaning: Content-Type is the label for the kind of content in a response. Without nosniff, a browser can guess that a text/plain response that happens to hold valid JavaScript is a script, and run it. With nosniff, the browser keeps to the text/plain label and refuses.
⚡ Set them once at the gateway
Write:
server_tokens off;
proxy_hide_header X-Powered-By;
add_header X-Content-Type-Options "nosniff" always;
Guess first: add_header attaches a header to the response. Without the word always, does a 404 Not Found response carry that header too?
No. Without always, nginx only adds it to codes such as 200, 201, 204 and 30x. The security headers disappear on 404 and 500.
Meaning: On the nginx gateway (a server in front of all your API services), the headers are set once for every response. server_tokens off; hides nginx's version, and proxy_hide_header removes the backend's X-Powered-By (the backend is the application behind the gateway).
⚡ The values must be exact
Meaning: A misspelled value such as nosnif, or the old X-Frame-Options value ALLOW-FROM, is ignored by browsers. X-XSS-Protection: 1; mode=block (an old XSS filter in browsers) is obsolete: OWASP recommends 0, or not setting it at all.