Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 8 min read

X-Content-Type-Options: nosniff and MIME Sniffing Attacks

Most teams add X-Content-Type-Options: nosniff because a scanner told them to, then forget it. That is a shame, because this one-word header closes a real hole: it stops the browser from guessing what a file is and runni

X-Content-Type-Options: nosniff and MIME Sniffing Attacks

Most teams add X-Content-Type-Options: nosniff because a scanner told them to, then forget it. That is a shame, because this one-word header closes a real hole: it stops the browser from guessing what a file is and running an "image" or "text file" as script. It also has a habit of breaking deployments that serve JavaScript with the wrong MIME type, which is why it is worth understanding rather than copy-pasting.

I build PixelValut, a set of free browser-based tools for checking sites and files. I wrote this with help from AI tools and checked every command and claim myself.

Related video: for generating CSP, HSTS, CORS and Cache-Control headers, see 6 Free HTTP Header Generators on the PixelValut channel.

What does X-Content-Type-Options: nosniff do?

Direct answer: X-Content-Type-Options: nosniff tells the browser to trust the declared Content-Type instead of sniffing the bytes. With it, a script is blocked unless it is served with a JavaScript MIME type, and a stylesheet is blocked unless it is text/css. That stops uploaded files and mislabeled responses from being executed as code.

Why MIME sniffing exists, and why it is dangerous

Early web servers often sent no Content-Type or a wrong one, so browsers learned to look at the first bytes of a response and decide for themselves. That made broken sites work. It also meant the browser and the server could disagree about what a file is, and attackers live in that gap.

The classic scenario looks like this:

  1. Your app lets users upload avatars and serves them from the same origin, for example /uploads/7f3a.jpg.
  2. An attacker uploads a file that is valid JavaScript but named .jpg. Your server stores it and serves it as image/jpeg.
  3. Somewhere else on the site the attacker finds a small HTML injection. Your Content Security Policy says script-src 'self', so inline script is blocked.
  4. The attacker injects <script src="/uploads/7f3a.jpg"><\/script>. The file is same-origin, so CSP allows it.

Without nosniff, how the browser handles step 4 depends on its sniffing rules. With nosniff, modern browsers refuse to execute it, because image/jpeg is not a JavaScript MIME type. The header turns a CSP bypass into a console error.

The same idea applies to stylesheets. A user-controlled text file loaded with <link rel="stylesheet"> can be used for CSS-based data extraction on some pages. nosniff blocks styles that are not served as text/css.

What nosniff actually changes, by resource type

Resource request Without nosniff With nosniff What you must get right
<script src> Wrong MIME types may still run Blocked unless a JavaScript MIME type (e.g. text/javascript) Serve every JS file with text/javascript
<link rel="stylesheet"> Some browsers were lenient in quirks mode Blocked unless text/css Serve CSS as text/css
Cross-origin JSON, HTML, XML read by <img> or <script> Browser-dependent Chromium's read-blocking protections treat nosniff as a strong signal to block Correct Content-Type on API responses
Top-level page navigation Browser may sniff a missing or generic type Sniffing is reduced; behaviour still varies by browser Never serve user content as text/html
Images, fonts, media Mostly unaffected Mostly unaffected Still send accurate types

Two things to notice. First, nosniff is not a fix for a wrong Content-Type. If your API returns user-controlled JSON as text/html, a victim who opens that URL can get XSS, header or no header. Second, the header has exactly one valid value, nosniff. Anything else is ignored.

Checking a site from the command line

Start with the HTML page, then check the assets that matter most: your main JavaScript bundle and any user-uploaded files.

curl -sI https://example.com/ | grep -iE '^(content-type|x-content-type-options)'
curl -sI https://example.com/assets/app.3f9c1.js | grep -iE '^(content-type|x-content-type-options)'
curl -sI https://example.com/uploads/7f3a.jpg | grep -iE '^(content-type|x-content-type-options|content-disposition)'

A healthy result for the bundle looks like this (illustrative output for example.com):

content-type: text/javascript; charset=utf-8
x-content-type-options: nosniff

The results I see most often when auditing are less tidy:

# HTML has the header, but the JS bundle comes from a CDN or bucket without it
content-type: application/octet-stream

# Header present twice, once from the app and once from the proxy
x-content-type-options: nosniff
x-content-type-options: nosniff

The first case is the dangerous combination: if you add nosniff at the CDN later, that bundle stops loading. The duplicated header is harmless for this value, but it tells you two layers both think they own security headers, which usually means other headers disagree too.

For a browser-side check, the PixelValut security headers checker shows which headers a URL returns. Run it against the page and then against the direct URL of your main script and an uploaded file, because headers often differ between them.

Blurred lines of code on a dark monitor
AI-generated image.

Setting the header correctly

Nginx:

server {
    # "always" also sends it on 4xx/5xx responses
    add_header X-Content-Type-Options "nosniff" always;

    location /assets/ {
        # Careful: any add_header here REPLACES the server-level ones
        add_header Cache-Control "public, max-age=31536000, immutable" always;
        add_header X-Content-Type-Options "nosniff" always;
    }
}

That inheritance rule is the most common reason I find the header on HTML pages but missing on static assets. In Nginx, a location that defines its own add_header drops every add_header from the server block. Repeat the security headers in that location or move them into a shared include file.

Also check the MIME map. Older mime.types files map .js to application/javascript, which browsers accept, but a missing entry for .mjs falls back to default_type, often application/octet-stream. With nosniff, those ES modules stop loading.

Apache:

Header always set X-Content-Type-Options "nosniff"
AddType text/javascript .js .mjs

Node with Express: the helmet package sets nosniff by default, so check whether you already have it before adding a second middleware. In Laravel, a small middleware that sets the header on every response works, but if Nginx already sets it you only need one layer.

For object storage (S3, R2, GCS), the header comes from the bucket or CDN configuration, and the Content-Type comes from object metadata set at upload time. A deploy script that uploads files without setting types is a common cause of binary/octet-stream bundles.

Rolling it out without breaking production

  1. Inventory content types first. List every distinct Content-Type your JS and CSS assets return. Anything other than a JavaScript type or text/css must be fixed before enabling the header.
  2. Fix the MIME map on web servers and the upload metadata on buckets.
  3. Enable in staging and open the busiest pages with DevTools. Chromium logs a clear console error when it refuses a script or stylesheet because of its MIME type.
  4. Check third-party hosts you control, such as a bucket for widgets or a separate static subdomain.
  5. Enable in production on all layers that serve content, including error pages.
  6. Monitor client-side error reporting for script load failures for a few days.

User uploads: nosniff is one layer, not the plan

nosniff protects you when a mislabeled file is pulled in as script or style. It does not stop someone opening an uploaded HTML file directly. For user content, combine:

  • Serving uploads from a separate domain (e.g. a dedicated user-content host), not your main origin.
  • Content-Disposition: attachment for anything that is not an image you render.
  • Validating type by content, not extension, and re-encoding images.
  • A strict Content-Type set by your server, never copied from the upload request.
  • A CSP that limits where scripts can come from.

X-Content-Type-Options audit checklist

  • [ ] HTML responses return X-Content-Type-Options: nosniff
  • [ ] Main JS bundles return it and use text/javascript (or another JavaScript MIME type)
  • [ ] CSS returns it and uses text/css
  • [ ] .mjs files have a JavaScript MIME type
  • [ ] Error pages (404, 500) also send it (always in Nginx)
  • [ ] Nginx locations with their own add_header repeat the security headers
  • [ ] Bucket and CDN objects have correct Content-Type metadata
  • [ ] API responses use application/json, never text/html
  • [ ] User uploads are served from a separate host with safe headers
  • [ ] Only one layer owns security headers, documented in your runbook

If you are working through the rest of your header set, I have written about Permissions-Policy, Referrer-Policy and reading CSP and Trusted Types reports, which pair well with this one. For pinning third-party scripts, see Subresource Integrity.

FAQ

Is X-Content-Type-Options still needed in modern browsers?

Yes. Modern browsers sniff less than old ones, but the header is what makes them strictly enforce MIME types for scripts and stylesheets, and Chromium uses it as a signal for blocking cross-origin reads. It costs nothing to send.

What values does X-Content-Type-Options accept?

Only nosniff. There is no "off" value and no other option. If you see something like X-Content-Type-Options: none, browsers ignore it, which is the same as not sending the header.

Will nosniff break my site?

It can, if any script or stylesheet is served with the wrong Content-Type. Typical causes are application/octet-stream from buckets, missing .mjs mappings and text/plain from misconfigured servers. Fix the types first, then enable the header.

Does nosniff prevent XSS?

Not on its own. It blocks one technique, running a mislabeled file as script, which matters most when CSP allows same-origin scripts. You still need output encoding, correct content types and a solid Content Security Policy.

Should I set it on images and fonts?

Set it on every response. It mainly affects scripts, stylesheets and cross-origin reads, but sending it everywhere is simpler than tracking which responses need it, and it avoids gaps on error pages and new routes.

Where should I set it: app, proxy or CDN?

At the outermost layer that serves all your content, usually the reverse proxy or CDN, so static files and error pages get it too. Avoid setting it in several places; pick one owner and document it.

The short version

Send X-Content-Type-Options: nosniff everywhere, but first make sure every script and stylesheet has the right Content-Type. Watch out for Nginx add_header inheritance and bucket metadata, and keep user uploads on a separate host. Check the page and your asset URLs separately, because they rarely share the same headers.

Follow & Connect

Watch on YouTube: Resume Boost AI · PixelValut · Daily AI News By Ali

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.