What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this:

export default async function (req, res) {
    // prevent same site/ obfuscate original API
    // some logic here 
    fetch(req.body.url).then(r => {
      r.body.pipe(res);
    }).catch(err => {
      console.log(err);
      res.status(500).send("Invalid Url");
    })
}

It worked flawlessly. However, now the response.body returned by the fetch API no longer has the pipe method. Instead, it offers pipeTo and pipeThrough methods. Unfortunately, the Next.js res:NextApiResponse cannot be assigned to a WritableStream.

I attempted creating a blob (await r.blob()) and using res.send(blob) and res.send(blob.strem()). Initially, it seemed to work but the data received by the frontend turned out to be incorrect (Essentially,

fetch().then((res) => res.blob()).then((blob) => URL.createObjectURL(blob)))
resulted in corrupted data).

Answer №1

In the realm of web development, an experimental API called Readable.fromWeb() has emerged. This API has the ability to convert a fetch() call into a ReadableStream, transforming it into a nodejs stream seamlessly. As reported, this functionality appears to be operational in node version 18.14.0.

import { Readable } from 'node:stream';

export default async function (req, res) {
    // To ensure data security and privacy
    // Additional logic here 
    fetch(req.body.url).then(r => {
      Readable.fromWeb(r.body).pipe(res);
    }).catch(err => {
      console.log(err);
      res.status(500).send("Invalid Url");
    })
}

Answer №2

Here is a fantastic solution that worked wonders!

const https = require("https");

export default async function handler(req, res) {
   try {
      const url = `your-url`;
      res.status(200);
      https.get(url, (response) => {
        response.pipe(res);
        response.on("finish", res.end);
      });
    } catch (err) {
      console.log(err);
      res.status(500).send("Invalid Url");
    }
}

Update

The above method is effective in simple scenarios but fails when there are redirects.

Klesum recommends using the Readable API for better results.

import { Readable } from "node:stream";

export default async function (req, res) {
    fetch(req.body.url).then(r => {
      Readable.fromWeb(r.body).pipe(res);
    })
}

TypeScript may show warnings for this specific line, but you can simply ignore them with // @ts-ignore and everything will work smoothly.

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

Do you need assistance with downloading files and disconnecting from clients?

When looking at the code snippet below: async function (req, res, next) { const fd = await fs.open("myfile.txt") fs.createReadStream(null, { fd, autoClose: false }) .on('error', next) .on('end', () => fs.close(fd)) . ...

The React functional component captures a snapshot of its state when initializing a websocket event handler

When using a react functional component, it captures a snapshot of the state at the time of subscription. For example, refer to the code below. If I click the setSocketHandler button and then press the setWelcomeString button. If I receive a message over ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

"Master the art of using express and jade to loop through data and generate dynamic

Hey there! I have a question regarding node.js. When working with express, we typically have multiple files such as app.js, index.jade, index.js, and server.js where most of the server logic resides. Let's say we have two objects defined in server.js ...

Creating both Uniform and Varying drawings on a single webGL canvas

My goal is to create this specific illustration. https://i.sstatic.net/5AfdW.png This project requires the usage of TypeScript. The Code: The code is organized across multiple files. Within the scenegraph file, there's a function that visits a gro ...

React hook triggering re-render

A function has been implemented to retrieve and decode user claims from a token stored in local storage using a hook. export const useActiveUser = (): { user: IUserTokenClaims | null } => { const [user, setUser] = useState<IUserTokenClaims | nul ...

There is a possibility of encountering an endless update loop in the watcher when utilizing the expression "tabs" error in vue

My code includes a watcher on tabs to prevent them from changing based on the values of the edit. If edit is false, then go to the next tab; otherwise, prevent the change. However, when I try to click on the tab heading to change the tab, I encounter an er ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

The Owl carousel's autoplay feature seems to be set at a fixed speed of 5

I've been attempting to adjust the autoplay speed on an owl carousel (specifically using owl carousel 1), but no matter what integer I add after autoplay:, it remains stuck at 5 seconds. The website, which is currently broken, suggests that adding a n ...

Displaying a subset of categories based on the user's selection

I have been trying to find a solution to automatically display a subcategory select drop-down only when a user selects a category. If no category is selected, the subcategory drop-down should remain hidden. I have searched online tutorials and videos for ...

The function get_template_directory_uri() returned an unexpected string error

Exploring WP themes has been an interesting journey for me. Currently, I am working on creating a shortcode for some html/script and encountering an issue with enqueuing the js file. My initial query is about whether I am loading this from the correct loc ...

Capture a screenshot with Puppeteer at a random URL stop

I am facing an issue with my service nodejs running on Ubuntu, where I use puppeteer to capture screenshots of pages. However, the method page.screenshot({fullPage: true, type: 'jpeg'}) sometimes fails on random URLs without displaying any errors ...

The request body doesn't meet the interface requirements, but it does not trigger an error response

I created a specific interface called NewTransactionPayload to ensure that only objects of this type are accepted in the request body. Strangely, TypeScript does not show any errors when I host the application. Why is that? // Sample interfaces interface ...

Discover an Effective Approach for Transmitting Form-Data as a JSON Object

Hey there! I'm encountering a bit of an issue with sending some data as a JSON object. The problem arises when trying to send images using FormData. It seems like I need to convert my form data into a single JSON object. Can anyone assist me with this ...

Utilizing Firebase 3 with Ionic 2 and cordova-plugin-camera for seamless file uploading

I have been attempting to upload images to Firebase storage using the cordova-plugin-camera but have not been successful: Below is the code I have been using: let options:any = { quality : 100, destinationType : Camera.DestinationType.DATA_URL, ...

how can JavaScript be used to retrieve an object based on a condition from an array of objects and an ArrayList

My JavaScript challenge involves working with an array of objects called arrobj and a list called prgList. The goal is to extract the names from arrobj based on the programs listed in prgList. If the program exists in arrobj, it should be displayed accor ...

Combine a pair of select statements to utilize the RxJS store within an Angular Guard

When working on an Angular Guard, I encountered a challenge where I needed to select two fields from the ngrx store. Here is the code snippet for reference: @Injectable() export class RoleGuard implements CanActivate { constructor( public router: A ...

Using Javascript and JQuery to create an alert that pops up upon loading the page is not effective

I am having trouble making an alert show up when my website loads. The Javascript code is functional when directly included in the HTML, but once I move it to a separate file named script.js and link it, nothing happens. Can someone please help me identify ...

Tips on using the .map() method to extract data from a JSON response received from a get request and utilizing the content within a specific index to populate table rows

Here is the JSON response representation, https://i.stack.imgur.com/0QWkv.png This is how my project displays it: https://i.stack.imgur.com/LnA5v.png The rendering code snippet is as follows: render() { const { materials } = this.state; ...

Steps to display text in a div upon clicking on an image

I am trying to create an image with two DIVs separated by a black line. The left DIV will contain 4 images, and I want the following functionality: When a user clicks on any of the buttons in the left DIV, a corresponding text should be revealed in the ri ...