⚡️ Static Router, Static Assets, Serving A Server-side Rendered Site

Featured image from photo by Greg Jeanneau on Unsplash

This is part 7 of my series on server-side rendering (SSR):

  1. 🤷🏻‍♂️ What is server-side rendering (SSR)?
  2. ✨ Creating A React App
  3. 🎨 Architecting a privacy-aware render server
  4. 🏗 Creating An Express Server
  5. 🖥 Our first server-side render
  6. 🖍 Combining React Client and Render Server for SSR
  7. [You are here] ⚡️ Static Router, Static Assets, Serving A Server-side Rendered Site
  8. 💧 Hydration and Server-side Rendering
  9. 🦟 Debugging and fixing hydration issues
  10. 🛑 React Hydration Error Indicator
  11. 🧑🏾‍🎨 Render Gateway: A Multi-use Render Server

Last time, we worked to combine the client website implementation and the server rendering architecture into a single solution. Unfortunately, where we ended up was a failing app. This week we are going to jump straight in where we left off with the goal of finally server-side rendering our website. I'll let you in on a little secret; we hit that goal this week1!

🗺 StaticRouter

At the end of our attempts to integrate our website with the server, we got this error:

Error: Invariant failed: Browser history needs a DOM

To fix this, our first instinct might be to provide a DOM using perhaps JSDOM. However, this additional dependency is not the right way to resolve this error. Instead, we can look to React Router. It turns out that besides the BrowserRouter, React Router provides other router implementations such as HashRouter, MemoryRouter, and StaticRouter. There are different scenarios where these different routers come into play – for example, the MemoryRouter is really useful for testing, including storyboard style tests where one might want to verify that navigation would happen without actually having it happen. In the case of server-side rendering, it is the StaticRouter component that is there to help us. StaticRouter is pretty much what it says. It provides all the things React Router's infrastructure needs to render routes but with none of the navigation support. We tell it the location we are at and it ensures that is the route we render.

To get StaticRouter into our app we have now come to the point where our client-side website implementation can no longer be oblivious to our server-side rendering implementation. As we shall find during our SSR adventures, this will not be the only time our client app must consider its server-side rendering, but we can make it as seamless as possible. To start, let's modify our root App component so that we can control whether it renders a BrowserRouter or a StaticRouter.

import React from 'react';
import {BrowserRouter, StaticRouter} from "react-router-dom";

export default function Router(props) {
    const {ssrLocation, children} = props;

    if (ssrLocation == null) {
        return <BrowserRouter>{children}</BrowserRouter>;
    }

    return <StaticRouter location={ssrLocation}>{children}</StaticRouter>;
}
import React from 'react';
import {Link, Route, Switch} from "react-router-dom";
import Router from "./Router.js";
import logo from './logo.svg';
import './App.css';

function App(props) {
  const {ssrLocation} = props;
  return (
    <Router ssrLocation={ssrLocation}>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <div className="App-links">
            <Link className="App-link" to="/">Home</Link>
            <Link className="App-link" to="/about">About</Link>
            <Link className="App-link" to="/contact">Contact</Link>
          </div>
        </header>
        <section className="App-content">
          <Switch>
            <Route path="/about">
              This is the about page!
            </Route>
            <Route path="/contact">
              This is the contact page!
            </Route>
            <Route path="/">
              This is the home page!
            </Route>
          </Switch>
        </section>
      </div>
    </Router>
  );
}

export default App;
require("./require-patches.js");
const express = require("express");
const React = require("react");
const {renderToString} = require("react-dom/server");
const {getPageTemplate} = require("./get-page-template.js");
const App = require("../client/src/App.js").default;

const port = 3000;
const app = express();

const pageTemplate = getPageTemplate();

const renderPage = (reactComponent) => {
    const renderedComponent = renderToString(reactComponent);
    return pageTemplate.replace('<div id="root"></div>', `<div id="root">${renderedComponent}</div>`);
};

app.get("/*", (req, res) => res.send(
    renderPage(<App ssrLocation={req.url}  />),
));

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

The first thing I did was to create a new component in our client app called Router. This component encapsulates the choice between using BrowserRouter or StaticRouter. It takes two props: children and ssrLocation. The first, children is what the component will render as its children (this is a React idiom – to use the prop children for any child components that a component will render). The second, ssrLocation is the URL that will be used with the StaticRouter when server-side rendering. If ssrLocation is not specified, we assume we are client-side and use BrowserRouter; if ssrLocation is specified, we assume we are server-side and use ServerRouter.

Second, I updated our App component to use this new Router component and to allow for the provision of an ssrLocation prop. I have highlighted the more important lines of that change.

With the client-side app now smart enough to handle the two worlds, we need the server to provide the ssrLocation prop. This change is highlighted in the server/index.js.

If we run the server with yarn start and visit localhost:3000 to see if it worked.

Screenshot from browser showing the URL of localhost:3000, and a page with an image placeholder called "logo", three links without padding nor margins labelled "Home", "About", and "Contact", and the text "This is the home page!"

Success-ish! We can even visit a different route like localhost:3000/about and see that it renders the about page. Brilliant, even though there is no nice spinning SVG and no styles, we rendered our app without an obvious error. Still, where is that logo and where are out styles? If we look at the server's console we see a couple of errors indicating that some files were requested but we failed to return them because we failed to decode the URL. Are these errors a clue to our missing CSS?

yarn run v1.21.1
$ NODE_ENV=development babel-watch index.js
Example app listening on port 3000!
URIError: Failed to decode param '%PUBLIC_URL%/manifest.json'
    at decodeURIComponent (<anonymous>)
    at decode_param (/hello-react-world/server/node_modules/express/lib/router/layer.js:172:12)
    at Layer.match (/hello-react-world/server/node_modules/express/lib/router/layer.js:148:15)
    at matchLayer (/hello-react-world/server/node_modules/express/lib/router/index.js:574:18)
    at next (/hello-react-world/server/node_modules/express/lib/router/index.js:220:15)
    at expressInit (/hello-react-world/server/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (/hello-react-world/server/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/hello-react-world/server/node_modules/express/lib/router/index.js:317:13)
    at /hello-react-world/server/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/hello-react-world/server/node_modules/express/lib/router/index.js:335:12)
URIError: Failed to decode param '%PUBLIC_URL%/favicon.ico'
    at decodeURIComponent (<anonymous>)
    at decode_param (/hello-react-world/server/node_modules/express/lib/router/layer.js:172:12)
    at Layer.match (/hello-react-world/server/node_modules/express/lib/router/layer.js:148:15)
    at matchLayer (/hello-react-world/server/node_modules/express/lib/router/index.js:574:18)
    at next (/hello-react-world/server/node_modules/express/lib/router/index.js:220:15)
    at expressInit (/hello-react-world/server/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (/hello-react-world/server/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/hello-react-world/server/node_modules/express/lib/router/index.js:317:13)
    at /hello-react-world/server/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/hello-react-world/server/node_modules/express/lib/router/index.js:335:12)

If we run the server in production mode with yarn start:prod and revisit localhost:3000, we see the same HTML rendered with no logo nor CSS and this time, there are no server console errors. However, if we look in the browser console, we see some curious errors:

2.dbb51963.chunk.js:1 Uncaught SyntaxError: Unexpected token '<'
main.448e42f3.chunk.js:1 Uncaught SyntaxError: Unexpected token '<'
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.

If we select the Network tab and refresh, then click on the response for one of these files, we can see exactly what is happening to cause the console errors, and see a clue as to why our logo is missing.

Our server is responding to every request as if it were the request for a page, when we really want it to return the files that were requested. In addition, we can see that instead of being written with tags, the SVG has been written out with HTML entities. These are two different problems. Let's fix the SVG one first.

🎩 Repetitive Magic

If you recall, last time around we taught NodeJS how to import SVG and CSS files with custom import extensions that looked like this:

const fs = require("fs");
const requireText = function (module, filename) {
    module.exports = fs.readFileSync(filename, 'utf8');
};
require.extensions[".svg"] = requireText
require.extensions[".css"] = requireText;

This is then used in our App component as follows (I have pared this down to just the import and usage for clarity):

import logo from './logo.svg';

<img src={logo} className="App-logo" alt="logo" />

That is not right. Of course our logo is not showing up because we're producing a nonsense source string. To see why our client app does not have this issue, let's run it in dev mode and see how that img tag gets rendered.

<img src="/static/media/logo.5d5d9eef.svg" class="App-logo" alt="logo">

That is weird. That file path does not even exist. It turns out webpack is doing some magic work for us to ensure that the import of the SVG file becomes an actual URL to the static file on disk rather than some nonsense inline pseudo-HTML like we have from our server. So, what do we do?

Well, we could do a few things:

  1. Work on mimicking this behavior, continuing down our path of trying to import the client code inside of our server app, providing our own magic for dealing with SVG files.
  2. Change the build process for the client-side app so that the server can use the built version of the JavaScript and benefit from webpack's magic.
  3. Something else entirely.

The advantage to option 1 is that it would be an interesting problem to solve. We could change our custom import stuff to track what SVG gets imported and then work out some way of ensuring that its reference in the React causes the URL to appear instead of the content (perhaps by using a property accessor). The disadvantage is that this feels like work we should not need to do; like we're fighting against the current. There are already tools doing this magic work; why do we need to reimplement that magic? Why can we not just reuse it as it is?

With option 2, it means starting to unpack all the things that the create-react-app tool set up for us, taking control of the webpack bundling configuration and all that good stuff, so that we can import the production builds of files. Even if we managed it, it would not work for development, since our render server is not requesting files from the webpack dev server. In addition, it seems like the problem is now dictating odd parts of our solution; why should the client build be optimized only for server use when it also has to work in the client, which may have different concerns? There has to be a better way and there is. However, before we discover that better way, our option 3 – something else, we should first consider the other problem; our render server is trying to render file requests as web pages. What we need is for our server to serve the files themselves instead.

📤 Serving Files

To be clear, in a real world situation, we may well use a CDN to orchestrate some of this work. Based on its rules, it would either server files and cached renders, or request a new render from our render server, and our render server would obtain any files it needs either from the CDN or from a local folder that replicates those files. However, we want to learn more and so let's assume for now that we don't have a CDN and our render server is going to be the server browsers talk to first. Therefore, it's going to need to know how to serve the different types of requests; files, pages, etc.

This is a solved problem, so it should be pretty easy to get working. Part of the issue is that our handler currently assumes everything is a request for HTML. Instead, it should probably be looking at the Accept header in the request to determine what is needed and then act accordingly. However, we must consider both our final production behavior where files will be served from a static folder, and our development behavior where we are going to want to get those files from webpack's dev server so that we can benefit from its development time bundling and static file generation.

Production

Since development is going to be a little harder, let's work on production first, since that is not just easier, it's a lot easier. Thanks to the built-in static middleware that Express provides, we can specify our build folder as the source of static files and express does the rest.

if (process.env.NODE_ENV === "production") {
    app.use(express.static("../client/build"));
}

app.get("/*", (req, res) => res.send(
    renderPage(<App ssrLocation={req.url} />),
));

Before our route handler, we add a check for production, and if it passes, we add the middleware for the /static route. If we refresh our production server, amazingly, everything appears to work2!

Development

If only development was as easy. I mean it could be, we could just defer all our calls to the client webpack dev server and we would have a working site, but we would not be testing out any actual server-side rendering. Instead, we need to proxy everything to the webpack dev server first, including the web pages. Why the web pages too? Well, if you may recall earlier in this post, our early attempts had two server-side errors where we failed to interpret URLs. This was because the index.html template for development requires some string substitution that webpack handles for us. If our render server loads that template via webpack, not only will it give us the right substitutions, but it is going to embed the CSS and scripts for us too. Of course, since we also want to stick in some rendered HTML, we will need intercept those specific requests and add our own bits.

Before we can do any of that, we need to know the address of the client server. As it happens, it is currently the same as our render server; localhost:3000. That's a bit of a problem, so let's move our render server to 3001 while we're at it. That way, both the client development server and our render server can coexist.

There are quite a few changes I made to get this working, all of them in the render server itself. Since the index.html template for the development mode is served via the webpack dev server, I modified the template loading code to only support the production build template. I also updated the server to use port 3001 and I implemented changes to the route handler so that during development, we proxied requests to the webpack dev server. Finally, I modified our custom file importers to just import as their own filenames. I made this change because as we found out, reading the file contents was not helping us and in fact, may have actually been hindering our ability to debug. By having the filenames instead, it should give a better experience for us when we're debugging.

require("./require-patches.js");
const http = require("http");
const express = require("express");
const React = require("react");
const {renderToString} = require("react-dom/server");
const getProductionPageTemplate = require("./get-production-page-template.js");
const App = require("../client/src/App.js").default;

const port = 3001;
const app = express();

const renderPage = (pageTemplate, reactComponent) => {
    const renderedComponent = renderToString(reactComponent);
    return pageTemplate.replace('<div id="root"></div>', `<div id="root">${renderedComponent}</div>`);
};

if (process.env.NODE_ENV === "production") {
    app.use(express.static("../client/build"));
}

app.get("/*", (req, res, next) => {
    /**
     * Production is easy. We'll load the template and render into it.
     */
    if (process.env.NODE_ENV === "production") {
        res.send(
            renderPage(getProductionPageTemplate(), <App ssrLocation={req.url} />),
        );
        next();
        return;
    }

    /**
     * During development, we're going to proxy to the webpack dev server.
     */
    if (process.env.NODE_ENV !== "production") {
        /**
         * Let's make life easier on ourselves and only accept UTF-8 when it's
         * a text/html request. We're in dev, so we don't need GZIP savings.
         */
        const headers = Object.assign({}, req.headers);
        if (req.headers["accept"] && req.headers["accept"].indexOf("text/html") > -1) {
            headers["accept-encoding"] = "utf8";
        }

        /**
         * Now call the client dev server, which we know is on port 3000.
         */
        http.get(
            {
                port: 3000,
                path: req.url,
                headers: headers,
            },
            (proxiedResponse) => {
                /**
                 * If our original request was text/html, we want to render
                 * react in there. So, let's gather that response and then
                 * render the page.
                 */
                if (req.headers["accept"] && req.headers["accept"].indexOf("text/html") > -1) {
                    let responseBody = "";
                    proxiedResponse.setEncoding("utf8");
                    proxiedResponse.on("data", (chunk) => {
                        responseBody += chunk;
                    }).on("end", () => {
                        res.send(
                            renderPage(responseBody, <App ssrLocation={req.url} />),
                        );
                        next();
                    }).on("error", e => {
                        res.status(500);
                        res.send(e);
                    });
                    return;
                }

                res.writeHead(proxiedResponse.statusCode, proxiedResponse.headers);
                proxiedResponse.pipe(res, {end: true});
                next();
            },
        );
    }
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));
const fs = require("fs");

let productionTemplate;
export const getProductionPageTemplate = () => {
    if (!productionTemplate) {
        productionTemplate = fs.readFileSync("../client/build/index.html").toString();
    }
    return productionTemplate;
};
const fs = require('fs');

const requireText = function (module, filename) {
    console.log(`Pretend import of ${filename}`)
    module.exports = filename;
};

require.extensions['.svg'] = requireText
require.extensions['.css'] = requireText;

After making these changes, if we fully reload our development server, it appears to work! Fantastic! We're done right? Well, not quite. Though it may not be obvious, especially when compared with some of our earlier errors, we have some problems remaining:

  1. The HTML we render on the server has the wrong SVG path in it. Because we're rendering the non-production version of the App component in the server, it has no access to the magic sauce that webpack introduces. This is going to be the case for any other similar imports we do.
  2. We are not yet performing what React refers to as hydration. This means that all the work we did on the server is pretty much ignored once it reaches the client, and the React app is remounted from scratch. This may not seem important for our little app since it is already so fast (mainly because it does almost nothing), but for a bigger application all we have done is make serving the page slower with no actual benefit!

👋🏻 Until next time

Next time we will work on addressing these issues and finally have server-side rendering that works. Of course, even then our journey is not over. With a fundamental render server working, it will be prime territory for us to branch out into dealing with some gnarlier problems like server-side rendering parts of an app that rely on asynchronous operations like data requests, speeding up our app by only loading the parts we need, and how to optionally render components between server and client without getting rehydration errors.

As always, thanks for joining me on this journey through the lands of server-side rendering with React. Until next time, have a lovely week! 💙

  1. Sadly, we our site won't benefit from it whatsoever []
  2. It really is not, but we'll get to that another time. []

🖥 Our first server-side render

Photo by Markus Spiske on Unsplash

This is part 5 of my series on server-side rendering (SSR):

  1. 🤷🏻‍♂️ What is server-side rendering (SSR)?
  2. ✨ Creating A React App
  3. 🎨 Architecting a privacy-aware render server
  4. 🏗 Creating An Express Server
  5. [You are here] 🖥 Our first server-side render
  6. 🖍 Combining React Client and Render Server for SSR
  7. ⚡️ Static Router, Static Assets, Serving A Server-side Rendered Site
  8. 💧 Hydration and Server-side Rendering
  9. 🦟 Debugging and fixing hydration issues
  10. 🛑 React Hydration Error Indicator
  11. 🧑🏾‍🎨 Render Gateway: A Multi-use Render Server

Over the last few weeks, we have been chipping away at server-side rendering and how to implement it. In the last post, we created a server; in this one, we will see if we can make that server render a page containing some server-side rendered React. If you recall from last time, there are two ways we can approach implementing our render server:

  1. Standalone with a way to pass our React app to it
  2. Integrated so that it knows all about our React app

Both approaches start from common origins; they both need a server that can render a React component inside a page. By the end of this post, we should be able to request a URL from our server and receive a rendered HTML page with some rendered React embedded inside of it. This will give us some fundamentals that we can then use next time to finally render our client-side application.


🖌 Rendering React on the server

app.get("/*", (req, res) => res.send("Hello World!"));

The server that we made last time will be the basis for our solution. Above is our current route handler for the server. Regardless of the get request, the server responds with Hello World!. What we want to do is to replace Hello World! with the rendered React component tree embedded within an HTML page.

When rendering in a browser, our React application is mounted so that it will dynamically update based on events like mouse movements, network requests, etc. When we are rendering on the server, we do not want all that. In fact, we do not even have a DOM like the browser does in which to create elements and event handlers and the like1. Instead of mounting the React application, we want to capture the very first render of the application and stop. React provides a methods for doing things like this in the React DOM package. We are going to use its renderToString method2.

The renderToString method takes a React component and gives us back a string of the markup that is initially rendered by that component. Before we can try it, we need to add the appropriate packages to our server: react and react-dom.

yarn add react react-dom

Now, in theory, we can render some React. Sadly, just updating our route handler with a component as shown below will not work.

app.get("/*", (req, res) => res.send(
    renderToString(<div>Hello World!</div>)
));

If we add this and then run our server with yarn start, we get a rather cryptic error output.

app.get("/*", (req, res) => res.send(renderToString(<div>Hello World!</div>)));
                                                    ^

SyntaxError: Unexpected token <
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

The issue is, our server has no idea how to handle JSX syntax (the embedded HTML-like description of our React component; <div>Hello World!</div>). Our client-side application works because the create-react-app package sets up some tools to process JSX files and turn them into valid JavaScript that can be understood by a modern browser. Our server-side application does not have any of that magic and so it does not work.

Rather than spending time to add that magic into our server, it feels more appropriate to assume our server is just another browser and that our client-side code will already be transformed into JavaScript by the time we see it3. Instead, just to test our React rendering, we can replace the JSX with its transpiled counterpart, which is a call to React.createElement. React.createElement takes the component being rendered and its props. In our case, we are rendering an HTML div element. These are special cases where a string is used to represent them, rather than a real React component type. Therefore, our simple JSX example becomes; note how the text is passed as the children of the component.

app.get("/*", (req, res) => res.send(
    renderToString(React.createElement("div", { children: "Hello World!" }))),
);

If we now yarn start our server application, it runs and when we visit http://localhost:3000, we see our Hello World! text. This is great. It means that given a suitably transpiled React component, we can server-side render it. Now that we have the ability to render a component, we need to embed that rendered component inside a full HTML page.

📄 The Page Template

OK, so we have some HTML that represents our rendered component. Now we need to put that into an HTML page, we need to think about what that page looks like. What does the page include? We can revisit the React app we made and see for ourselves.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="/manifest.json" />
    <!--
      Notice the use of  in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  <script src="/static/js/bundle.js"></script><script src="/static/js/0.chunk.js"></script><script src="/static/js/main.chunk.js"></script></body>
</html>

Above is the development-time HTML template that is used with our simple React app. I have highlighted some important sections.

  1. The head containing page metadata, including title, description, favicon, etc.
  2. Scaffold body to provide a mounting point for our React component
  3. Scripts

The head content is static4 and the scripts are inserted by the build operation of our client app. The bit that matters to us is the mounting point for our React app, <div id="root"></div>, as this is where anything we render will need to be inserted by our server-side rendering operation.

Of course, we want to do all this with production code. To see how that affects things, we can run yarn build in our React app. Running this creates a build folder with all sorts of things in it, including a slightly different version of our HTML template (we will perhaps consider the other files another time).

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="/logo192.png" />
    <link rel="manifest" href="/manifest.json" />
    <title>React App</title>
    <link href="/static/css/main.b0083702.chunk.css" rel="stylesheet" />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script>
      !(function(f) {
           // SNIPPED FOR CLARITY
      })([]);
    </script>
    <script src="/static/js/2.78e6b881.chunk.js"></script>
    <script src="/static/js/main.dcbf6a7c.chunk.js"></script>
  </body>
</html>

This looks a little different than what we had before, but it is not as different as you may think. We still have the head element metadata (though this time it includes a CSS file, which was not there in the development version), we still have the scripts (though there is now some inlined scripting that wasn't there before, which I have snipped out just to make things a little more readable), and most importantly, we still have our mounting point, <div id="root"></div>.

Given this information, we can update our server application to return a full page containing our rendered component. For our purposes here, we will hard code a simple page template. Eventually, we can replace this simple template and the React component being rendered with the production output of our client application.

🖼 Rendering the page and the component together

Using what we have learned here, I have modified the server as follows.

const express = require("express");
const React = require("react");
const {renderToString} = require("react-dom/server");

const port = 3000;
const app = express();

const pageTemplate = `<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="description"
      content="SSR result"
    />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
`;

const renderPage = (reactComponent) => {
    const renderedComponent = renderToString(reactComponent);
    return pageTemplate.replace('<div id="root"></div>', `<div id="root">${renderedComponent}</div>`);
};

app.get("/*", (req, res) => res.send(
    renderPage(React.createElement("div", {children: "Hello World!"})),
));

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

We have a page template string called pageTemplate. Then we have a renderPage method that does a simple replace operation to replace <div id="root"></div> in our template with the same div containing our rendered React component. Finally, in the get handler, the renderPage method is invoked with our React component.

If we yarn start this version of the server and visit http://localhost:3000, viewing the resultant page source gives us the following HTML.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="description"
      content="SSR result"
    />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"><div data-reactroot="">Hello World!</div></div>
  </body>
</html>

On the highlighted line, you can see the inserted server-side rendered React code. Success! We haven't even loaded any scripts client-side to see this result. Of course, if we want an app that a user can interact with, we are going to need to change that. Join me next time when we work out how to integrate our server with our client-side application in order to get our very first server-side rendered app. Of course, that does not mean we will have reached our destination on this server-side rendering adventure; on the contrary, it feels like we have barely begun.

Thanks again for reading. I hope that something you find here is useful. Please comment as you see fit. 💝

  1. We could introduce a DOM using a library like JSDOM. However, that is an extra step that we would like to avoid as it increases the latency of our server-side rendering process. Instead, we should aim to make sure our React app does not rely on there being a DOM present at all. []
  2. It is worth looking at the other options, such as renderToNodeStream, to see what they can offer you and your specific SSR challenges []
  3. You may notice that this starts to lead us down one of our two paths; does the server know all about the client code, or does it get blindly provided somehow? []
  4. For now, let's assume that the page metadata (item 1, above) remains static; while we can certainly build in a mechanisms to make this dynamic, such as changing page title when the selected route is different, that will over-complicate things at this stage. []

✨ Creating A React App

Photo by Rolands Zilvinskis on Unsplash

This is part 2 of my series on server-side rendering (SSR):

  1. 🤷🏻‍♂️ What is server-side rendering (SSR)?
  2. [You are here] ✨ Creating A React App
  3. 🎨 Architecting a privacy-aware render server
  4. 🏗 Creating An Express Server
  5. 🖥 Our first server-side render
  6. 🖍 Combining React Client and Render Server for SSR
  7. ⚡️ Static Router, Static Assets, Serving A Server-side Rendered Site
  8. 💧 Hydration and Server-side Rendering
  9. 🦟 Debugging and fixing hydration issues
  10. 🛑 React Hydration Error Indicator
  11. 🧑🏾‍🎨 Render Gateway: A Multi-use Render Server

Last week, I gave my own brief history of web sites and how their frontend implementation has drifted from entirely server-based, to entirely client-based, and is now settling (perhaps) with hybrid that we call server-side rendering (SSR). The goal of this journey is to poke around the gnarly bones of SSR and learn what we learn. We may make mistakes, break idioms, and portray ourselves as fools, but we will definitely learn. For that reason, we are not going to bother with things like Next.js, which have already fleshed over and hidden away the gnarly bones for us1.

Now, before we dip even further in the specific world of SSR, we are going to need an app. To be specific, we are going to need a React app.

Hello, React World!

Before creating a React app, we need a package manager; either npm or yarn will suffice. Though we could put together our own app from scratch, there is no need to as the handy create-react-app package exists. There are numerous ways to use this, but the easiest is to use yarn create or npx, which will do the work of obtaining the package and executing it all in one go.

For yarn, drop create from the front of create-react-app:

yarn create react-app <app-name-here>

For npx:

npx create-react-app <app-name-here>

I want to also put this in a git repository so I can track my changes. I would normally make a directory, run git init and then get started. In this case, we do not need to as create-react-app takes care of that for us.

So, let's begin. Open a terminal and invoke create-react-app.

yarn create react-app hello-react-world

After executing this, you will have a working React app that uses react-scripts to manage the basics. This is perfect for our initial journey. If we navigate to that directory and run the project, we can see our app in action.

cd hello-react-world
yarn start
Screenshot of the website created by the create-react-app tool. It shows the React logo in blue, over a dark grey background, with the text "Edit src/App.js and save to reload." and a link labelled, "Learn React"

Fantastic. We have an app. Before we do any more, let's get some remote source control underway. I am paranoid of my machine dying and losing all my work, so having an off machine place to store things is really useful. First, add a new repository on your source control site of choice (I prefer GitHub). Second, connect the local repository to the remote one:

git remote add origin <repo-url>
git fetch
git branch --set-upstream-to origin/master master

Since we want our local code to be the first commit and we're pushing to a brand new repository, we can force push what we have.

git push -f

Routing

Okay, we have an app and it is in source control. This is usually a good spot to spend some time setting up code quality tools like eslint and prettier. I am going to be naughty and skip right over that right now and save it for a different post, perhaps. Instead, let us add some routing to our fledgling application.

There are a few options for implementing routing in a React application (some frameworks, like Next.js, even provide it out of the box). We are going to use React Router. There are two variants of React Router; one for React on websites, and one for React Native on mobile. We want the website variant, which is provided by the react-router-dom package.

yarn add react-router-dom

Now we will edit our app to have a couple of routes. The main app is defined in the src/App.js file. It should look something like this. I have highlighted the lines we're going to replace; we are also going to add some too.

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

There are two things we want to add.

  1. The routes to render our pages.
  2. The links to navigate to our routes.

First we import four things from react-router-dom:

  1. BrowserRouter
    This is the root of our React Router-based navigation. Basically, the router is responsible for the routing (I'm sure you guessed that).
  2. Link
    This replaces the anchor tag (<a>) for our navigation.
  3. Route
    This is used to render a matched route.
  4. Switch
    This allows us to specify a table of possible routes that can be used to work out what should handle the URL currently being viewed.

With these things, we can then add some routes. I am adding Home, About, and Contact. Here is my app code after the edit. I have highlighted the new lines.

import React from 'react';
import {BrowserRouter, Link, Route, Switch} from "react-router-dom";
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <div className="App-links">
            <Link className="App-link" to="/">Home</Link>
            <Link className="App-link" to="/about">About</Link>
            <Link className="App-link" to="/contact">Contact</Link>
          </div>
        </header>
        <section className="App-content">
          <Switch>
            <Route path="/about">
              This is the about page!
            </Route>
            <Route path="/contact">
              This is the contact page!
            </Route>
            <Route path="/">
              This is the home page!
            </Route>
          </Switch>
        </section>
      </div>
    </BrowserRouter>
  );
}

export default App;
Screenshot of the updated app using React router. The top shows the React logo with three links below it for "Home", "About" and "Contact" all on a dark grey background. Below that is a white region with the text "This is the home page!"

I also edited the CSS a little, but only to make things easier to see. The important bits are the router, wrapping our app, the Link components to perform navigation, and the Route components that render each route. With this, we now have a single page React app that has three pages for home, about, and contact.

This is going to be the application we will eventually render on the server. The important take away at this point is that we are not going to change the functionality of this app in order to achieve our aim. There are some changes we must make to support SSR, but we will not have two versions of the code. The code that runs in the browser will run on the server.

Next time, we are going to setup a server that will perform our SSR and consider what changes we need to make to our application infrastructure in order to support it. We might even get our first server-side rendered page. Until then, thanks for joining me on this continued exploration of server-side rendering using React.

  1. of course, if starting a new project knowing you need SSR, you should explore solutions like Next.js []