Skip to content

No Content-Type header when returning a stream #3891

@sholladay

Description

@sholladay

What are you trying to achieve or the steps to reproduce?

Trying to respond with a stream and receive an appropriate content-type header on the client.

Under most circumstances, hapi sends a content-type header automatically based on whatever the return value of my handler is. However, if the handler returns a stream, this doesn't happen.

Here is a reproducible example that shows no content-type header being sent for a simple "Hello, world!" stream. The response headers are logged to the server's console when starting the server and also rendered in the browser if you visit /.

Edit o5wlywl7pz

Source code
"use strict";

const hapi = require("hapi");
const { Readable } = require("stream");

const server = hapi.server({ port: 8000 });
server.route({
  method: "GET",
  path: "/hello",
  handler() {
    const stream = new Readable({
      read() {
        this.push("Hello, world!");
        this.push(null);
      }
    });

    return stream;
  }
});

server.route({
  method: "GET",
  path: "/{anything*}",
  handler() {
    return `
      <html><script>
        fetch('/hello').then((response) => {
          const headers = Object.assign(...Array.from(response.headers, ([key, value]) => {
            return { [key]: value };
          }));
          const pre = document.createElement('pre');
          pre.textContent = JSON.stringify(headers, null, 4);
          document.body.appendChild(pre);
        });
      </script></html>
    `;
  }
});

server.inject("/hello").then(response => {
  console.log(JSON.stringify(response.headers, null, 4));
});

server.start();

What was the result you received?

No content-type header is sent in the response when the handler's return value is a simple "Hello, world!" readable stream.

What did you expect?

I expected hapi to set a content-type header whenever possible.

Ideally, I'd like it to be based on the actual contents of the stream, which could be determined by reading the first few bytes to inspect the magic number (also see the file-type module). But even the generic application/octect-stream would be better than nothing.

Context

  • node version: 8.11.3
  • hapi version: 17.6.0
  • os: macOS 10.13.6

Metadata

Metadata

Assignees

Labels

bugBug or defect

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions