React 18, the latest iteration of the popular JavaScript library to build interactive UIs is loaded with a treasure of new features and improvements. Its most prominent feature is its improved support for Server Side Rendering (SSR).
Create a server folder in the root of the project with two files, index.js and server.js.
server/index.js
require("ignore-styles");
require("@babel/register")({
ignore: [/(node_modules)/],
presets: ["@babel/preset-env", "@babel/preset-react"],
});
require("./server");
This line of code starts Babel to compile code, ignores specific files such as files in "node_modules", and starts the server by importing the "server" module. This setup is mostly applied in React server side rendering to enable the server to process and send React components to clients.
server/server.js
import express from "express";
import React from "react";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import App from "./src/App";
const app = express();
app.get("*", (req, res) => {
const { pipe, abort } = ReactDOMServer.renderToPipeableStream(
<StaticRouter location={req.url}>
<App />
</StaticRouter>
);
{
bootstrapScripts: entryPoint,
onShellReady() {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
pipe(res);
},
onShellError() {
res.statusCode = 500;
res.send("<doctype html><p>Loading...</p>");
},
}
});
app.listen(3002, () => {
console.log("App is running on http://localhost:3002");
});
The code assigns a route handler to all routes by app.get("/*", ...). It suggests that this route handler will handle any request to the server. Inside the route handle:
Include a script to run the SSR server.
{
"scripts": {
"ssr": "npm run build && node server/index.js"
}
}
Hit the following command to start the SSR server:
npm run ssr
With Server APIs in React 18, you can render React components on the server as streams efficiently, optimizing for page loads and SEO.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.