Create a pipeable stream that does not trigger any events when data is piped

I have been trying to utilize the renderToPipeableStream function from React18, and although it is functional, I am struggling with handling the pipe properly.

The key section of my code involves an array of strings representing HTML. I am splitting the string in the middle to insert the React code where desired.

server.get("/", (req: any, res: any) => {  
    res.write(html[0] + '<div id="root">')
    const stream = ReactDomServer.renderToPipeableStream(
        <App />
    ).pipe(res, { end: false })
    stream.on("end", () => {
        res.write('</dev>' + html[1])
        res.end()
    })
})

The issue arises when stream.on("end" fails to trigger. This poses a problem as the HTML code remains incomplete without it. While browsers may overlook this, it is not ideal.

Answer №1

Here is a solution that worked well for me:

  I found success using the following code snippet:
  
  const stream = renderToPipeableStream(jsx, {
    onAllReady() {
      res.end(`</div></body></html>`);
    },
  });

  stream.pipe(res, { end: false });
  res.flush();

Check out this link for more information on react-dom-server!

Answer №2

I managed to solve the problem by using the code below:

  const app = renderToPipeableStream(<App />);

  res.type('html');

  res.write(getDocumentHead(req, res)); //A unique method for creating header html

  app.pipe(res, {end: false});

  res.write(getDocumentEnd(req, res)); //A special function to generate scripts

  res.end();

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

Attention: NextJS/React + Django Rest Framework encountered a non-boolean attribute `crossOrigin` with a value of `true`

I've been encountering this warning message but I'm unsure of its source or how to resolve it. It seemingly appeared out of nowhere as I revisited earlier commits where the warning was not present during my initial work on them. My suspicion is t ...

Working with arrays in Angular 4 to include new items

I am struggling with the code below: export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() { } ngOnInit() { } onEmpCreate(){ conso ...

Angular route unable to detect Passport User Session

The navigation bar in the header features buttons for Register, Login, and Become a Seller. Upon user login, it displays logout and view profile buttons. This functionality is operational on all routes except one, causing a client-side error. user not def ...

"Enhancing Code Functionality in React - Seeking Ways to Improve

When working with Redux, I often find myself repeatedly using the same piece of code: const dispatch = useDispatch() Then, every time I need to call a function, I do something like this: dispatch(endpointError(true)) My goal is to streamline this proce ...

Dynamic Schema Updates with Apollo Server for GraphQL

Seeking advice on implementing hot reloading for the GraphQL schema on my apollo-server-express server. Does anyone have experience with this or know how to accomplish it? Currently, I am using schema stitching to combine schemas from multiple APIs, but I ...

Roll out a custom-built server for an Angular 7, MongoDB, Express, and Node application

I am seeking to host my Angular application with Node.js, MongoDB, and Express.js on a server of my own. My current deployment method involves: -> ng build --prod (generates output in the dist folder) -> ng serve from the dist directory To start the back ...

How can I dynamically adjust the font size of content in a React Material-UI Button when it's unexpectedly

In my web application project, I have created multiple choice questions where each answer is displayed within a single button: <Button fullWidth={true} variant="contained" onClick={(answer) => this.handleAnswer(this.state.answers[0].tex ...

Proceed to the Paypal express checkout page to finalize your purchase using a credit card

It appears that Paypal has recently introduced a new interface for its users. Unfortunately, using SOLUTIONTYPE=Sole and LANDINGPAGE=Billing no longer functions correctly in this updated environment. We have attempted to reach out to Paypal multiple times ...

Verify if a certain value is present within a nested array

I need assistance with checking if a specific value is present within a nested array. Here is an example of the data I am dealing with: [ { name: 'alice', occupation: ['Artist', 'Musician'], }, { ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...

Converting a string into an array of JSON objects

I am currently attempting to send data to my NodeJS server using the HTTP protocol (vue-resource). The goal is to send an array of JSON objects structured like this : [{"name":"Charlotte","surname":"Chacha","birth":"2000-04-02"},{"name":"Michael","surname ...

Starting a React app within a Laravel project can be a seamless process when following

I am facing an issue with my Laravel and React project setup. When I try to run npm start, I encounter the error "npm ERR! missing script: start". The project runs successfully when I use the command npm run dev. Is there a way to only run the React projec ...

What could be causing the "Error: Unable to set headers after they have been sent" message, even though I have already sent a status code?

Take a look at my code snippet: app.post('/register', function(req, res){ var user = new User(req.body); if (req.body.password.length <= 5){ res.status(400).send('error: password should be longer'); } if (req.body.username.len ...

Searching for a string in an array using the $in operator in M

I have a custom model defined as follows: var MessageSchema = new Schema({ msgID: String, patientList: [String], created_at: Date, updated_at: Date }); The patientList is always dynamic in nature. I am attempting to construct a Mongoose ...

Tips for utilizing an array within React and transforming it into a component

I've developed a website that pulls data from a SQL database I created, containing details such as name, address, and occupation of individuals. I successfully managed to showcase this information on the webpage by structuring an array and inserting t ...

What is the best approach to implement a recursive intersection while keeping refactoring in consideration?

I'm currently in the process of refactoring this code snippet to allow for the reuse of the same middleware logic on multiple pages in a type-safe manner. However, I am encountering difficulties when trying to write a typesafe recursive type that can ...

Enhancing nested structures in reducers

Currently, I am utilizing react, typescript, and redux to develop a basic application that helps me manage my ingredients. However, I am facing difficulties with my code implementation. Below is an excerpt of my code: In the file types.ts, I have declared ...

Looking for guidance on sending data from a JS file to HTML using Nodejs? Seeking advice on various modules to achieve this task effectively? Let's

Looking for advice on the most effective method to transfer data from a JS file (retrieved from an sqlite db) to an HTML file in order to showcase it in a searchable table. My platform of choice is NodeJS. As a beginner, I am willing to put in extra time a ...

Exploring ways to cycle through a select dropdown in React by utilizing properties sent from the Parent Component

I'm having trouble displaying the props from a parent component in a modal, specifically in a select dropdown. How can I make it so that the dropdown dynamically shows the values from the props instead of the hardcoded 'Agent' value? What am ...

Is it feasible to manage middleware using a function as a handler?

i am facing some confusion, let me begin by showing the code within app.js app.oauth=require('./serverice/login') // this is 1 middleware app.islogin=require('./middleware/islogin')(app) // this is 2 middleware app.get('/next ...