Don't Sniff Mimetype Middleware

1.1.0 · active · verified Wed Apr 22

This package provides a small, focused Express/Connect middleware designed to set the `X-Content-Type-Options` HTTP header to `nosniff`. This header is a crucial client-side security measure that prevents browsers from "sniffing" or inferring the MIME type of a response, thereby enforcing the `Content-Type` header explicitly sent by the server. Without it, browsers might execute files (like HTML or JavaScript) that are incorrectly served with a generic MIME type (e.g., `text/plain`), leading to cross-site scripting (XSS) or other content-based attacks. The current stable version is 1.1.0, which was last published in 2019, indicating a highly mature and stable, but infrequently updated, codebase. It is a standalone component of the broader Helmet.js suite, which includes this functionality by default. Its key differentiator is offering granular control over this specific security header without deploying the entire Helmet.js bundle.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to apply the `dont-sniff-mimetype` middleware to an Express application, showing how it sets the `X-Content-Type-Options: nosniff` header and prevents a browser from executing an incorrectly typed script.

import express from 'express';
import dontSniffMimetype from 'dont-sniff-mimetype';

const app = express();

// Apply the X-Content-Type-Options: nosniff header to all responses
app.use(dontSniffMimetype());

app.get('/', (req, res) => {
  res.set('Content-Type', 'text/html');
  res.send('<h1>Hello! MIME sniffing is prevented.</h1><script>console.log("This script runs because it's HTML, but if a JS file was served as text/plain, it would be blocked.");</script>');
});

app.get('/untrusted.txt', (req, res) => {
  // Serve a 'text' file that looks like JavaScript, but is explicitly text/plain
  // With 'nosniff', browsers will not execute this as script.
  res.set('Content-Type', 'text/plain');
  res.send('alert("This should not execute as JavaScript!"); console.log("MIME sniffed prevented for untrusted.txt");');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
  console.log('Visit / to see HTML. Visit /untrusted.txt and check headers/console.');
});

view raw JSON →