Anjolaoluwa Adebayo-Oyetoro Maker. Writes sometimes. playful most times. loves beautiful UIs

Introduction to Inertia.js

4 min read 1387

Building web applications can be a very daunting process. You have to think about if it will be a traditional server-side rendered app(SSR) or a single page application(SPA) before proceeding to pick from the many frameworks and libraries.

While both server-side and client-side rendering have their pros and cons, Inertia combines the best of both worlds.

What is Inertia.js?

Inertia is a library that combines the best of both server-side rendering (SSR) and client-side rendering (CSR) by allowing developers to build SPAs using server-side routing and controllers.

According to its official documentation:

Inertia is a new approach to building classic server-driven web apps. We call it the modern monolith.  Inertia allows you to create fully client-side rendered, single-page apps, without much of the complexity that comes with modern SPAs. It does this by leveraging existing server-side frameworks.

Some might be asking is this another JavaScript framework? The documentation has this to say:

Inertia isn’t a framework, nor is it a replacement to your existing server-side or client-side frameworks. Rather, it’s designed to work with them. Think of Inertia as glue that connects the two.

The problem Inertia.js solves

Inertia solves many problems developers face when building modern applications. Problems like:

  • SPA complexities — building modern SPAs comes with some hassles. Developers have always had problems with effectively managing the state for the app, figuring routing for the app, setting up navigation guards, and authentication
  • Building APIs — With Inertia.js you don’t need to build a REST or GraphQL API, because Inertia was created to work out of the box with your classic server-side frameworks such as Laravel, Ruby on Rails, or Django
  • Browser issues — Inertia has built-in services that solve browser issues faced when building SPAs, issues such as:
    • Browser history management and scroll position — it provides remember , preserveState, and preserveScroll properties to cache local component states
    • Loading indication — because Inertia requests are made via AJAX calls there’s no default browser loading indicator, so Inertia includes NProgress.js, a progress bar library. The loading indicator is only shown if a request takes longer than 250m
    • Assets reloading and versioning — Inertia provides an option to track and store the current version of assets on your website

Why should you use Inertia.js?

GraphQL benefits without using GraphQL

Inertia gives full access to run specific queries on a database to get the data needed for a page while using your server-side ORM as a data source.

Limited AJAX calls

In traditional SPAs, AJAX calls are made on every page visit to fetch data. In Inertia, an AJAX call is made to boot up the app then it maintains a persistent Vue.js instance and every subsequent page visits are made via XHR with a special X-Inertia header set to true. This triggers the server sending an Inertia response as JSON rather than making a full-page visit.

It also creates a fail-safe component that wraps around a standard anchor link, it intercepts click events and prevents full page reloads from occurring.

Security

When building API-powered apps, we have to add CORS support to our app to be able to access resources on other origins.

We made a custom demo for .
No really. Click here to check it out.

With Inertia you don’t have to worry about setting up CORS since your data is provided via your controllers and housed on the same domain as your JavaScript components.

You can set up authorization on the server-side and perform authorization checks bypassing tokens as props to your page components, this helps reduce the risk of exposing important information because handling authorizations on the client can put one at the risk of an XSS attack (cross-site scripting).

Framework agnostic

Inertia is both server-side and client-side framework agnostic. You can use Inertia with any server-side framework as well as any client-side framework that supports dynamic components.

Inertia adapters are services(packages) that help make Inertia work well with specific frameworks. Official adapter support is currently limited to Rails and Laravel on the backend, and React, Vue.js, and Svelte on the frontend.

There are unofficial adapters for some other frameworks, such as Symfony, Django, CakePHP, and Adonis.

Is there a future for Inertia?

The web is forever evolving and we’ve seen a transition from traditional server-side built monolith apps to API-powered apps. With this current trend is there a future for Inertia?

Of course, the answer to the question depends on the use case and preferences.

Inertia is built for people who want to build monolith applications — they generally prefer the tight coupling between their controllers and their views, but also want to build their apps using modern client-side frameworks. A majority of developers still fall into this category but with the rise and industry support for API-powered apps, we might see its usage dwindle.

Of course, there are times when using Inertia might not be the best fit. Situations such as when you need multi-client support, customer-facing/marketing pages, and SEO driven websites. Using Inertia for these is probably not a good idea. But it is perfectly useful to build web apps that power dashboards and the likes.

Is server-side rendering possible with Inertia?

Inertia does not currently support server-side rendering but there are tools to pre-render Inertia websites, they generate and cache static HTML versions of specific routes of your websites, and then serve that content.

Get started with using Inertia.js in your project

Prerequisites

This installation process makes use of Laravel for the server-side and Vue.js for the client-side, the following is required to follow along with this section:

Create a new Laravel project:

laravel new inertia-example

Or create with composer:

composer create-project --prefer-dist laravel/laravel inertia-example

cd into the project:

$ cd inertia-example

Install Inertia’s server-side adapter using composer:

composer require inertiajs/inertia-laravel

Rename the welcome.blade.php file found in your resources/views folder to app.blade.php.

Replace the content of your app.blade.php with this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <link href="{{ mix('/css/app.css') }}" rel="stylesheet" />
    <script src="{{ mix('/js/app.js') }}" defer></script>
  </head>
  <body>
    @inertia
  </body>
</html>

The @inertia directive is a helper that creates a base div with an id of app that contains the page information, it tells Laravel that the views are generated using Inertia.

Next, set up the client-side adapter by running this command in your terminal:

npm install @inertiajs/inertia @inertiajs/inertia-vue

#or, Using Yarn

yarn add @inertiajs/inertia @inertiajs/inertia-vue

Open your app.js file found in resources/js and replace the content of your app.js file with the following:

import { InertiaApp } from '@inertiajs/inertia-vue'
import Vue from 'vue'

Vue.use(InertiaApp)

const app = document.getElementById('app')

new Vue({
  render: h => h(InertiaApp, {
    props: {
      initialPage: JSON.parse(app.dataset.page),
      resolveComponent: name => require(`./Pages/${name}`).default,
    },
  }),
}).$mount(app)

The resolveComponent callback tells Inertia how to load a page component. It receives a string as a page name and returns a page instance.

Dynamic imports

To enable code-splitting we use a babel plugin for dynamic imports.

First, install it by running this command:

npm install @babel/plugin-syntax-dynamic-import
#or, Using Yarn
yarn add install @babel/plugin-syntax-dynamic-import

Next, create a .babelrc file in your projects root directory with the following:

{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}

Finally, update the resolveComponent callback in your app initialization to use import instead of require. The callback returns a promise that includes a component instance, like this:

......

new Vue({
  render: h => h(InertiaApp, {
    props: {
      initialPage: JSON.parse(app.dataset.page),
      resolveComponent: name => import(`./Pages/${name}`).then(module => module.default),
    },
  }),
}).$mount(app)

Conclusion

Inertia is a great library for building “hybrid” SPAs. In this article, we’ve looked at its viability in the nearest future, the advantage it has, and how to use it in a Laravel and Vue project.

Checkout Inertia on Github and this article written by Jonathan Reinink to learn more. The official documentation is also well written and is an excellent resource to get started with.

You come here a lot! We hope you enjoy the LogRocket blog. Could you fill out a survey about what you want us to write about?

    Which of these topics are you most interested in?
    ReactVueAngularNew frameworks
    Do you spend a lot of time reproducing errors in your apps?
    YesNo
    Which, if any, do you think would help you reproduce errors more effectively?
    A solution to see exactly what a user did to trigger an errorProactive monitoring which automatically surfaces issuesHaving a support team triage issues more efficiently
    Thanks! Interested to hear how LogRocket can improve your bug fixing processes? Leave your email:

    Are you adding new JS libraries to improve performance or build new features? What if they’re doing the opposite?

    There’s no doubt that frontends are getting more complex. As you add new JavaScript libraries and other dependencies to your app, you’ll need more visibility to ensure your users don’t run into unknown issues.

    LogRocket is a frontend application monitoring solution that lets you replay JavaScript errors as if they happened in your own browser so you can react to bugs more effectively.

    https://logrocket.com/signup/

    LogRocket works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting metrics like client CPU load, client memory usage, and more.

    Build confidently — .

    Anjolaoluwa Adebayo-Oyetoro Maker. Writes sometimes. playful most times. loves beautiful UIs

    4 Replies to “Introduction to Inertia.js”

    1. Hi, thanks for your analysis! When you write : “Of course, there are times when using Inertia might not be the best fit. Situations such as when you need multi-client support”, what type of multi-client support scenario are you referring to? Thank you

    2. I believe he is talking about building an app that may require multiple clients, i.e. you need both a web app and a mobile app. Then it may be better to build a stand-alone api that you use in both clients.

    3. In my opinion, that shouldn’t be a limitation since Laravel support API routes. One can have a monolith web application and still support other application types.

    Leave a Reply