Avoid This Common Anti-Pattern in Full-Stack Vue/Laravel Apps
Avoid This Common Anti-Pattern in Full-Stack Vue/Laravel Apps
In this post, we'll look at a design pattern that makes it easy to inject initial application state into the head of the HTML page, and allows for a lot of flexibility.
Join the DZone community and get the full member experience.Join For Free
If you want your Vue.js single-page app to communicate with a Laravel backend, you will, quite reasonably, think of using AJAX. Indeed, Laravel comes with the Axios library loaded in by default.
However, it's not advisable to use AJAX to retrieve application state on the initial page load, as it requires an extra round-trip to the server that will delay your Vue app from rendering.
I see many full-stack Vue/Laravel apps architected in this way. An alternative to this anti-pattern is to inject initial application state into the head of the HTML page so it's available to the app as soon as it's needed. AJAX can then be used more appropriately for subsequent data fetches.
Using this approach can get messy, though, if your app has different routes requiring different initial state. In this article, I'll demonstrate a design pattern that makes it very simple to implement this injection approach, and allows for a lot of flexibility, even in multi-route apps.
As you'll shortly see, an example app I created is interactive 25% sooner when implementing this design pattern.
You may also like: The Eight Biggest Laravel Development Mistakes You Can Easily Avoid.
Passing Data to Vue From Laravel
Here's an example full-stack Vue/Laravel app I built for Oldtime Cars, a fictitious vintage car retailer. The app has a front page, which shows available cars, and a generic detail page, which shows the specifics of a particular model.
This app uses Vue Router to handle page navigation. Each page needs data from the backend (e.g. the name of the car model, the price, etc.), so a mechanism for sending it between Vue and Laravel is required. The standard design pattern is to setup API endpoints for each page in Laravel, then use Vue Router's
beforeRouteEnter hook to asynchronously load the data via AJAX before the page transitions.
The problem with such an architecture is that it gives us this sub-optimal loading process for the initial page load:
Eliminating the AJAX request here would make the page interactive much sooner, especially on slow internet connections.
Injecting Initial Application State
If we inject the initial application state into the HTML page, Vue Router won't need to request it from the server, as it will already be available in the client.
We can implement this by JSON-encoding the state server-side and assigning it to a global variable:
It is then trivial for the app to access and use the state:
This approach eliminates the need for an AJAX request, and reduces the initial app loading process to this:
I've supplied Lighthouse reports at the bottom of the article to show the improvement in load time.
Note: this approach won't be appropriate if the initial application state includes sensitive data. In that case, you could perhaps do a "hybrid" approach where only non-sensitive data is injected into the page and the sensitive data is retrieved by an authenticated API call.
Implementation in a Multi-Route App
This approach is good enough as-is in an app with only a single route, or if you're happy to inject the initial state of every page within each page requested. But Oldtime Cars has multiple routes, and it'd be much more efficient to only inject the initial state of the current page.
This means we have the following problems to address:
- How can we determine what initial state to inject into the page request since we don't know what page the user will initially land on?
- When the user navigates to a different route from within the app, how will the app know whether or not it needs to load new state or just use the injected state?
But route changes from the browser, e.g. the URL bar, or links to the app from external pages, cannot be intercepted by Vue Router and will result in a fresh page load.
Core Concept of the Design Pattern
With that in mind, we need to ensure that each page has the required logic to get its data from either an injection into the page, or via AJAX, depending on whether the page is being loaded freshly from the server, or by Vue Router.
Implementing this is simpler than it sounds, and is best understood through demonstration, so let's go through the code of Oldtime Cars and I'll show you how I did it.
You can see the complete code in this GitHub repo.
As the site has two pages, there are two different routes to serve: the home route, and the detail route. The design pattern requires that the routes be served either views, or as JSON payloads, so I've created both web and API routes for each:
I've abbreviated some of the code to save space, but the main idea is this: the web routes return a view with the initial application state injected into the head of the page (the template is shown below), while the API routes return exactly the same state, only as a payload.
(Also note that in addition to the state, the data includes a
path. I'll need this value in the frontend, as you'll see shortly).
I'm using the same template for each page. Its only notable feature is that it will encode the state as JSON in the head:
The frontend of the app uses a standard Vue Router setup. I have a different component for each page, i.e. Home.vue and Detail.vue.
Note that the router is in history mode because I want each route to be treated separately.
There's very little going on in the page components. The key logic is in a mixin which I'll show next.
This mixin needs to be added to all the page components, in this case, Home and Detail. Here's how it works:
- Adds a
beforeRouteEnterhook to each page component. When the app first loads, or whenever the route changes, this hook is called. It, in turn, calls the
getDatamethod loads the injected state and inspects the
pathproperty. From this, it determines if it can use the injected data, or if it needs to fetch new data. If the latter, it requests the appropriate API endpoint with the Axios HTTP client.
- When the promise returned from
beforeRouteEnterhook will use whatever data is returned, and assign it to the
dataproperty of that component.
By implementing this mixin, the page components have the required logic to get their initial state from either the data injected into the page, or via AJAX, depending on whether the page loaded from the server, or was navigated to/from Vue Router.
Performance Improvements for Oldtime Cars
I've generated some reports on the app performance using the Lighthouse Chrome extension.
If I skip all of the above and go back to the standard pattern of loading the initial application state from the API, the Lighthouse report is as follows:
One metric of relevance is the time to first meaningful paint, which here is 2570 ms.
Let's compare this to the improved architecture:
By loading the initial application state from within the page rather than from the API, the time to first meaningful paint went down to 2050 ms, a 25% improvement.
Published at DZone with permission of Anthony Gore , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.