In my current project, I am utilizing Next.js with Typescript. A unique scenario has arisen where the Next.JS client and server are on separate hosts.
The client necessitates displaying an image from a different service located at localhost:3001/....
, but this service is only accessible on the Next.JS server machine and not where the browser is situated. To address this discrepancy, I have implemented URL proxying through the Next.JS server by modifying all src
attributes in the image tags using a function that rewrites the URLs to something like
/api/image-rewrite?orig=<base 64 of original URL>
. This modification is successful.
The next step involves handling the request in the Next.JS API route image-rewrite
. Upon extracting the original URL from the orig
search parameter, I proceed to execute a fetch
operation on it within this context. The fetched image can be confirmed via content-type and content-length verification.
My objective now is to relay this image back to the Next.JS client; nevertheless, I encounter obstacles preventing the completion of this task. Below is pertinent code snippet (excluding error checks - assume data validity and correct content type (image/jpeg) and size):
// Parse out the original URL and fetch it
const parsedURL = Buffer.from(originalURL as string, 'base64').toString('ascii');
const orig_url = new URL(parsedURL);
const full_url = new URL(`${BASE_URL}/render${orig_url.search}`);
const imgResp = await fetch(full_url);
// Retrieve necessary information (body, content type, content length)
const body: ReadableStream<Uint8Array> | null = imgResp.body;
const contentType: string | null = imgResp.headers.get('Content-Type');
let contentLength: string | number | null = imgResp.headers.get('Content-Length');
contentLength = Number(contentLength);
// Send response to client
res.writeHead(
200,
{
'Content-Type': contentType,
'Content-Length': contentLength as number
}
);
Multiple methods were attempted:
Directly writing out the imgResp
body:
return res.write(body);
Using stream
to stream the body into res
("no overloads match this call"):
stream.pipeline(body, res);
Attempting to pipe the body into res
("Argument of type 'NextApiResponse' is not assignable to parameter of type 'WritableStream'."):
body.pipeTo(res);
I am seeking guidance on how to resolve these issues effectively.