patternjavascriptModerate
Content-Type Sniffing Prevention with X-Content-Type-Options
Viewed 0 times
mime sniffingx-content-type-optionsnosniffcontent typemime confusionhelmetfile upload security
Error Messages
Problem
Some browsers try to detect resource types by examining content rather than trusting the server's Content-Type header. Attackers can exploit this to load a file with a safe extension as an executable script.
Solution
Set the X-Content-Type-Options: nosniff header on all responses. This instructs browsers to honour the declared Content-Type and not guess from content.
Why
Without nosniff, a browser might execute a JavaScript file uploaded with a .jpg extension if the content looks like a script. nosniff eliminates this class of MIME confusion attacks.
Gotchas
- nosniff also affects CSS and script loading—the browser will refuse to load stylesheets served without text/css and scripts without a JavaScript MIME type
- This header is particularly important on file-serving endpoints where users can upload content
- helmet sets this header by default via helmet.noSniff()
Code Snippets
Setting X-Content-Type-Options via helmet
const helmet = require('helmet');
// Included in helmet() default setup
app.use(helmet());
// Or explicitly:
app.use(helmet.noSniff());
// Adds: X-Content-Type-Options: nosniff
// Also ensure correct content types on file responses
app.get('/uploads/:file', (req, res) => {
// Set explicit MIME type rather than letting it be guessed
res.type('image/jpeg');
res.sendFile(resolvedPath);
});Revisions (0)
No revisions yet.