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

Server Side Rendering

Adding ES6 and JSX Support on the Server

In this tutorial, we expand our Express server's capabilities by integrating Babel Register to enable ES6 and JSX support. This step is crucial for preparing your server to dynamically render React components.


Step 1: Dynamically Pass Variables to EJS Templates

  1. Update your EJS template:

    • Replace static HTML with dynamic placeholders.
    • Example for a layout template:
      <html>
        <head>
          <title><%= title %></title>
        </head>
        <body>
          <%= body %>
        </body>
      </html>
      
    • The <%= %> syntax dynamically injects values into the template.
  2. Update your Express server to pass variables:

    app.get('/', (req, res) => {
      res.render('layout/blank', { 
        title: 'Mastering React Performance', 
        body: 'I got a body.' 
      });
    });
    
    • This sends the title and body properties to the template.
  3. Restart your server to reflect changes:

    • Use Ctrl+C to stop the server, then node server.js to restart.

Step 2: Set Up Babel Register

  1. Install Babel Register:

    npm install @babel/register --save
    
    • This package dynamically transpiles ES6+ and JSX files during runtime.
  2. Add Babel Register to your project:

    • Place this at the top of your server.js file:
      require('@babel/register')({
        presets: ['@babel/preset-env', '@babel/preset-react']
      });
      
    • This ensures all JavaScript files loaded by the server are transpiled to a compatible format.
  3. Configure Babel in your project:

    • Create a .babelrc file in your project root:
      {
        "presets": ["@babel/preset-env", "@babel/preset-react"]
      }
      

Step 3: Load React Components Dynamically

  1. Load React and ReactDOMServer:

    const React = require('react');
    const ReactDOMServer = require('react-dom/server');
    
  2. Dynamically render React components:

    • Import your main React app:
      const App = require('./path-to-your-app').default;
      
    • Render the React component into HTML:
      const renderedHTML = ReactDOMServer.renderToString(<App />);
      

Why Use Babel Register?

Babel Register eliminates the need to precompile files, allowing you to:

  • Work with ES6 and JSX seamlessly.
  • Automatically cache transpiled files for optimized performance.
  • Enable runtime support for modern JavaScript features.

In the next lecture, we’ll combine these tools to render React components directly from the server, completing our journey to isomorphic JavaScript!

2024

The approach described is still functional in 2024, but it is no longer the most efficient or commonly recommended practice. The JavaScript ecosystem has evolved significantly, with modern frameworks and tools providing more streamlined and optimized solutions for server-side rendering (SSR). Here are some key points:


Key Considerations in 2024

1. Babel Register vs. Precompilation

  • Babel Register is still a valid solution, especially for quick setups. However, it adds runtime overhead as files are transpiled on-the-fly. In a production environment, precompiling your code using a build tool like Webpack or Vite is the preferred approach.
  • Modern build tools can bundle, minify, and tree-shake your code, resulting in significantly better performance.

2. The Rise of Next.js

  • Next.js has become the industry standard for server-side rendering and full-stack React applications. It provides:
    • Built-in ES6+ and JSX support.
    • Automatic code splitting for optimized loading.
    • API routes and server-side functions for seamless backend integration.
    • File-based routing for simplicity.
    • Edge rendering for ultra-low-latency applications.
  • In 2024, using Next.js eliminates the need for manual Babel configurations or custom Express server setups, significantly reducing complexity.

3. Native ES Modules in Node.js

  • Node.js has robust ES module support, allowing developers to use import and export natively without Babel for most modern use cases.
  • If you still require JSX transpilation, SWC (used by Next.js) or ESBuild can provide faster alternatives to Babel.

4. Enhanced React Ecosystem

  • The React ecosystem now includes powerful libraries like React Server Components (RSC), enabling fine-grained control over what is rendered on the server versus the client.
  • React’s Streaming SSR offers improved performance for server-side rendering by streaming content to the browser as it is generated.

Recommended Modern Workflow

  1. Use Next.js for Full-Stack Applications:

    • Skip the manual setup of Babel, ReactDOMServer, and Express.
    • Focus on your application logic instead of configuration.
  2. Precompile Your Code for Production:

    • Use build tools like Vite, Webpack, or SWC for preprocessing ES6+ and JSX files before deploying your application.
  3. Leverage React Server Components (RSC):

    • Use server components for SSR while dynamically rendering client components as needed.
  4. Embrace Edge Functions (Optional):

    • Use platforms like Vercel or Cloudflare Workers to deploy server-rendered content closer to your users for better performance.

When Would This Setup Still Be Useful?

The described approach (using Babel Register, EJS, and Express) may still be relevant if:

  • You are maintaining a legacy application.
  • You need a custom server setup for educational purposes.
  • You are exploring low-level SSR concepts as part of a learning process.

However, for new projects in 2024, modern frameworks like Next.js or Remix are far superior in terms of both developer experience and performance.

Video Transcript

00:00We finally reached the heart of this section
00:02where we'll start rendering our server side on the server
00:06side with that universal JavaScript.
00:08In our case it's React.
00:10And I want to talk to you
00:11before we actually start doing it
00:13about why do you want to do this?
00:14For one, you're gonna be using the same JavaScript
00:16universally, so that means that you're gonna have less code,
00:19which is gonna be better
00:20for your overall management of your code.
00:23It's great for search engines in our case of React
00:25because our content will be pre-rendered in the HTML.
00:28So even if the user doesn't have support for JavaScript,
00:31they would still get something on their site.
00:33And for that matter, it's better for accessibility,
00:35it's better for search engines.
00:37There's a lot of benefits of having HTML pre-rendered even
00:40before there is JavaScript.
00:42And last but not least, we could share this data
00:45and that data can be cached.
00:47So if the, instead of having
00:48that rendering always happening on the client,
00:51if we have this data and it's the same for all users,
00:53why not just have it in advance sitting there and ready
00:55and even not render anything on the client side.
00:58Maybe the job, the, maybe we're just rendering something out
01:01and we don't even need the client side JavaScript.
01:03So there's a lot of benefits in performance
01:05and in this lecture we're gonna see
01:06how we actually integrate it.
01:09Alrighty, we're getting really close.
01:10Let's go ahead and start setting up babble itself.
01:13So we required our babble app,
01:15but in this process of the required,
01:17because it was transcribed down, there is no such thing
01:20as default in ES five modules.
01:23So I need to go ahead and ask for that default item
01:26that is the name that has been assigned to it
01:28because it's the default item.
01:30So now that I've gained access to that default item,
01:33I'm gonna make sure that inside of this area, I'm not going
01:36to use any E es six things.
01:39So to be able to do that, I'm just gonna go to my body
01:41and let me, let's just break a line here
01:43so you can see it more easily.
01:45And I'm gonna go ahead. First of all,
01:46I'm going to show you the, the steps.
01:48First of all, I'm gonna go to React and instead of React,
01:52and instead of using JSX,
01:54'cause we don't wanna use JSX in this file,
01:56I'm gonna go ahead and say react, do create element,
02:03and I'm gonna go ahead and send in our app.
02:06So in this case, you know, let me just go ahead
02:08and I'm gonna grab this whole thing.
02:09Now, technically speaking,
02:10if we were doing this in E ES six,
02:12this would not be permitted, but I could go ahead
02:15and just delete that variable
02:16'cause we're only using it once beyond that.
02:18I'm gonna take that element that we've created
02:20and I'm gonna render it into that React dumb server.
02:24So our React Do server, I'm gonna call that render
02:29to not renter, re to string.
02:33And I'm gonna literally just go ahead
02:34and send this whole beautiful construct we've just created
02:39as its value, oopsie as its value.
02:43So again, what's happening here, we required the app,
02:46it automatically was transcribed using Babb Register.
02:50We took the default item from it
02:52and then we sent it to create a React element.
02:55So far we've been using JSX, but
02:57because this specific file does not support e es six
03:00because we're building our server in this file.
03:02Last but not least, once we have our element itself,
03:05we're sending it to be rendered using rendered to string.
03:08'cause we really just wanna get a string
03:09and send that to our body.
03:11Now if everything worked and lemme go ahead and save this
03:14and restart our server,
03:16although technically I don't, ah, it's not running.
03:19So yeah, let's, let's start up our server, that's for sure.
03:22And once our server is running, if I go back there
03:25and click here on refresh, we should get
03:27a step further closer.
03:29Now we're almost ready. It's not completely done.
03:31We have one more, two more problems really.
03:33And if you take a look at this, we're trying to load up
03:36CSS files and these CSS files are just not accessible
03:40because this is client side specific in our case,
03:43and we really don't, we technically speaking, we would love
03:46for our server to ignore all this, all of these CSS requests
03:50that are happening in our navigation and many other places.
03:54So what we're gonna do to avoid this is I'm gonna do
03:56something that is specifically related to the server itself.
04:00And I'm gonna go into my server
04:02and write all the way on the top here
04:04before I really do anything.
04:05I'm gonna create a global variable
04:07and I'm gonna call it Global Server.
04:09Set it to be true. Now we have a global server variable.
04:13Now that we have a global server variable, I could go inside
04:16of specific components for that matter
04:19and literally just ask
04:22and see if we could load them up.
04:24Now I'm gonna go ahead
04:26and do this in a kind of contrived way.
04:29I'm gonna go into the utilities function here
04:32inside of my utilities.
04:33And I'm gonna export another method here.
04:36I'm gonna go ahead and export it
04:37and I'm gonna call this a function.
04:40And I'm gonna, I'm gonna give it a name of load, client
04:44externals, external load, client external.
04:48It's gonna receive a path
04:51and only if we're not on the server.
04:55And only in that case I'm gonna go ahead and require,
04:58and again, I'm using Require
05:00and not ES six load, um, imports.
05:03'cause this would not be permitted if we were
05:05using E ES six.
05:06So in this case, I'm just gonna require,
05:08and I'm gonna go ahead
05:10and ask for that specific path that's
05:14inside the current directory.
05:15And if I'm already doing this, let's cut down the
05:17amount of file typing.
05:18Amount of typing, which will always be good.
05:20So if I go ahead now,
05:21and I'm just gonna go step by step into every
05:24single element now.
05:25So in our navigational element here, um, instead
05:28of using an import oopsie, instead of using an import,
05:31I'm gonna copy this load external file.
05:34Um, I'm gonna also make sure that it's actually loaded up
05:38and then I'm gonna go ahead here and load up our navigation.
05:43Beautiful. Let's go ahead. We don't need that anymore.
05:46Let me, you know, let me leave that there just
05:48so you could peek at it if you choose to.
05:51And let's go ahead and let's save,
05:53let's do this also in our jumbotron.
06:01And let's do this. Oso in our button.
06:06My aunt always says button. I I love that word.
06:09Instead of button, button.
06:12Okay, we got here a button and nothing here else,
06:16but let's check if the app has some CSS.
06:18Uh, sure does. It has some SaaS technically speaking
06:22and I just have to make sure that I'm, oh, I forgot
06:24to import it in all those areas.
06:26So first of all, I'm gonna go ahead and import Where are we?
06:31Where are we? Where are we? I need to import it.
06:34We don't have it here. Okay, so let's just go one by one
06:36to make sure that we're loading up.
06:37So we're definitely doing it here.
06:39So let me just grab that
06:41and make sure that it's also container doesn't have any CSS
06:45Jumbotron sure does.
06:49Our navigation sure does, but it's already there.
06:52And for our app itself, I'm just gonna go ahead here
06:55and import also our load external, we don't need
06:59to classify, but in this case it's not in the current
07:02directory, but inside of Bootstrap Utilities.
07:06Okay, so now that we've loaded it all up, fee,
07:08theoretically speaking, if we run it, which should work.
07:12So let's go ahead and give it a shot
07:13and let's see if we, we have any more errors.
07:17Oopsie. And let's stop our server,
07:21clear everything up, give it another shot,
07:24and we actually go and test it out.
07:28What happened there? Our server should run. And there we go.
07:31Our react is rendering.
07:33Now don't forget, our web pack is packing,
07:35packaging our CSS and JavaScript.
07:37So those are not gonna run right now,
07:39but our React application is now rendering the information
07:42that needs to be rendering as we're separating these steps.
07:46This is kind of like the production
07:48way we would wanna build out our application.
07:50We don't wanna package things up in the production.
07:52The pro the packaging would happen is externally
07:55to the production itself.
07:57Then there we go. We're done with one more step closer
08:00to get our application to be fully working, integrated
08:02with server side rendering.
08:06In this lecture we integrated our React application
08:10to build up on the server itself.
08:12And really we're very close to the end of this section,
08:15but there's a couple of more things that we need to do
08:17to be able to get our application to actually fully work.
08:20So in this, in the next lecture, we're gonna take out
08:22a look at node modules
08:24because we're gonna need one to be able
08:26to continue building out our production server.

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!