score:2
the calls to rendertostring()
are synchronous, so they are blocking the thread while they are running. so its no surprise that when you have 100+ concurrent requests that you have an extremely blocked up queue hanging for ~10 seconds.
edit: it was pointed out that react v16 natively supports streaming, but you need to use the rendertonodestream()
method for streaming the html to the client. it should return the exact same string as rendertostring()
but streams it instead, so you don't have to wait for the full html to be rendered before you start sending data to the client.
score:3
1. run express in a cluster
a single instance of node.js runs in a single thread. to take advantage of multi-core systems, the user will sometimes want to launch a cluster of node.js processes to handle the load.
as node is single threaded the problem may also be in a file lower down the stack were you are initialising express.
there are a number of best practices when running a node app that are not generally mentioned in react threads.
a simple solution to improve performance on a server running multiple cores is to use the built in node cluster module
https://nodejs.org/api/cluster.html
this will start multiple instance of your app on each core of your server giving you a significant performance improvement (if you have a multicore server) for concurrent requests
see for more information on express performance https://expressjs.com/en/advanced/best-practice-performance.html
you may also want to throttle you incoming connections as when the thread starts context switching response times drop rapidly this can be done by adding something like nginx / ha proxy in front of your application
2. wait for the store to be hydrated before calling render to string
you don't want to have to render you layout until your store has finished updating as other comments note this is a blocks the thread while rendering.
below is the example taken from the saga repo which shows how to run the sagas with out the need to render the template until they have all resolved
store.runsaga(rootsaga).done.then(() => {
console.log('sagas complete')
res.status(200).send(
layout(
rendertostring(rootcomp),
json.stringify(store.getstate())
)
)
}).catch((e) => {
console.log(e.message)
res.status(500).send(e.message)
})
https://github.com/redux-saga/redux-saga/blob/master/examples/real-world/server.js
3. make sure node environment is set correctly
also ensure you are correctly using node_env=production
when bundling / running your code as both express and react optimise for this
score:3
in the above image, i am doing reactdom.hydrate(...) i can also load my initial and required state and send it down in hydrate.
i have written the middleware file and i am using this file to decide based on what url i should send which file in response.
above is my middleware file, i have created the html string of the whichever file was requested based on url. then i add this html string and return it using res.render of express.
above image is where i compare the requested url path with the dictionary of path-file associations. once it is found (i.e. url matches) i use reactdomserver render to string to convert it into html. this html can be used to send with handle bar file using res.render as discussed above.
this way i have managed to do ssr on my most web apps built using mern.io stack.
hope my answer helped you and please write comment for discussions
Source: stackoverflow.com
Related Query
- React app with Server-side rendering crashes with load
- How to deploy React App on production with Server Side Rendering
- React Server Side Rendering with Sass
- React Context not working with server side rendering
- How we can convert client side rendering react js app to server side rendering using react router 4?
- React Router v5 accompanied with Code Splitting, and Data Prefetching with the use of Server Side Rendering
- React facebook share not working on open graph meta tags with server side rendering
- React code splitting and server side rendering with System.import or require.ensure
- React JS server side rendering with python
- Failed to load resource: the server responded with a status of 500. Deployed react app with vercel
- How to do Server Side Rendering in React With React Loadable and Fetching Data for Components (Like Next.js)?
- React Server side rendering with Express - warning on the client checksum & Styling
- react server side rendering with client side routing
- React Server Side Rendering with expensive initial API call
- how to properly deal with window=undefined error in react server side rendering
- Server Side Rendering with React Router Dom getting error: Warning: React.createElement: type is invalid -- expected a string
- React Server Side Rendering App - how to update meta data
- How to implement error boundary in react with server side rendering in nextjs?
- Server rendering React app behind a URL prefix with react-router
- React Query with server side rendering using Next.js
- Window is not defined with Server Side Rendering React and Express
- Empty cache after server side rendering a request in isomorphic app using Apollo GraphQL and React
- Express server with React front end routing without server side rendering
- Include a third party script in a functional component of react with server side rendering
- How to setup multistage builds for a ReactJS App with server side rendering
- Faced Failed to load resource: the server responded with a status of 404 () when uploaded my react app to github pages
- Server side rendering with Webpack Express and React
- React server side rendering with backend requests
- Using momentjs with correct locale in React server side rendering
- passing down props with React server side rendering
More Query from same tag
- How to pass State in Context React
- Spying on React components using Enzyme (and sinon?) to check arguments
- How can I loop through the zone id and pass each zoneId to uosId to make an API request each
- Set react slick autoplayspeed dynamically without setState
- TypeScript error passing prop to styled-components
- React - Link redirect to item but not refresh the component
- How to verify my domain with Apple in a React App
- With React, clicking on a label is not changing the input type checkbox checked value. Why?
- How to process JSON fields with lodash map/countBy/groupBy?
- why i am getting this error on using Link tag from next/link? Error: React.Children.only expected to receive a single React element child
- React : Cannot set property 'animation' of undefined
- Navigate using react-router-dom v6 after performing user action
- Designinig SASS I want Box layout but not able to get it
- How to call a function method in a component class render method? getting Uncaught TypeError: Cannot read property 'value' of null in React
- Trouble-shooting a basic test with React and Jest
- How to change background color of active Navigation Tab?
- JavaScript function syntax? export default ({...}) => (<View .... >)
- React click on item to show details
- use every and filter function together in JavaScript
- Using data passed from parent to child classes for adding points on globe
- Jest unit test with Luxon: how do I mock .setZone('local')
- How to toggle a button in React list?
- Using class member not state
- How to test in JEST a request that downloads a file
- React router - page does not render until I do a browser refresh
- How do I style a Material UI 1.x FormLabelControl's label?
- React How to add new dynamic key to existing state?
- Redux connect with Relay
- Passing props to UseEffect hook from Parent component
- How to add linking images to ckeditor in React?