Introduction to Inertia.js
Tags: inertia, javascript, webdev
Published: 2020-02-05 14:00:12

---
title: Introduction to Inertia.js
published: true
date: 2020-01-31 17:00:24 UTC
tags: inertia,javascript,webdev
canonical_url: https://blog.logrocket.com/introduction-to-inertia-js/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/dz1dsf9ljwtbhsp2yxkr.png
---
**Written by [Anjolaoluwa Adebayo-Oyetoro](https://blog.logrocket.com/author/anjolaoluwaadebayooyetoro/)**✏️

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](https://inertiajs.com/) 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](https://inertiajs.com/):

> 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](https://inertiajs.com/) 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](https://ricostacruz.com/nprogress/), a progress bar library. The loading indicator is only shown if a request takes longer than 250m
  - [Assets reloading and versioning](https://inertiajs.com/asset-versioning) — Inertia provides an option to track and store the current version of assets on your website

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## 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](https://blog.logrocket.com/jwt-authentication-best-practices/) 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](https://github.com/inertiajs/inertia-rails), [Laravel](https://github.com/inertiajs/inertia-laravel) on the backend, and [React](https://github.com/inertiajs/inertia-react), [Vue.js](https://github.com/inertiajs/inertia-vue), [Svelte](https://github.com/inertiajs/inertia-svelte) on the frontend.

There are unofficial adapters for some other frameworks such as [Symfony](https://github.com/rompetomp/inertia-bundle), [Django](https://github.com/jsbeckr/inertia-django), [CakePHP](https://github.com/ishanvyas22/cakephp-inertiajs), and [Adonis](https://github.com/MZanggl/inertia-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](https://code.tutsplus.com/articles/the-increasing-importance-of-apis-in-web-development--net-22368), 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:

- [Node.js 10x](https://nodejs.org/en/download/) or higher and [Yarn](https://yarnpkg.com/lang/en/) / [npm 5.2 or higher installed](https://www.npmjs.com/get-npm) on your PC
- PHP >= 7.2.0, [Composer](https://getcomposer.org/) and [Laravel](https://laravel.com/docs/6.x) installed on your PC
- Basic Vue and Laravel fundamentals

Create a new Laravel project:

```jsx
laravel new inertia-example
```

Or create with composer:

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

`cd` into the project:

```jsx
$ cd inertia-example
```

Install Inertia’s server-side adapter using composer:

```jsx
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:

```jsx
<!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:

```jsx
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:

```jsx
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:

```jsx
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:

```jsx
{
  "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:

```jsx
......

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](https://github.com/inertiajs) and [this article](https://reinink.ca/articles/introducing-inertia-js) written by [Jonathan Reinink](https://reinink.ca/) to learn more. The official [documentation](https://inertiajs.com/) is also well written and is an excellent resource to get started with.

* * * 
## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) 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](https://logrocket.com/signup/).
* * *

The post [Introduction to Inertia.js](https://blog.logrocket.com/introduction-to-inertia-js/) appeared first on [LogRocket Blog](https://blog.logrocket.com).