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.
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.
Inertia solves many problems developers face when building modern applications. Problems like:
remember
, preserveState
, and preserveScroll
properties to cache local component statesInertia 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.
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.
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).
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.
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.
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.
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.
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)
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.
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.
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 — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
4 Replies to "Introduction to Inertia.js"
and it’s the https://github.com/Nothing-Works/inertia-aspnetcore Asp.net adapter.
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
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.
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.