02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Running React on the Server Side

Running React on the Server Side

In this tutorial, we will explore how to set up and run React components on the server side. By doing this, you can improve the rendering performance of your application and make it more flexible. We'll focus on configuring React to work on the server, and also touch on some best practices for maintaining code that can be shared between both client and server.

Introduction to Server-Side Rendering (SSR)

Server-side rendering (SSR) involves running JavaScript code on the server to generate HTML that can be sent to the client. This technique provides a fast initial load and improved SEO, which can be beneficial for content-heavy websites.

Here, we will not create idiomatic JavaScript (i.e., code that runs seamlessly on both the client and server), but we will explore how to run the same React components on both sides. The ultimate goal is to develop components that are capable of running in both environments, and we leave that part as a challenge for you to explore.

Note: This tutorial was created in 2016, and there have been significant advancements in SSR frameworks, such as Next.js. If you're looking for a modern approach to SSR, consider using a framework like Next.js, which offers a lot of built-in functionality.

Setting Up React for Server-Side Use

Step 1: Install React and Dependencies

First, you need to install the necessary dependencies for React and server-side rendering:

npm install react react-dom

Additionally, you need to install react-dom/server, which allows you to render React components as static markup on the server.

Step 2: Setting Up Your Server

Let's configure our server to use React components. Below is a simplified example using Express and EJS for rendering templates:

  1. Import react and react-dom/server modules:

    const React = require('react');
    const ReactDOMServer = require('react-dom/server');
    
  2. Set up a route to render a React component on the server:

    app.get('/register', (req, res) => {
        const RegisterComponent = require('./components/Register');
        const registerHTML = ReactDOMServer.renderToString(
            React.createElement(RegisterComponent)
        );
        res.render('layout', { body: registerHTML });
    });
    

    In the above example, we use React.createElement to create a component instance and ReactDOMServer.renderToString to convert it to HTML.

Note: Since this tutorial was made, React has introduced hooks and improved rendering performance through features like concurrent rendering. It's advisable to check the React documentation for the latest updates on SSR.

Step 3: Structuring Code for Reusability

In order to use the same React component on both the client and the server, you need to ensure that no server-specific or client-specific logic is directly inside the component code. Instead, keep such logic in separate modules and import them as needed.

For instance, anything related to browser APIs should be isolated in a client-only script, while server-only code should be kept in modules that the server uses explicitly.

Hint: Think about separating rendering logic from data fetching, as server-side components should not directly interact with browser APIs.

Homework Assignment

As an assignment, consider making a React component idiomatic by ensuring it runs both on the client and server. To do this, you need to abstract away the parts of your component that are client-specific (e.g., event listeners, window access) into separate utility files.

Conclusion

Running React on the server helps improve the initial user experience and boosts SEO. In this tutorial, we explored the basic steps required to set up React for server-side use. We also touched on how to improve reusability by abstracting client-specific and server-specific logic.

Next Steps: In the next tutorial, we will cover integrating Babel for transpiling JavaScript and optimizing your server-side rendering workflow without using Webpack.

Video Transcript

00:00In this lecture, we're gonna go ahead
00:02and set up our React components that we've created
00:05to run on the server.
00:07Now, we are not gonna actually create idiomatic JavaScript.
00:11I wanna explain to you what that is.
00:13Idiomatic JavaScript
00:14or JavaScript files
00:15that you could use in multiple different places.
00:18In this case, our React application
00:20or components could be built out
00:23to be used both on the client side and on the server.
00:26Now we're not gonna do that,
00:28but instead of that, we showed you how
00:29to run it on the client
00:30and we're gonna show you now how to run it on the server.
00:33What I want to give you as a homework assignment is figure
00:36out how to get the exact same file
00:38to run both on the client and the server.
00:40And the hint is you want
00:42to take out any server specific code out of your React files
00:46and have them render in a different place.
00:49Whatever is connected only to the server,
00:51whatever's connected only to the client, you want
00:52to put in a separate file as well.
00:54And that way you could use the same exact file
00:57for both the client and the server.
00:59And although we've given you all the skills to be able
01:01to solve it, all that's left for you to do is
01:03to explore and figure it out.
01:04But in this lesson, we're gonna show you how to set up
01:07and take those React elements components
01:10and get them to work on the server.
01:13All righty, let's continue our journey.
01:15And the next step in our journey that I want
01:18to do is I basically want
01:19to get our React code to run on the server.
01:22Our goal is to create a React application
01:24that completely runs on the server.
01:26Now, to do that, I'm gonna put that react inside
01:29of our source folder folder.
01:31Now, personally I would differentiate it,
01:34so I would call it React, no, I would call it React.
01:38Uh, I would call it React.
01:40And once I created that folder, I'm gonna go inside there
01:42and let's grab a React logic
01:45and I'm just gonna copy it right from our original file.
01:49And because this is not gonna be standard client side react,
01:53I'm gonna go ahead and give it a name
01:55that is fitting to what it does it.
01:56It relates to authentication, things that relate to React.
02:00Okay? Okay.
02:02So let's go inside that file and let's go ahead
02:03and start editing it
02:05and getting it ready to be able to really run on the server.
02:07So let's go into React into our auth file
02:11and inside of our auth file.
02:12First of all, I'm gonna go ahead and delete these stuff.
02:14We don't need them and I'm gonna delete the layout
02:16because we don't need that anymore.
02:18We have a layout. The next thing I wanna do also,
02:20let's go ahead and also make sure that we are going
02:23to our turn terminal.
02:25Turn terminal, terminal.
02:27And what I want to do is I want to install, so NPM install,
02:32save it into our production.
02:34I want to get react and react dumb, remember that?
02:37So let's go ahead and install those.
02:38And as those are installing,
02:40let's continue with our editing.
02:42So the first step that I want to do is I want
02:44to create now new constants.
02:45'cause now we need to have a react.
02:47And so we need something similar to react dumb.
02:50So first of all, let's go ahead and configure React. React.
02:53We're gonna fetch by calling the require function
02:58And asking for React, making sure it's all lowercase.
03:05And secondly, we wanna also get a React dom,
03:07but instead of asking for React dom, we're gonna ask
03:10for React Dom server
03:11because it's gonna be running on the server,
03:13which does logic a little bit bit differently.
03:15So we want React dumb server
03:20slash to get it from the server.
03:22So there you go. Those are the two global
03:24variables, constants.
03:26In our case, we decided that we're gonna be using
03:28to run our application.
03:30Let's go through the funnel. And I'm gonna start from
03:32taking, making sure that our call on the bottom there
03:35to render is actually gonna call React Dom server.
03:38But really we're not gonna be rendering stuff right away
03:41because this is not actually a view.
03:43What we wanna do is we want to export the access
03:46to be able to trigger it.
03:48Now, the way we do that is very simple.
03:49What we're gonna do is, and I'm just gonna go right ahead
03:51here, we're gonna delete this in a second.
03:53I'm gonna call module exports.
03:55We've seen that for a second previously.
03:58And I'm gonna send in an object to it.
04:00And that object will have a function
04:02which I'll call register.
04:05And that function will
04:08actually wrap up our rendering process
04:10and send it to whoever's calling.
04:12So I'm gonna go ahead here and return,
04:14and I'm gonna ask for that React, um, server.
04:17And I'm gonna render into a string,
04:20which is something you could do on the server.
04:22And then I'm gonna send inside what I wanna send.
04:24So in this case, I'm, I'm calling Register.
04:26So I wanna call the register component. Beautiful.
04:30Alright? The next step
04:32after this is really to test things out
04:33to see if they work, but they won't work.
04:35So I'm, let's assume that they do work for now
04:37and we're going to continue on with our process.
04:40Now, in a real world scenario, in our registration,
04:43there might be a lot of different types
04:44of errors to enable that.
04:46What I want to do is I'm gonna push in when this function is
04:48called a message, which is not gonna be a mandatory message.
04:52But what I wanna do is I wanna send
04:53that message into our register
04:55and let me make sure that there's word wrap here.
04:57Also, view word wrap.
05:00And I'm gonna make sure that I'm sending
05:02that variable onwards.
05:03And this is something we haven't seen completely,
05:05but we've seen it, but not completely.
05:06Now, if we go into our register now, our register component,
05:10what I wanna do, because I want to have that processed
05:12inside of our password section, I'm gonna go ahead
05:15and I'm gonna send in another property for message.
05:19And I'm gonna just pass
05:20through without even knowing what's inside.
05:22I'm gonna pass this props do message, just letting it go
05:26through, flow through until the password component.
05:30Now, when we go into the password component,
05:32because we're running things on the server,
05:34we're not gonna have state,
05:36our component is gonna be stateless.
05:37And as such, we're gonna get rid of all
05:39that state related mumbo jumbo.
05:42And instead of that, instead of that logic
05:44of checking if things are equal
05:46or not, which is something that should be done in our module
05:48on the server, especially if we're running things on the
05:50server, and this is part of the supposed view.
05:53So instead of that, what we're gonna do is
05:55I'm gonna go ahead and just
05:57Ask if, if,
06:01what do we wanna know if our this props message,
06:06okay, so we got a message, what do we wanna do?
06:09In that case, I'm gonna go to ch
06:10and I'm gonna push into it a message.
06:12What message do I wanna push into it?
06:14Let's think, let's go ahead
06:16and copy this error message that we have here.
06:19And I'm just gonna paste that message away.
06:23And once I paste that message away, what I want
06:25to do next is, is, is, is, is is not have your uh,
06:28hardcoded value, but instead of that, I'm gonna go ahead
06:31and pass the value that's inside of this message,
06:34making sure that I have a message that is passing through,
06:37okay, now we don't need this if password stuff anymore,
06:41nor do we need this, nor do we need this message here
06:43anymore, nor do we need this message variable.
06:47'cause really what's happening is if there is a message,
06:48we're adding it into the children
06:50and then we're printing it out, sending it in.
06:53Okay? So that's it.
06:54Those are really all the changes that we needed to make.
06:57There's a couple more changes that I want to cut through.
07:00One is because we're running on the server first,
07:02it's not gonna work natively when we're gonna go ahead
07:04and try to run our application.
07:06It's just simply not gonna work.
07:07So we're gonna address that
07:09and sort that out in the next lecture
07:11where we're gonna integrate something
07:13that is incredibly familiar to you probably already,
07:16which is the Babel transcriber.
07:19In this lesson, we took you a hundred steps closer
07:22to idiomatic JavaScript, although we deliberately
07:25and I deliberately left you some room to explore yourself.
07:28So this is a real challenge, not incredibly hard,
07:31but a very rewarding one where I urge you
07:33to not continue watching the videos yet,
07:35but instead of that, try to figure out how could you get
07:37that react component
07:39to work both on the client and the server.
07:40And again, the hint is don't use server related things
07:45inside of the class itself, nor client ones
07:49and leave the rendering itself to be in a separate file.
07:52Alright? And in the next lecture, what we're gonna do,
07:54we're continuing down our path.
07:56And what we're gonna do is we're gonna integrate Babel six
07:58this time without Webpac,
08:00but in a different way, a smart way, in a way
08:02that you'll understand much better how Babel Six works,
08:05or more accurately how it should work
08:07and how you should have it work.
08:08And you're gonna see the best way to work
08:10with it in the next lecture.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!