Get Picture from NextJS API endpoint

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.

Answer №1

Uncertain of the exact reason behind its functionality, but this is the solution that proved effective:

const response = await axios({ url, method: 'GET', responseType: 'stream' });

// Various error checks...

await new Promise<void>(
    (resolve) => {
        response.data.pipe(res);
        response.data.on("end", () => { resolve(); });
    }
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting haxe-pixi.js to function properly as it only shows a blank white screen

***UPDATE: Success! Managed to solve the issue. It turns out the missing library in the html file was causing the problem. The pixi.min.js file was not present in the haxelib directory, which seems a bit unusual. Here's a more challenging question: i ...

Guidelines for establishing an NPM Typescript package during development to uphold import syntax

Currently, I am in the process of developing an NPM TypeScript package for code-splitting from my main application. Both projects are located within a shared root directory structure: - mylib - package.json - tsconfig.json - src/ - dist/ - myapp ...

Utilize @types for the Typescript npm library without the need for downstream projects to install this dependency

Our npm library package, built in TypeScript and known as lib-utils, provides a range of utilities for other projects to leverage. One of the dependencies within lib-utils is d3, which is both a peerDependency and a devDependency. Additionally, there is a ...

Tips for setting up outlet in Next.js with the app router

I recently set up a basic Next.js app with the following structure app(dir) page.js layout.js student(dir) --page.js Within this structure, layout.js includes: import { Inter } from "next/font/google"; const inter = Inter({ subsets: ["lati ...

Tips for adjusting the size to ensure full browser window opening using selenium web-driver in JavaScript

I am facing an issue with my test setup where the selenium web-driver window that opens appears to be too small. This is causing problems as some elements that I need to interact with are hidden in menus due to the browser size. I would like to find a way ...

Vue: The async Apollo mixin function successfully logs a value, however it ultimately returns as undefined

I've encountered numerous async/return undefined queries on this platform, but despite trying various solutions, I'm unable to make any progress. My apologies if I overlooked something obvious. In an attempt to improve reusability, I extracted a ...

Trouble with clicking inner elements after applying JQuery code to parent div

Currently, I have implemented a code for toggling a search bar and it is functioning properly. The toggle function is applied to the main div using a click function in jQuery. While the toggling works fine, there seems to be an issue when clicking on the i ...

Efficiently find alphabets in an array of strings by utilizing JavaScript

I have a list of various products shown below const allProducts = ['washing machine', 'sewing machine', 'refrigerator', 'desk'] If a user inputs any word in the search field, I want to display all matching products ...

The attempt to load a JavaScript resource has resulted in an error: the file was not located, despite the fact that it is a

Recently, I came across a new challenge in my application. Whenever I navigate to specific pages, I notice an error message in the development console: inject.preload.js:373 GET blob:http://my-app-name.test/ba65127c-383e-45b7-8159-9b52ea288658 0 () Upon ...

Is there a way to incorporate the ACE code editor into a Vue project without relying on its built-in Vue

Just starting out with Vue and I'm looking to incorporate the ace code editor (this package) into my project. However, I want to avoid using the vue2-component & vue3-component versions for learning purposes. How can I achieve this? What's t ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

unable to determine the reason for the undefined value

My function is designed to remove an element tag when it's clicked on and also remove the corresponding content/ingredient from another list. Everything seems to work fine in the browser, but when I check the console, a TypeError pops up, and I can&ap ...

What are the differences between incorporating JavaScript directly into HTML and writing it in a separate file?

I need help converting this JavaScript embedded in HTML code into a standalone JavaScript file. I am creating a toggle switch that, when clicked, should go to a new page after the transformation. I am looking for the non-embedded version of the function. H ...

Failure to Fetch the Uploaded File's Value Using the Parameter

Objective: My aim is to automatically upload the second input named "file2" to the action result using jQuery code that is compatible with the latest versions of Firefox, Chrome, and Internet Explorer. Issue: The problem arises when HttpPostedFileBase ...

Retrieve a value using the jQuery each() method

Hello, I am a beginner in JavaScript and I need help with extracting values from JSON and adding them to an array. My goal is to be able to parse this array using another function later on. However, I'm struggling with returning the array after adding ...

Separate the JSON array according to the type of suggestion it's being given

My JSON array is structured like this: [ { "characterID": 0, "description": "Series 1", "id": 1, "seriesID": 0, "status": "ACCEPTED", "type": "SE ...

Node.JS using Express: Issue : encountering EADDRINUSE error due to address being already in use

Currently, I am in the process of developing a CRUD API with Node.js and Express. Everything was going smoothly until today when a new error message popped up. It appears that I can only use a TCP Port once. Whenever the server is stopped and restarted, I ...

retrieving XML information through DOM children elements

Suppose I have an XML object in the following format: <book id="01"> <author>Conner, Jim</author> <title>House Hunter</title> <genre>DIY</genre> <price>5.95</price> <publish_date>2000-1 ...

A guide on dividing date strings within a JavaScript array

When dealing with an array of Month/Day/Year datestrings like the one below... const array1 = ["05/31/2022", "06/01/2022", "06/02/2022"] ...my goal is to modify the array to exclude any datestrings (starting with 01 as the Day) that come after datestrings ...

Examining Angular Modules using Jasmine Unit Tests

Currently, I am integrating an AngularJS service into my application. Upon testing, I discovered that the service is not as reliable as I had hoped. To address this issue, I decided to implement some unit tests for it. While the service functions properly ...