2

I've recently been working on a little project to serve static files. I want to be able to serve different types of files like:

html, jpg, png, pdf, doc...

All files seem to render correctly in different browsers without assigning a MIME type.

For example, if I serve an image and declare a MIME type I would write this in my node.js code:

response.writeHead(200, {'Content-Type': 'image/jpg'});
response.end(data);

Ignoring the MIME type will render the exact same results in different browsers:

response.writeHead(200);
response.end(data);

It is my understanding that if no MIME type is declared in the header, the browser will do its best to figure it out.

According to the HTTP specifications, the 'Content-Type' header is not required.

As with all multipart MIME types, each part has an optional "Content-Type", which defaults to text/plain.

Should I declare a MIME type for each response? Why?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
samland
  • 192
  • 1
  • 12
  • 2
    That part of the spec (which btw is obsoleted by rfc7578) you point to is about multipart form encoding from a client perspective. Your question seems to be about whether a server should include a Content-Type header. Which are kind of unrelated subjects. – Matt Harrison May 08 '16 at 21:19
  • This has nothing to do with JavaScript or Node.js. It doesn't matter how the server is implemented. – Bergi May 08 '16 at 22:41

2 Answers2

3

You are quoting a MIME RFC. But in this context, Content-Type is under authority of RFC 7231, section 3.1.1.5 which reads (emphasis mine):

A sender that generates a message containing a payload body SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender.

On a practical note, if you omit this header you are leaving the client with guesswork over filename extensions and magic bytes. A Content-Type header will have precedence over those and save the client quite some work.

The relevant part of the RFC addresses this as follows:

Clients that do so risk drawing incorrect conclusions, which might expose additional security risks (e.g., "privilege escalation"). Furthermore, it is impossible to determine the sender's intent by examining the data format: many data formats match multiple media types that differ only in processing semantics.

Community
  • 1
  • 1
DaSourcerer
  • 6,288
  • 5
  • 32
  • 55
2

You must set the mime type. It is useful for the client to determine the type of data it is dealing with. Nothing to do with node. It is http spec.

  • 1
    Check this SO http://stackoverflow.com/a/20392909/4466350 it adds the details about the spec. Which says that the client may try to guess, so it works most of the time. –  May 08 '16 at 21:09