Search code examples
next.jsnext.js13next.js14

How do I return blobs from Route Handlers with Next.js 14?


I am trying to download a blob off of my Next.js 14 route handler from a client component. I am on Next version 14.04.

Behaviour that should be observed: On loading the client code, the useEffect will run and call the route handler. The request should be printed to console, then the blob body read from the ReadableStream, then "blob" will be printed to console.

Behavior that is observed: The request is printed to console, but "blob" is never printed to console because res.blob() stalls forever.

Route handler (/test/api/route.ts):

export async function GET(request: Request) {
  const res = await fetch("https://picsum.photos/200/300");
  console.log(res);
  const blob = await res.blob();
  return new Response(blob);
}

Client code:

"use client";
import React, { useEffect } from "react";

const page = () => {
  useEffect(() => {
    const getData = async () => {
      const res = await fetch("/test/api");
      console.log(res);
      const blob = await res.blob();
      console.log("blob");
    };
    getData();
  });
  return <div>page</div>;
};

export default page;

I'm wondering if I'm doing something wrong here to cause the await res.blob() to stall forever.


Solution

  • With the route handler, just use the url ( localhost:3000/test/api ) as "src" of the image and that's all!

    Maybe you'll need to set some headers in the response (content-type) but i think it's fine!