The magic of React Hydrate with Jopi Rewrite
Johan PIQUET

Johan PIQUET @johanpiquet

About: Full stack developer near Lyon (France).

Location:
Villefontaine, France (38090)
Joined:
Apr 5, 2023

The magic of React Hydrate with Jopi Rewrite

Publish Date: Jul 29
4 0

What is React Hydrate?

React.js is an open-source JavaScript library for building user interfaces (UI) in the browser. React.js is very popular and many developers use it to simplify their projects.

For a long time, React.js was a technology that ran only in the browser, allowing you to create high-quality interactive UIs. This is called React BSR (Browser Side Rendering).

About four years ago, it became possible to use React on the server side, known as React SSR (Server Side Rendering). Here, React.js only generates HTML, which corresponds to the visual of a React component but without any interactivity. It is a dead component, without interactivity, whose role is only to help us write HTML. The idea of React SSR is to reuse component logic and composition to make things easier.

React SSR is interesting because it allows you to create React.js websites that are compatible with search engine indexing (Google).

Then frameworks appeared, notably NextJS. They introduced a third way to use React.js, with something called hydration. The idea here is to use React SSR to generate HTML, making the site compatible with Google indexing. Then, once in the browser, the React SSR is automatically replaced by React BSR: so the dead component, which does not respond to events, is automatically replaced by a live and fully functional component.

React Hydrate is React SSR that automatically becomes React BSR.

What is Jopi Rewrite?

Jopi Rewrite is a server framework for Bun.js (a high-performance clone of Node.js). It is minimalist in its logic and is very similar to express.js. However, it includes many interesting tools while keeping a keep it simple philosophy.

Here is an example of code using Jopi Rewrite for React SSR:

import {JopiServer, WebSite} from "jopi-rewrite";

// Create a server responding to url http://127.0.0.1
const server = new JopiServer();

// Jopi Rewrite can handle more than one website.
// That's why we declare a server and a website in two steps.
const myWebSite = server.addWebsite(new WebSite("http://127.0.0.1"));

server.startServer();

// Is called when visiting the home page.
myWebSite.onGET("/", req => {
    // Returns a React component.
    return req.reactResponse(<MyButton />);
});

// This is the React component itself.
function MyButton() {
    const doClick = ()=>alert("click!");
    const style = {border: "1px solid red", background:"yellow"};

    return <div style={style} onClick={doClick}>Click me!</div>;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, with Jopi Rewrite, doing React SSR is very simple! There is nothing special to do, nothing to configure. Here, the React component is very simple: it displays a yellow button with a listener that shows an alert message when you click the button.

The generated HTML code is as follows:

<div style="border:1px solid red;background:yellow">Click me!</div>
Enter fullscreen mode Exit fullscreen mode

Here, two things are remarkable:

  1. There is no onClick event listener, no JavaScript scripts, nothing. This is normal, because we are doing React SSR: the React component is converted into dead HTML code, without interactions.
  2. Jopi Rewrite has not added anything to our page, we only have our component (no headers, no scripts). This behavior matches the philosophy of Jopi Rewrite: avoid automatic things.

Creating a Jopi Rewrite project

Here we will see how to install Jopi Rewrite and create our first project.

Jopi Rewrite does not use Node.js but Bun.js. So you need to start by installing BunJS.

  • Bun.js project page: https://bun.sh
  • Simplified installation if you already have Node.js: npm install bun --global.
  • Otherwise:
    • For Linux / OSX: curl -fsSL https://bun.sh/install | bash
    • For Windows: powershell -c "irm bun.sh/install.ps1 | iex"

Once bun.js is installed, just create a package.json file with the dependencies.

File package.json

{
  "dependencies": {
    "jopi-rewrite": "latest",
    "jopi-rewrite-ui": "latest"
  }
}
Enter fullscreen mode Exit fullscreen mode

Everything works like with Node.js, but here you replace the word node with bun. Instead of running node install you run bun install. Instead of running node index.js you run bun index.tsx.

Now we just need to create our application itself. Here we will create a file with the extension tsx: this is Typescript for React. One interesting thing with BunJS is that it understands Typescript, so you don't need to convert your Typescript files to JavaScript (which is a hassle with NodeJS). Likewise, it can directly interpret tsx files.

React Hydrate

Now we will convert our previous example to enable React Hydrate capabilities. This means our component will become alive again once in the browser. To do this, it's very simple, just follow these two rules:

  1. Our root component must live in its own file.
  2. It must be marked so that Jopi Rewrite knows it should automatically hydrate it.

That's it, those are the only constraints. So let's start by creating a file MyButton.tsx with this content:

File: MyButton.tsx

import {mustHydrate} from "jopi-rewrite-ui";
import React from "react"; // <-- required when doing hydrate.

function MyButton() {
  const doClick = ()=>alert("click!");
  const style = {border: "1px solid red", background:"yellow"};
  return <div style={style} onClick={doClick}>Click me!</div>;
}

// mustHydrate enables hydration for our component.
// Here it wraps it with things which will automatically hydrate our component.
//
const MyButton_Hydrate = mustHydrate(import.meta, MyButton);

// Expose our component.
export default MyButton_Hydrate;

// You can also directly do:
//export default  mustHydrate(import.meta, MyButton);

// Or:
//export default  mustHydrate(import.meta, () => function MyButton() {...});
Enter fullscreen mode Exit fullscreen mode

Now, just call this component from our main code.
For this, we will create the file index.tsx:

File: index.tsx

import {JopiServer, WebSite} from "jopi-rewrite";
import MyButton from "./MyButton";

const server = new JopiServer();
const myWebSite = server.addWebsite(new WebSite("http://127.0.0.1"));
server.startServer();

myWebSite.onGET("/", req => {
    return req.reactResponse(<MyButton />);
});
Enter fullscreen mode Exit fullscreen mode

If you run this code bun ./index.tsx then the page http://127.0.0.1 will still display our yellow button. However, this time you can click on it and see that the alert message appears: our component is alive.

Here it is a very simple component, but you can use much more complex components.

No Webpack or ViteJS? If you are used to doing React.js BSR, you know that you need a tool to create a bundle of your JavaScript code, which consists of taking all the '.ts', '.tsx' files, converting them to JavaScript, and then bundling them into a single large file.

Here this is not necessary, because Jopi Rewrite handles all this internally (based on EsBuild: which is ultra fast).

Using CSS files

Jopi Rewrite automatically includes your CSS files when you use React Hydrate. Here, we will modify the MyButton.tsx file to use a CSS file.

File MyButton.tsx

import {mustHydrate} from "jopi-rewrite-ui";
import React from "react";
import "./MyButton.css";

export default  mustHydrate(import.meta, () => {
    const doClick = ()=>alert("click!");
    return <div className="my-button" onClick={doClick}>Click me!</div>;
});
Enter fullscreen mode Exit fullscreen mode

File: MyButton.css

.my-button {
    background: #5bb0f3;
    color: white;
}
Enter fullscreen mode Exit fullscreen mode

Now in the browser it's no longer a yellow button but a blue button, which shows that our CSS has been included.

Jopi Rewrite also supports the use of SASS files (.scss files).

Going further

Jopi Rewrite allows you to do many things. It includes components that make the following very easy:

  • Create an HTML cache.
  • Create a proxy with load-balancing.
  • Create a crawler to scan all the pages of a site.
  • It natively manages JWT tokens and role-based security.

Jopi Rewrite also brings something unique: the ability to live-edit your server's source code (just like in PHP). The server then updates itself, without interrupting ongoing processes and without losing its memory content.

I invite you to visit the project's Github page for more information https://github.com/johanpiquet/jopi-rewrite.

☆☆☆☆☆☆

If you like this project, let it be known by adding a star on Github!

☆☆☆☆☆☆

Comments 0 total

    Add comment