Preact-rpc is three things packaged into one:
The overall system is quite simple, but lets walk through an example to make things crystal clear.
Assume that our backend is a Go app, and we would like to render React components from there. Lets say we have a simple component like this:
It is a simple component that takes a prop toWhat and prints out a Hello message.
Now lets install the module: npm install preact-rpc
We’ve registered the component Hello with the name ‘hello’. We’ll use this name when we want to send render requests later.
Even though I’ve only used a single component in the example above, you can register as many components as you need. In practice, you’d create a Webpack bundle that includes all the required components.
This will start a server with a UNIX socket. You can use a TCP socket by providing a number for the port command line argument.
After the server starts, it is ready to fulfill component rendering requests. The protocol is very simple. The request is in the form of JSON:
The server expects requests to end in a special sequence of bytes. By default this is defined as: \r\n.
We can now write a client to connect to the server in the language of our choice. You can write this code yourself if you wish, or you could use one of the helper libraries included with preact-rpc. For Go, the package github.com/musawirali/preact-rpc/goclient is included. Here is our Go backend that uses this package to connect to the RPC server started earlier:
Run the app and see our simple Hello component rendered.
In its current state, the preact-rpc package is functional, but still quite minimal. A number of things are in the pipeline to flesh out the system:
Hope this project is helpful to the community. Contributions are welcome!
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!
Level up your reading game by joining Hacker Noon now!