reactjsprogressive-web-appsviteworkboxvite-plugin-pwa

React + Vite + VitePWA plugin workbox configurations


I'm trying to cache some url in order to have my app working offline.

I'm using vite 5.0.5 vite-plugin-pwa 0.17.3

and here is my vite.config.js

import react from '@vitejs/plugin-react';
import postcssNested from 'postcss-nested';
import { defineConfig } from 'vite';
import svgrPlugin from 'vite-plugin-svgr';
import { VitePWA } from 'vite-plugin-pwa';

export default defineConfig({
  build: {
    sourcemap: true, //@todo false in prod
  },
  plugins: [
    react(),
    svgrPlugin(),
    VitePWA({
      strategies: 'generateSW',
      registerType: 'autoUpdate',
      mode: 'development',
      workbox: {
        globPatterns: ['**/*.{js,jsx,css,html,png,svg,woff2,json}'],
        runtimeCaching: [
          {
            urlPattern: /\/api\//,
            handler: 'StaleWhileRevalidate',
            method: 'GET',
            options: {
              cacheName: 'api-cache',
              cacheableResponse: {
                statuses: [0, 200],
              },
            },
          },
        ],
      },
      devOptions: {
        enabled: true,
      },
      manifest: {
        name: 'AppName',
        short_name: 'AppName',
        description: 'App description',
        theme_color: '#ffffff',
        icons: [
          {
            src: '/manifestIcons/maskable_icon_x1024.png',
            sizes: '1024x1024',
            type: 'image/png',
            purpose: 'any maskable',
          },
        ],
      },
    }),
  ],
  css: {
    postcss: {
      plugins: [postcssNested],
    },
  },
  server: {
    port: 3000,
    open: true,
    host: true,
  },
});


But it seems that it doesn't work, there's only 1 entry in the cache : enter image description here

Why my "api-cache" doesn't show ?

I DO have a status 200 request including /api/ :

enter image description here

And I can see this in the sw.js :

enter image description here


Solution

  • For anyone experiencing the same problem it has been solved HERE

    The problem was that with "only" urlPattern: /regexp/ workbox won't cache CORS calls if the regexp pattern doesn't match your WHOLE url !

    Then you'll have to either

    urlPattern: ({ url, sameOrigin }) => sameOrigin && url.pathname.match(/^\/api\//),