Browsers Refuse a Stylesheet Served with the Wrong Content-Type

In progress Docker AppSec

A browser applies a stylesheet only if the response says it is one: Content-Type: text/css. When a server labels style.css as text/plain (or text/html, often an error page served in its place), the browser refuses it and the page renders unstyled, with nothing wrong in the server logs. With X-Content-Type-Options: nosniff, scripts with a non-JavaScript type are blocked the same way. The fix is making the server's type mapping explicit.

The Symptom

Refused to apply style from 'http://localhost:4000/static/css/style.css' because its
MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME
checking is enabled.

The request succeeds (status 200), which is why it is easy to miss: only the type is wrong.

Where Python Servers Get the Type

Starlette's StaticFiles (used by FastAPI) and many Python servers ask the standard mimetypes module, which combines a built-in table with system files such as /etc/mime.types. Minimal container images ship few system packages, and platform registries (on Windows) can override mappings, so the same code can return different types on a laptop and in a container.

Make the Mapping Explicit at Startup

import mimetypes

mimetypes.init()
mimetypes.add_type("text/css", ".css")
mimetypes.add_type("text/javascript", ".js")
mimetypes.add_type("image/svg+xml", ".svg")

Run it in the module that creates the app, before static files are mounted; the server then returns the right type whatever the host provides.

Open Question

In my case the image was python:3.12-slim, and the explicit mapping fixed it. Python's mimetypes has a built-in .css entry, so the missing system file may not be the whole story; worth reproducing to find the real override.

References

Review cards

Flashcard Why can a page render unstyled although `style.css` returns 200?

The browser applies a stylesheet only if it's served as Content-Type: text/css. Served as text/plain or text/html, it's refused, and the server logs show nothing wrong.

Flashcard Before fixing MIME mappings for a refused stylesheet, what should you check, and how?

The response body: a misconfigured static path can let a catch-all route answer with an HTML page, which is also refused. curl -sI <url> | grep -i content-type shows what the browser gets.

Quiz How do you make a FastAPI app return `text/css` for `.css` whatever the container provides?
  • Call mimetypes.add_type("text/css", ".css") at startup, before mounting static files
  • Rely on the host's /etc/mime.types
  • Add X-Content-Type-Options: nosniff
  • Rename the file to style.css.txt

Starlette's StaticFiles asks the mimetypes module, which depends on the host's files and registries. An explicit mapping makes the answer the same everywhere; nosniff makes browsers stricter, not the server right.