A szerveroldali renderelés megvalósítása a React alkalmazásban három egyszerű lépésben

Írta: Rohit Kumar

Íme, amit felépítünk ebben az oktatóanyagban: egy ilyen szép React kártya.

Ebben az oktatóanyagban a kiszolgálóoldali megjelenítést használjuk HTML-válasz leadására, amikor a felhasználó vagy a robot beüt egy oldal URL-jére. Ez utóbbi kéréseket az ügyfél oldalon kezeljük.

Miért van szükségünk rá?

Hadd vezesselek a válaszra.

Mi a különbség az ügyféloldali és a szerveroldali megjelenítés között?

Az ügyféloldali megjelenítésnél a böngésző minimális HTML-oldalt tölt le. Megjeleníti a JavaScript-et és kitölti a tartalmat.

A kiszolgálóoldali megjelenítés viszont a szerver React összetevőit rendereli. A kimenet HTML tartalom.

Ezt a kettőt kombinálva létrehozhat egy izomorf alkalmazást.

A React a szerveren történő visszaadásának hátrányai

  • Az SSR javíthatja a teljesítményt, ha kicsi az alkalmazás. De ronthatja a teljesítményt is, ha nehéz.
  • Növeli a válaszidőt (és rosszabb is lehet, ha a szerver foglalt).
  • Növeli a válasz méretét, ami azt jelenti, hogy az oldal betöltése hosszabb ideig tart.
  • Növeli az alkalmazás bonyolultságát.

Mikor érdemes használni a szerveroldali renderelést?

Az SSR ezen következményei ellenére vannak olyan helyzetek, amelyekben használhatja és használja is.

1. SEO

Minden webhely meg akar jelenni a keresésekben. Javíts ki, ha tévedek.

Sajnos a keresőmotorok robotjai még nem értik / teszik lehetővé a JavaScript használatát.

Ez azt jelenti, hogy egy üres oldalt látnak, bármennyire is hasznos a webhelye.

Sokan azt mondják, hogy a Google robotja most JavaScript-t jelenít meg.

Ennek tesztelésére telepítettem az alkalmazást a Heroku-ra. Ezt láttam a Google Search Console-on:

Egy üres oldal.

Ez volt a legnagyobb oka annak, hogy a szerveroldali renderelést kutattam. Különösen akkor, ha ez egy sarokoldal, például céloldal, blog stb.

Annak ellenőrzéséhez, hogy a Google rendereli-e webhelyét, látogasson el ide:

Search Console irányítópult> Feltérképezés> Megtekintés Google-ként. Írja be az oldal URL-jét, vagy hagyja üresen a kezdőlap számára.

Válassza a FETCH AND RENDER lehetőséget. Ha elkészült, kattintson az eredmény megtekintéséhez.

2. Javítsa a teljesítményt

Az SSR-ben az alkalmazás teljesítménye a kiszolgáló erőforrásaitól és a felhasználó hálózati sebességétől függ. Ez nagyon hasznos a tartalmas webhelyek számára.

Például mondjuk, hogy közepes árú, lassú internet-sebességű mobiltelefonja van. Megpróbál elérni egy webhelyet, amely 4 MB adatot tölt le, mielőtt bármit is látna.

Láthatna bármit a képernyőn 2–4 másodpercen belül?

Meglátogatná még egyszer azt a webhelyet?

Nem hinném, hogy megtennéd.

Egy másik jelentős javulás az első felhasználói interakció ideje. Ez az időbeli különbség attól kezdve, amikor a felhasználó eléri az URL-t, és amikor tartalmat lát.

Itt van az összehasonlítás. Teszteltem egy fejlesztő Mac-en.

A React a szerveren jelenik meg

Az első interakciós idő 300 ms. A hidratálás 400 ms-on fejeződik be. A terhelési esemény kb. 500 ms-nál lép ki. Ezt a fenti kép megtekintésével láthatja.

A React megjelenik az ügyfél böngészőjén

Az első interakciós idő 400 ms. A terhelési esemény 470 ms-nál lép ki.

Az eredmény önmagáért beszél. 100 ms különbség van az első felhasználói interakciós idő alatt egy ilyen kicsi alkalmazás esetében.

Hogyan működik? - (4 egyszerű lépés)

  • Hozzon létre egy új Redux Store-t minden kérésre.
  • Opcionálisan küldjön néhány műveletet.
  • Hozza ki az állapotot a Store-ból, és hajtsa végre az SSR-t.
  • Küldje el az előző lépésben kapott állapotot a válasszal együtt.

We will use the state passed in the response for creating the initial state on client-side.

Before you get started, clone/download the complete example from Github and use it for reference.

Getting Started by Setting up our App

First, open your favourite editor and shell. Create a new folder for your application. Let’s start.

npm init --yes

Fill in the details. After package.json is created, copy the dependencies and scripts below into it.

Install all dependencies by running:

npm install

You need to configure Babel and webpack for our build script to work.

Babel transforms ESM and react into Node and browser-understood code.

Create a new file .babelrc and put the line below in it.

{ "presets": ["@babel/env", "@babel/react"] } 

webpack bundles our app and its dependencies into a single file. Create another file webpack.config.js with the following code in it:

const path = require('path');module.exports = { entry: { client: './src/client.js', bundle: './src/bundle.js' }, output: { path: path.resolve(__dirname, 'assets'), filename: "[name].js" }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" } ] } }

The build process output’s two files:

  1. assets/bundle.js — pure client side app.
  2. assets/client.js — client side companion for SSR.

The src/ folder contains the source code. The Babel compiled files go into views/. views directory will be created automatically if not present.

Why do we need to compile source files?

The reason is the syntax difference between ESM & CommonJS. While writing React and Redux, we heavily use import and export in all files.

Unfortunately, they don’t work in Node. Here comes Babel to rescue. The script below tells Babel to compile all files in the src directory and put the result in views.

"babel": "babel src -d views",

Now, Node can run them.

Copy Precoded & Static files

If you have already cloned the repository, copy from it. Otherwise download ssr-static.zip file from Dropbox. Extract it and keep these three folders inside your app directory. Here’s what they contain.

  1. React App and components resides in src/components.
  2. Redux files in src/redux/.
  3. assets/ & media/: Contain static files such as style.css and images.

Server Side

Create two new files named server.js and template.js inside the src/ folder.

1. src/server.js

Magic happens here. This is the code you’ve been searching for.

import React from 'react'; import { renderToString } from 'react-dom/server'; import { Provider } from 'react-redux'; import configureStore from './redux/configureStore'; import App from './components/app'; module.exports = function render(initialState) { // Model the initial state const store = configureStore(initialState); let content = renderToString(); const preloadedState = store.getState(); return { content, preloadedState }; };

Instead of rendering our app, we need to wrap it into a function and export it. The function accepts the initial state of the application.

Here’s how it works.

  1. Pass initialState to configureStore(). configureStore()returns a new Store instance. Hold it inside the store variable.
  2. Call renderToString() method, providing our App as input. It renders our app on the server and returns the HTML produced. Now, the variable content stores the HTML.
  3. Get the state out of Redux Store by calling getState() on store. Keep it in a variable preloadedState.
  4. Return the content and preloadedState. We will pass these to our template to get the final HTML page.

2. src/template.js

template.js exports a function. It takes title, state and content as input. It injects them into the template and returns the final HTML document.

To pass along the state, the template attaches state to window.__STATE__ inside a pt> tag.

Now you can read state on the client side by accessing window.__STATE__.

We also include the SSR companion assets/client.js client-side application in another script tag.

If you request the pure client version, it only puts assets/bundle.js inside the script tag.

The Client Side

The client side is pretty straightforward.

1. src/bundle.js

This is how you write the React and Redux Provider wrap. It is our pure client-side app. No tricks here.

import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from './redux/configureStore'; import App from './components/app'; const store = configureStore(); render(   , document.querySelector('#app') );

2. src/client.js

Looks familiar? Yeah, there is nothing special except window.__STATE__. All we need to do is grab the initial state from window.__STATE__ and pass it to our configureStore() function as the initial state.

Let’s take a look at our new client file:

import React from 'react'; import { hydrate } from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from './redux/configureStore'; import App from './components/app'; const state = window.__STATE__; delete window.__STATE__; const store = configureStore(state); hydrate(   , document.querySelector('#app') );

Let’s review the changes:

  1. Replace render() with hydrate(). hydrate() is the same as render() but is used to hydrate elements rendered by ReactDOMServer. It ensures that the content is the same on the server and the client.
  2. Read the state from the global window object window.__STATE__. Store it in a variable and delete the window.__STATE__.
  3. Create a fresh store with state as initialState.

All done here.

Putting it all together

Index.js

This is the entry point of our application. It handles requests and templating.

It also declares an initialState variable. I have modelled it with data in the assets/data.json file. We will pass it to our ssr() function.

Note: While referencing a file that is inside src/ from a file outside src/ , use normal require() and replace src/ by views/. You know the reason (Babel compile).

Routing

  1. /: By default server-rendered homepage.
  2. /client: Pure client-side rendering example.
  3. /exit: Server stop button. Only available in development.

Build & Run

It’s time to build and run our application. We can do this with a single line of code.

npm run build && npm run start

Now, the application is running at //localhost:3000.

Ready to become a React Pro?

I am starting a new series from next Monday to get your React skills blazing, immediately.

Original text


Thank you for reading this.

If you like it and find it useful, follow me on Twitter & Webflow.