Runtime caching for APIs, in Vue, Vite PWA plugin seems not working?

488 Views Asked by At

I've add PWA plugin in my Vuejs project, with Vite. I made the precaching but when I tried to make runtime caching for API request, it doesn't work. The runtime cache file doesn't appear and no runtime caching happens.

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { VitePWA } from 'vite-plugin-pwa'



// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    VitePWA({
      manifest: {
        icons: [
          {
            src: "./SmallTile.scale-400.png",
            sizes: "284x284",
            type: "image/png",
            purpose: "any maskable",

          }
        ]
      },
      workbox: {        
        runtimeCaching: [{
          urlPattern: "https:\\/\\/openweathermap\\.org\\/api\\/.*",
          handler: "NetworkFirst",
          options: {
            cacheName: "api-cache",
            cacheableResponse: {
              statuses: [0, 200] 
            }
          }
        }]
      }
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

I tried to change the url pattern but i couldn't fine a good solution

1

There are 1 best solutions below

0
Moshe Quantz On

That's because the default caching of Workbox takes precedence and overwrites your api runtimeCaching

So you need to tell Workbox to not cache API requests by default

Like so:

workbox: {        
  navigateFallbackDenylist: [/^\/api/], // every route that starts with /api will not use the fallback
  runtimeCaching: [{
    urlPattern: /^https:\/\/openweathermap\.org\/api/,
    handler: 'NetworkFirst',
  }]
}