Caching refers to the process of storing frequently demanded information in a cache so that the content can be accessed quickly. A cache is either hardware or software that temporarily stores frequently used data, improving its memory access time.
There are various methods and tools available for us to use in performing caching for both frontend and backend applications. If you’re a full-stack developer reading this article, you should already be familiar with caching using Redis, an open source, in-memory data store.
In this tutorial, we’ll focus on setting up a frontend cache with Vue and Workbox. To follow along with this article, you’ll need familiarity with the following:
We’ll cover the following:
GenerateSW
moodInjectManifest
moodCaching on the client-side is a very powerful technique for optimizing your app and improving your user experience. The idea of caching a web application’s data in the browser comes from the realization that fetching data from a local cache or browser storage API is more cost-effective than network requests.
Workbox deploys a set of modules and tools that simplify interaction with service workers by handling routing and caching. Workbox is designed to make developing service workers easy while also making room for complex application requirements. Each individual module in Workbox addresses specific functionality with service workers.
Progressive web applications use service workers to provide offline capabilities and boost the page performance of web applications. A typical web application that depends on multiple data sources to display a plethora of content to end-users requires a medium to cache and render information even when the application is in an offline mood.
The Service Worker API has a lot of complex interactions that handle network requests, caching, cache management, pre-caching, and more.
Workbox is an abstraction of the Service Worker API. It’s a set of JavaScript modules where each module handles a specific part of the Service Worker API:
workbox-routing
: Request matchingworkbox-strategies
: Caching strategiesworkbox-precaching
: Pre-cachingworkbox-expiration
: Managing cachesThese modules compose service workers in a declarative manner that makes them easier to read and maintain than directly interacting with the Service Worker API.
As long as performance remains a great concern for software application users, caching will continue to evolve, and more solutions and strategies will emerge. The following are some applications that require caching:
A service worker strategy is a communication between a service worker’s fetch
event and its cache interface. There are five popular service worker strategies that software developers often leverage to make their applications more performant:
To get started, let’s install Vue globally:
npm install -g @vue/cli # OR yarn global add @vue/cli
After the installation is complete, run the code below to confirm the Vue version:
vue --version
Then, create a new Vue project:
vue create vue workbox
Navigate into the newly created workbox
folder and start the project with the command below:
cd vue yarn serve
Add the Workbox plugin for Vue with the following command:
vue add pwa
The command above will install Workbox and all the dependencies required to communicate with Workbox in CDN mood.
Next, update your vue.config.js
file with the code below:
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, pwa: { name: "workbox", themeColor: "#fff3e0", msTileColor: "#fff3e0", appleMobileWbeAppCapable: "yes", appleMobileWebAppStatusBarStyle: "#fff3e0", workboxPluginMode: "InjectManifest", workboxOptions: { swSrc: "./service-worker.js", exclude: [/_redirect/, /\.map$/, /_headers/], }, manifestOptions: { background_color: "#ffe24a", } } })
workbox-webpack-plugin
supports two modes. In the configuration above, we’re setting the workboxPluginMode
to InjectManifest
. The InjectManifest
mood requires that you specify your service-worker
path swSrc
in the workBoxOptions
object. The other option, GenerateSW
, does not require a service.
Notice that we specified the directory for the service worker with the code below:
swSrc: 'src/service-worker.js',
If you intend to write your service-worker
file yourself, you can skip to the Using InjectManifest
section. Otherwise, follow the steps below.
GenerateSW
moodFirst, set the workboxPluginMode
with the code below:
workboxPluginMode: "GenerateSW" // swSrc: "./service-worker.js" comment out this line of code,
Then, build the production version of the app as follows:
yarn build
Once the build is complete, you should have manifest.json
and service-worker.js
added to the /dist
directory. To test the application in a production server, download and install Web Server for Chrome and set the folder to the ./dist
of your application, as seen in the screenshot below:
To view your application, click the URL provided by the web server. Inspect the webpage and navigate to the application. In the frame section, you should already see the images
, script
, and stylesheet
folders. This is an indication that all the web application’s static assets have been pre-cached and would still work even in offline mode:
InjectManifest
moodOpen up service-worker.js
and add the code below:
const { precacheAndRoute } = workbox.precaching; const { registerRoute } = workbox.routing; const { CacheFirst, StaleWhileRevalidate } = workbox.strategies; const { Plugin: ExpirationPlugin } = workbox.expiration; const { Plugin: CacheableResponsePlugin } = workbox.cacheableResponse;
Since Workbox functions from the Workbox CDN v4.3.1, Vue 3 automatically adds the CDN. The code above registers some of the Workbox endpoints that the application depends on to perform caching:
workbox.core.setCacheNameDetails({ prefix: "appname" }); self.addEventListener("message", (event) => { if (event.data && event.data.type === "SKIP_WAITING") { self.skipWaiting(); } }); /** * The workboxSW.precacheAndRoute() method efficiently caches and responds to * requests for URLs in the manifest. */ self.__precacheManifest = [].concat(self.__precacheManifest || []); precacheAndRoute(self.__precacheManifest, {}); // cache image and render from the cache if it exists or go t the network registerRoute( ({ request }) => request.destination === "image", new CacheFirst({ cacheName: "images", plugins: [ new CacheableResponsePlugin({ statuses: [0, 200], }), new ExpirationPlugin({ maxEntries: 60, maxAgeSeconds: 2 * 24 * 60 * 60, // cache the images for only 2 Days }), ], }) );
The code above takes images from the Vue /dist
folder and caches them for two days.
To get a response from the Workbox API, add the code below after the registerRoute
in service-worker.js
:
registerRoute( ({ url }) => url.pathname.startsWith("https://dog.ceo/api/"), new StaleWhileRevalidate() );
We’re using the StaleWhileRevalidate
function to cache the API response and serve it from the cache if it exists or goes to the network. Once you’re satisfied with the service worker, you can follow the instructions from earlier to test the application.
Keep in mind that this is an example service-worker
file. Your service-worker
file can contain only the logic that applies to your use case.
Caching web application assets can improve overall user experience, however, it can also ruin user experience when glitches happen and old web application source code is served to users instead of the most recent cached version. Although it rarely happens, I’ll advise you always confirm that your caching and fallback logic is correct before deployment to avoid such scenarios.
Caching improves the overall performance of our website or application. Once all the assets have been downloaded to a user’s machine, it becomes pretty convenient to show the user a pre-cached version of the website’s content, even in bad network situations.
In this article, we explored using Workbox service workers with Vue to handle routing and caching in our application. We covered what service workers are, when caching is needed, and finally, some potential problems that can arise from caching.
I hope you enjoyed this article, and be sure to leave a comment if you have any questions.
Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps, including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error and what state the application was in when an issue occurred.
Modernize how you debug your Vue apps — 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 nowJavaScript’s Date API has many limitations. Explore alternative libraries like Moment.js, date-fns, and the new Temporal API.
Explore use cases for using npm vs. npx such as long-term dependency management or temporary tasks and running packages on the fly.
Validating and auditing AI-generated code reduces code errors and ensures that code is compliant.
Build a real-time image background remover in Vue using Transformers.js and WebGPU for client-side processing with privacy and efficiency.
One Reply to "Frontend caching in Vue with Workbox service workers"
Nice article thankyou for sharing valuable information….