loading...
Cover image for create HTTP servers using react !!!

create HTTP servers using react !!!

shmuelhizmi profile image shmuelhizmi ・3 min read

So... I woke up this morning with an Idea - "creating reactable node HTTP/s servers with react can be quite interesting" and so I set down and start working and now 4-5 hours of work later I have an announcement to make - you can now create a reactable HTTP/s servers using a React warp of express.js.

Note: if your not interesting in reading this post and just want to create HTTP/s servers using a React that is completely ok, you can install it now using npm install @react-express/server or npm install @react-express/server-core for the slim version and you can find an example use at react-express github.

❓ why is it useful

The magic of React is that everything is stateful reactable and let's not even start talking about the extremely pretty syntax,
if you are not familiar with react please check it out it's the biggest web library/framework (in terms of user-base) and in my opinion the best one :)
and so... - as I see it all the benefits of React (stateful, reactable, cool syntax, component-based, and more...) can also be applied into the servers world,
express servers are great but they are too much static in my opinion and I think React can change that!!

❗ getting started

let's start by installing "@react-express/server" into our server we can do that by running npm install @react-express/server inside our project.

since we are using JSX let's make sure to enable JSX inside our project you can learn how to do it using bable and using typescript

and now let's start coding! if we want to mount an http server inside our project we need add the following lines to our code

import React from "react";
import { Render, Server, Route } from "@react-express/server"; // import the Render method and all the simple routing components 

Render(
  <Server listen port={2345 /* the port we want to listen on */}>
    <Route path={"/" /* the path we cant to handle requests from */} get={(req, res) => res.send("hello world") /* send "hellow world" response to every request at "http://localhost:2345/" */} />
  </Server>

and that's it, we just created an hello-world HTTP/s server.

more advance routing:

...
import {..., Router } from "@react-express/server"; // import the Router component

const posts = ["hello", "world 🗺"];

// applay middlewares
const use = (app) => {
  app.use(express.json(), express.urlencoded({ extended: true }));
};

Render(
  <Server listen port={2345}>
    <Router reference={use} path="/posts">
      <Route path="/" get={(req, res) => res.send(posts) /* get all posts*/} />
      <Route
        path="/:id"
        get={(req, res) => res.send(posts[req.params.id])}
        delete={(req, res) => posts[req.params.id] = "empty"}
        />
    </Router>
  </Server>

and just because it's now possible - rendering react components to the client:

...
import {..., ReactRoute } from "@react-express/server"; // import the Render method and all the simple routing components 

const posts = ["hey", "bey", "hello", "world 🗺"];

// applay middlewares
...

Render(
  <Server listen port={2345 /* the port we want to listen on */}>
    <Router reference={use} path="/posts">
      <ReactRoute >{
         () => (
           {posts.map((post, index) => (
             <li
              style={{
                color: `#${Math.floor(Math.random() *16777215).toString(16)}`,
                     }}
                key={index}
            >
               <h1>{post}</h1>
            </li>
          ))}
         )}
      </ReactRoute>
      <Route
        path="/:id"
        get={(req, res) => res.send(posts[req.params.id])}
        delete={(req, res) => posts[req.params.id] = "empty"}
        />
    </Router>
  </Server>

result:
the first full-stack react app :)

☯ contribute or just check out the repo

if you also find the idea of writing servers in React fascinating, feel free to check out the repo at

GitHub logo shmuelhizmi / react-express

create reactive node express servers using react!

react-express

create reactive node express servers using react!

Example code

import React from "react";
import express, { RequestHandler, Application } from "express";
import {
  Server,
  Route,
  Render,
  Router,
  ReactRoute,
} from "@react-express/server";
import * as path from "path";
const helloWorldJson: RequestHandler = (req, res) => {
  res.send({ hello: "world" });
};
const posts = ["hey", "bey", "hello", "world 🗺"];
const post: RequestHandler = (req, res) => {
  const newPost = req.body.post;
  if (newPost && typeof newPost === "string") {
    posts.push(newPost);
  }
  return res.send(JSON.stringify(posts));
};
const use = (app: Application)

the code base is pretty small and simple so if you want to contribute you can also feel free to open up a pull request :)

Posted on by:

shmuelhizmi profile

shmuelhizmi

@shmuelhizmi

A 16 years old full-stack web developer.

Discussion

markdown guide
 

Ha, this is awesome! I've thought about this exact perspective, but haven't ever found time to explore it.

How will it work with "dynamic" React. Ie., if you add state and props, and changes the JSX structure based on that, like you would in a regular React application? would it work, or would it break?

 

Hook and state should work just fine, but I won't be surprise if there are currently still some bug you can encounter while using them.

 

Wow, this is very... interesting. I couldn't have imagined JSX to be used like this. I applaud you for that. 👏

Yet, everything feels... strange. Perhaps I am just unfamiliar with React's idioms, but the HTML-like syntax seems a bit out of place for a back-end application.

But still, this is quite impressive.

 

Awesome sorcery. So this is rendered on the server, right? What is the performance like?

 

the performance should be relatively similar to an express server since this is just a warp of express, as for the react server side rendering it is using the react-dom/server renderer which is quite fast!