vite-plugin-pwa use custom fetch interceptor for '/api' routes

629 views Asked by At

I would like to develop a Vue Progressive Web App which uses the stock standard features of vite-plugin-PWA for all requests sent to any path other than those beginning with '/api/'. However for requests going to a path starting with '/api', I would like to handle it with code which uses the IndexedDB api. I would also like to hook into the install event of the serviceworker. If I were to be writing my own service worker, I would use something like:

let db:Dexie | null  = null;

self.addEventListener('install', (event) => {
  try {
    db = new Dexie("FrenemyDatabase");
    db.version(1).stores({
      friends: `id,name,age`,
      enemies: `id,name,age`
    });
    event.waitUntil(db.open())
  } catch(e) {
    event.waitUntil(Promise.reject(e))
  }
});

What would I put in the 'vite.config.ts' file plugins.vitePWA options, and what would a simple function look like, which kept all the functionality of vite-PWA-plugin for all non /api paths, but provide my an additional function to the service worker 'install' event and a replacement function for fetch requests to '/api' paths?

1

There are 1 answers

0
Wolf Utz On

Its maybe not exactly what you have asked for, but you can add your own service worker fairly easy by doing the following:

Inside your vite.config.js:

//...
export default defineConfig({
  plugins: [
    VitePWA({
      //...
      workbox: {
        importScripts: ["my-custom-sw.js"],
        //...
      },
    }),
  ],
  //...
});

Be aware that the service worker script my-custom-sw.js has to reside in your public folder.