You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
8 Hrs
31 Min
49 Seg

Hidratando la aplicaci贸n y separando el bundle del cliente

11/17
Resources

How to complete the server-side rendering process?

We are getting closer and closer to complete the server-side rendering process in our React application. This process involves several steps, from generating the template to sending the first DOM tree in plain text format. The last step is to hydrate our React application with JavaScript and some additional client-side configuration. The goal is to get our application working properly on both the server and the client.

How to configure the client build?

To configure the client build, we start by modifying the package.json file. A script is added that uses the Webpack configuration we had previously used. Here it is important to remove the Webpack plugin that generates HTML, as the HTML will now be sent directly from the server. The new build script will be named 'client', and it is crucial to ensure that this configuration is generated correctly by clearing the dist folder and running the build to verify the results.

{ " scripts": { " build:client": "webpack --config webpack.client.config.js" }}

How to create a general build script?

The creation of a general build script is essential for the correct functioning of our application, since it allows us to build both the client and the server. To do this, we configure the node environment to production and ensure that the script is able to perform separate builds for each part of the application.

{ " scripts": { " build": "NODE_ENV=production npm run build:client && npm run build:server" }} }

How to expose JavaScript from the server?

To expose the generated JavaScript from the server, we use an Express middleware called static, which allows to serve static files to the client. This configuration is done on the dist folder where the client build was generated.

app.use(express.static(path.join(__dirname, 'dist')));

Additionally, it is necessary to modify the template.tsx to include a <script> tag that refers to the client's JavaScript file. This file is loaded at the precise moment to allow the correct hydration of the elements.

<script src="/app.js" type="text/javascript"></script>

How to avoid double rendering in React?

During the hydration process it is common to face a double render of our application. To solve this drawback, it is crucial to adjust the generated HTML and store it directly inside the div with id="app", which is where React inserts the application.

In the index.tsx file, the createRoot method is replaced by hydrateRoot to take advantage of the already existing structure of the element tree, which avoids duplication of content during JavaScript execution.

import { hydrateRoot } from 'react-dom/client';
hydrateRoot(document.getElementById('app'), <App/>);

How to check the server-side rendering performance?

To check that server-side rendering is working properly, just disable JavaScript in the browser and reload the application. If the content is still visible, it means that server-side rendering is successfully implemented. By reactivating JavaScript, the application should hydrate and run smoothly. In addition, it is possible to verify in the "sources" tab that the server is sending the app.js file.

This process ensures that our React application behaves properly, running in both client-side and server-side rendering mode. In addition, other optimizations and enhancement techniques such as prefetching will be explored in the next stages, which will increase the efficiency of the server and the end-user experience. Go ahead and continue exploring the fascinating world of server-side rendering in React!

Contributions 6

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

Es interesante ver c贸mo hasta al mismo profesor comete errores que cualquiera como programador podr铆a tener, como olvidar poner un simple NODE_ENV=production en una l铆nea de c贸digo.
Lo importante es, que lo resuelve junto con nosotros para que nos demos cuenta que todos podemos equivocarnos y todo tiene soluci贸n馃榾

Segunda vez que tomo este curso, y no deja de encantarme y sorprenderme.

![](https://static.platzi.com/media/user_upload/image-08f3f70d-7dcb-41ed-bc9c-e48f03058652.jpg)![](https://static.platzi.com/media/user_upload/image-19198fab-ab32-4b0c-986d-f96c14cd21be.jpg)Agregamos a nuestro scripts: build cross-env codigo:"build": "cross-env NODE\_ENV=production npm run build-client && npm run build-server" instalamos la dependencia : ![](https://static.platzi.com/media/user_upload/image-8457108f-dd5b-41e3-ad6a-86f98f60a279.jpg) Por si surge alg煤n error cuando queramos hacer yarn build
cuando agrego ```app.use(express.static('dist')) ```deja de retornar en html base , y si desactivo javascript no se visualiza nada , probe directamente en la rama hydratation-process , reinstalando node\_modules y aun asi observo el mismo conportamiento al agregar ```app.use(express.static('dist')) ``` ```聽 const stream = renderToString(聽 聽 \<StaticRouter location={url}>聽 聽 聽 \<App />聽 聽 \</StaticRouter>聽 )``` retorna un string vacio
Hay alguna diferencia entre retornar un string y un archivo HTML desde un endpoint del servidor? Entiendo que ambos son texto plano, pero se me gener贸 esa duda.

Que curso m谩s espectacular, esto amplia als posibilidades de usar el server de nackend que querramos como express y fastify de js, flask y fastAPI con py.