DEV Community

kobaken
kobaken

Posted on

Released an Inertia.js Adapter for Mojolicious

Hi, I'm kobaken.

I've released an adapter for using Inertia.js with Mojolicious, a Perl backend framework. Inertia.js is a bridging library that connects backend frameworks with components written in React, Vue, and other frameworks.

https://github.com/kfly8/Mojolicious-Plugin-Inertia

What is Inertia.js?

Inertia.js is a framework that connects backend frameworks with React or Vue components. It allows you to use modern frontend components while maintaining a traditional backend approach.

I figure this is an approach that fits well when you have substantial assets on the backend side, but replacing everything would be too costly, and you want to start by improving the client-side experience.

When using components written in React, Vue, etc. with backend frameworks like Mojolicious, I believe there are two approaches. One is to mix JavaScript code into the backend framework's proprietary template engine. The other is to call backend APIs and handle rendering with CSR or SSR. Both approaches result in more complex architecture compared to the days when you could simply select a template on the backend and pass values to it.

Classic Approach

With Inertia.js, you can use React and other components while maintaining the good old way of writing code. Specifically, it works as follows: by writing $c->inertia(COMPONENT, PROPS) on the backend side, Inertia.js will connect with the component.

Mojolicious::Plugin::Inertia usage (backend)

Mojolicious::Plugin::Inertia usage (client component)


Inertia.js is the simple protocol

Another point I found appealing is that the protocol for this connection is simple. It's remarkably simple.

For example, if you write it like this...

$c->inertia('Index', {
   user => { name => 'Mojolicious' }
})
Enter fullscreen mode Exit fullscreen mode

It returns this JSON:

{
   "component": "Index",
   "props": { "user": { "name": "Mojolicious" } },
   "url": "/",
   "version": "c53bc3824540ea95b1e9b495c7a01a9d"
}
Enter fullscreen mode Exit fullscreen mode

So straightforward!

In fact, looking at Inertia.js's protocol, it's content you can finish reading in about 10 minutes, and Mojo's plugin is less than 100 lines, so I think it would be easy to port to other Perl frameworks.

Recently, in another project, I made React Server Components usable with Hono, but understanding that in 10 minutes is difficult for me 😅 Since Inertia.js becomes CSR, I think React Server Components is better if you're looking for user experience and SEO, but I believe there are situations where Inertia.js is sufficient.

https://zenn.dev/kfly8/articles/hono-meets-vite-rsc (Japanese)


Please give it a try if you'd like!

Top comments (0)