1. Home
  2. Blog
  3. Software Development

Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types tell the browser what a file is: HTML, JavaScript, an image, a PDF. The server sends one in the Content-Type header, and a wrong one can break a page or open a security hole. We served the same script and stylesheet with different types and headers to a real Chromium browser and recorded which ran and which were blocked, then checked what Python guesses for 16 common extensions.

9 min read
MIME types explained: Content-Type, nosniff and a common types list

Key takeaways

  • MIME types such as text/html and image/png describe a file’s format; servers send them in the Content-Type header.
  • Without nosniff, our script served as text/plain still ran; with X-Content-Type-Options: nosniff, the browser refused it.
  • A script served as image/png was blocked even without nosniff, and a stylesheet served as text/plain was ignored.
  • Python’s mimetypes module returned no type at all for .woff2 and .parquet on our system.

When a browser downloads a file, it does not trust the file name. It looks at the media type the server declares, and that decides whether the bytes are shown as a web page, run as JavaScript, displayed as an image or offered as a download. Get MIME types wrong and fonts fail to load, JSON appears as plain text, PDFs download instead of opening, or, worst of all, a user-uploaded file is executed as a script.

We tested behaviour in the Chromium-based browser built into our editor, against a small local Python server, and checked Python 3.13.6’s type guessing on Windows. Results in other browsers may differ in edge cases.

What is a MIME type?

MIME (Multipurpose Internet Mail Extensions) types were created for email attachments and are now officially called media types. The official registry is maintained by IANA. Every HTTP response with a body should carry one, and so should requests that send a body, such as a JSON POST to an API.

Type, subtype and parameters

text/html; charset=utf-8
type/subtype; parameter=value

application/json
image/svg+xml              (+xml suffix: an XML-based format)
application/vnd.api+json   (vnd.: vendor-specific)

The type is the broad category (text, image, audio, video, font, application, multipart), and the subtype the exact format. Parameters add details, most often the character set for text. Types are case-insensitive. application/octet-stream means “unknown binary data” and usually triggers a download.

HTTP/1.1 200 OK
Content-Type: text/javascript
X-Content-Type-Options: nosniff

The server chooses the type, usually from the file extension. Browsers also use the Accept request header to say which types they prefer, which lets servers return, for example, WebP images to browsers that support them. A separate header, Content-Disposition: attachment, forces a download regardless of type.

Our browser test

JS = b"window.R = (window.R || []); window.R.push(document.currentScript.dataset.name + ' RAN');"
ROUTES = {
  "/js-ok":            ("text/javascript",  False),
  "/js-plain":         ("text/plain",       False),
  "/js-plain-nosniff": ("text/plain",       True),    # True = send nosniff
  "/js-json-nosniff":  ("application/json", True),
  "/js-image":         ("image/png",        False),
  "/js-none":          (None,               False),   # no Content-Type at all
}

Every route returned the same tiny script, which records its own name if it runs. A test page loaded all six with ordinary script tags, and we read the list afterwards along with the browser console.

Scripts: what ran and what was blocked

Content-Type nosniff Result
text/javascript no Ran
text/plain no Ran
(none) no Ran
text/plain yes Blocked
application/json yes Blocked
image/png no Blocked
Refused to execute script from '/js-plain-nosniff' because its MIME type ('text/plain')
  is not executable, and strict MIME type checking is enabled.
Refused to execute script from '/js-image' because its MIME type ('image/png') is not executable.

Without the nosniff header, the browser was lenient: a script labelled as plain text, or with no type at all, still executed. With nosniff, any type that is not a JavaScript type was refused. Even without nosniff, the browser always refused to run a script declared as an image (it does the same for audio, video and CSV types), which closes the most obvious attack. The correct type for JavaScript is text/javascript; older values such as application/javascript are still accepted.

X-Content-Type-Options: nosniff

nosniff tells the browser to trust the declared type and never guess. According to MDN, browsers apply the blocking to script and style requests, and also stop sniffing other responses. Send it on every response; it costs nothing once your types are correct. Combined with a content security policy, it is one of the cheapest and most effective security headers.

Stylesheets

stylesheet served as text/plain, no nosniff   -> not applied (background transparent)
stylesheet served as text/css with nosniff    -> applied (background rgb(0, 128, 0))

Stylesheets were stricter than scripts: a CSS file served as text/plain was ignored even without nosniff, because standards-mode pages require text/css. This is a frequent cause of “the site has no styles after deployment” when a CDN or storage bucket serves files without types.

Why MIME sniffing is dangerous

Sniffing means the browser looks at the first bytes of a file and guesses its type. It was invented to cope with misconfigured servers, but it lets attackers smuggle code: upload a “profile picture” or “text file” that actually contains HTML or JavaScript, and if the site serves it from the same origin and the browser sniffs it as a script or page, the attacker’s code runs with the site’s cookies. Correct types, nosniff, and serving user uploads from a separate domain or with Content-Disposition: attachment close that door. The same origin rules interact with CORS when another site loads your files.

Common MIME types list

Extension MIME type
.html text/html
.css text/css
.js, .mjs text/javascript
.json application/json
.xml application/xml
.txt text/plain
.csv text/csv
.md text/markdown
.png, .jpg, .gif image/png, image/jpeg, image/gif
.webp, .avif image/webp, image/avif
.svg image/svg+xml
.ico image/vnd.microsoft.icon (image/x-icon is common)
.woff, .woff2 font/woff, font/woff2
.mp4, .webm video/mp4, video/webm
.mp3 audio/mpeg
.pdf application/pdf
.zip application/zip
.wasm application/wasm
Unknown binary application/octet-stream

WebAssembly is a type that must be exact: the browser’s streaming compile only accepts application/wasm. SVG files are XML documents that can contain scripts, so treat user-uploaded SVGs with the same care as HTML.

Guessing types in Python

import mimetypes
mimetypes.guess_type("app.js")          # ('text/javascript', None)
mimetypes.guess_type("logo.svg")        # ('image/svg+xml', None)
mimetypes.guess_type("archive.tar.gz")  # ('application/x-tar', 'gzip')
mimetypes.guess_type("notes.md")        # ('text/markdown', None)
mimetypes.guess_type("font.woff2")      # (None, None)
mimetypes.guess_type("data.parquet")    # (None, None)

Python’s mimetypes maps extensions to types using a built-in table plus the operating system’s own registrations (on Windows, the registry), so results can differ between machines. On ours, .woff2 and .parquet returned None, and a .tar.gz was reported as a tar file with gzip encoding, the second value. When you upload files to cloud storage or serve them from your own code, register the types you rely on with mimetypes.add_type("font/woff2", ".woff2") rather than trusting the default table. File handling in general is covered in our Python file handling guide.

Setting types on web servers and storage

Web servers such as nginx and Apache ship a mapping file from extensions to types; add entries for newer formats like WOFF2, AVIF and WebAssembly, set a safe default such as application/octet-stream for unknown files, and add the nosniff header to every response in the server or CDN configuration. Object storage services store a content type per file at upload time, which is the most common source of wrong types: if the upload tool did not set it, every visitor receives a generic binary type until you fix the file’s metadata. Caching layers keep whatever header they received, so purge cached copies after fixing it, as noted in our HTTP caching guide.

MIME types in APIs

  • Send Content-Type: application/json with JSON request bodies; many frameworks ignore or reject bodies without it.
  • Use Accept to request a format, and return 406 Not Acceptable or 415 Unsupported Media Type when you cannot serve or parse it; both appear in our HTTP status codes cheat sheet.
  • File uploads use multipart/form-data, with a separate type for each part.
  • Error responses can use application/problem+json, the standard error format for HTTP APIs.

MIME type checklist

  1. Every response has a correct, specific Content-Type; text types include charset=utf-8.
  2. The nosniff header is sent everywhere.
  3. Fonts, WebAssembly, SVG and modern image formats are mapped on the server and in upload tools.
  4. User uploads are served with a fixed safe type or as attachments, ideally from a separate domain.
  5. Check response headers in the browser’s network panel after every deployment.

Final thoughts

MIME types are a small header with large consequences. In our browser test, the same script ran or was refused depending only on its declared type and the nosniff header, and a stylesheet with the wrong type silently disappeared. Serve precise types, send nosniff on every response, register the formats your tools do not know, and never let user uploads be interpreted as code.

Frequently asked questions

What is a MIME type?

A label in the form type slash subtype, such as text/html or image/png, that tells software what format a file or response body is in. Servers send it in the Content-Type header.

What is the correct MIME type for JavaScript?

text/javascript. Older values such as application/javascript still work in browsers, but text/javascript is the current standard type for both scripts and modules.

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

It tells the browser not to guess a file type from its contents. Scripts and stylesheets with a non-matching declared type are then blocked, which prevents uploaded files from being executed.

What MIME type should I use for unknown files?

application/octet-stream, which means generic binary data. Browsers usually download such files instead of trying to display or run them.

What is the MIME type for JSON?

application/json. Use it for JSON responses and for JSON request bodies sent to an API.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →