DEV Community

Cover image for Introduction to Inertia.js
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

Introduction to Inertia.js

Written by Anjolaoluwa Adebayo-Oyetoro✏️

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

LogRocket Free Trial Banner

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.

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, Laravel on the backend, and React, Vue.js, 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
Enter fullscreen mode Exit fullscreen mode

Or create with composer:

composer create-project --prefer-dist laravel/laravel inertia-example
Enter fullscreen mode Exit fullscreen mode

cd into the project:

$ cd inertia-example
Enter fullscreen mode Exit fullscreen mode

Install Inertia’s server-side adapter using composer:

composer require inertiajs/inertia-laravel
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.


Plug: LogRocket, a DVR for web apps

 
LogRocket Dashboard Free Trial Banner
 
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
Try it for free.


The post Introduction to Inertia.js appeared first on LogRocket Blog.

Top comments (0)