JAVASCRIPT
Enforcing X-Content-Type-Options: nosniff to Prevent MIME Sniffing
Enhance web security by instructing browsers to disable MIME-sniffing, preventing them from interpreting files as a different content type.
const express = require('express');
const helmet = require('helmet'); // Helmet adds X-Content-Type-Options by default
const app = express();
// Option 1: Using Helmet (recommended for Express)
// Helmet includes `nosniff` as part of its default headers,
// so just `app.use(helmet());` would add it.
// To explicitly set it:
app.use(helmet.noSniff());
// Option 2: Manually setting the header without Helmet
/*
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
});
*/
app.get('/styles.css', (req, res) => {
// Intentionally send wrong Content-Type to show nosniff effect (in theory)
// In a real app, you would send 'text/css' for CSS files.
res.setHeader('Content-Type', 'text/plain');
res.send('body { background-color: lightblue; }');
});
app.get('/', (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<title>Nosniff Example</title>
<link rel=\"stylesheet\" href=\"/styles.css\"> <!-- Browser will try to load this as CSS -->
</head>
<body>
<h1>X-Content-Type-Options: nosniff in action</h1>
<p>If the browser respects 'nosniff' and the server sends a wrong Content-Type for the CSS,
the CSS won't be applied, preventing potential security issues.</p>
</body>
</html>
`);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: The `X-Content-Type-Options: nosniff` HTTP response header is a security feature that prevents browsers from "MIME-sniffing" a response away from the declared `Content-Type`. MIME sniffing can be a security vulnerability, especially for user-uploaded content, as it allows attackers to disguise malicious files (e.g., an executable disguised as an image) which the browser might then execute or interpret in an unintended way. This Node.js Express snippet demonstrates how to enforce `nosniff` using the `helmet` middleware or by manually setting the header, ensuring that the browser strictly adheres to the content type specified by the server.