Skip to content

Return Response.body from a fetch call as a stream #5279

@TJBlackman

Description

@TJBlackman

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.25.2

Plugin version

No response

Node.js version

20.10

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

11

Description

I make a fetch call on my Fastify server and I want to return the response from that fetch call as the response of my Fastify route as a stream.

I thought this would work since Fastify has stream docs (https://fastify.dev/docs/latest/Reference/Reply/#streams), but it does not.

Steps to Reproduce

Clone this github repo: https://github.com/TJBlackman/fastify-stream-test

Install dependencies and run the project:

  • npm i
  • npm run dev

Make requests to the API:

For the sake of completeness, here is the demo server file you could copy/paste if you want.

const fastify = require("fastify")({ logger: true });

// return JSON from SWAPI - works!
fastify.get("/api/json", async (request, reply) => {
  const response = await fetch("https://swapi.dev/api/people/1/");
  const json = await response.json();
  return reply.send(json);
});

// return stream from SWAPI - doesn't work
fastify.get("/api/stream", async (request, reply) => {
  const response = await fetch("https://swapi.dev/api/people/1/");
  return reply.send(response.body);
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});

Expected Behavior

The streamed response should be the same as the JSON response.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions