Require `Content-Type` HTTP response header with appropriate value

Require Content-Type HTTP response header with appropriate value (content-type)

content-type warns against not serving resources with the Content-Type HTTP response header with a value containing the appropriate media type and charset for the response.

Why is this important?

Even thought browsers sometimes ignore the value of the Content-Type header and try to sniff the content, it’s indicated to always send the appropriate media type and charset for the response as, among other:

What does the rule check?

The rule checks if responses include the Content-Type HTTP response header and its value contains the appropiate media type and charset for the response.

Examples that trigger the rule

Content-Type response header is not sent:

HTTP/... 200 OK
...

Content-Type response header is sent with an invalid value:

HTTP/... 200 OK
...
Content-Type: invalid
HTTP/... 200 OK
...
Content-Type: text/html;;;

Content-Type response header is sent with the wrong media type:

For /example.png

HTTP/... 200 OK
...
Content-Type: font/woff2

Content-Type response header is sent with an unofficial media type:

For /example.js

HTTP/... 200 OK
...
Content-Type: application/x-javascript; charset=utf-8

Content-Type response header is sent without the charset parameter for response that should have it:

For /example.html

HTTP/... 200 OK
...
Content-Type: text/html

Examples that pass the rule

For /example.png

HTTP/... 200 OK
...
Content-Type: image/png

For /example.js

HTTP/... 200 OK
...
Content-Type: application/javascript; charset=utf-8

Can the rule be configured?

You can overwrite the defaults by specifying custom values for the Content-Type header and the regular expressions that match the URLs for which those values should be required.

<regex>: <content_type_value>

E.g. The following configuration will make sonar require that all resources requested from a URL that matches the regular expression .*\.js be served with a Content-Type header with the value of text/javascript; charset=utf-8.

"content-type": [ "warning", {
".*\\.js": "text/javascript; charset=utf-8"
}]

Note: You can also use the ignoredUrls property from the .sonarrc file to exclude domains you don’t control (e.g.: CDNs) from these checks.

Further Reading