Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use runtimeCaching ? Can't cache API resquests #626

Closed
seba9999 opened this issue Dec 20, 2023 · 8 comments
Closed

How to use runtimeCaching ? Can't cache API resquests #626

seba9999 opened this issue Dec 20, 2023 · 8 comments

Comments

@seba9999
Copy link

seba9999 commented Dec 20, 2023

Here is my vite.config.js

export default defineConfig({
  build: {
    sourcemap: true, //@todo false in prod
  },
  plugins: [
    react(),
    svgrPlugin(),
    VitePWA({
      strategies: 'generateSW',
      registerType: 'autoUpdate',
      workbox: {
        globPatterns: ['**/*.{js,jsx,css,html,png,svg,woff2,json}'],
        runtimeCaching: [
          {
            urlPattern: /\/api\/.*/,
            handler: 'StaleWhileRevalidate',
            method: 'GET',
            options: {
              cacheName: 'api-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365, // <== 365 days
              },
              cacheableResponse: {
                statuses: [0, 200],
              },
            },
          },
        ],
      },
      devOptions: {
        enabled: true,
      },
      manifest: {
        name: 'AppName',
        short_name: 'AppName',
        description: 'App description',
        theme_color: '#ffffff',
        lang: 'fr',
        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,
  },
});

I'm just trying to cache the call to my API ( /api/* )

But I've tried a lot of variations of this config (with or without registerType: autoUpdate and differents handlers for the runtimeCaching ( 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate' ) ... ) And none works

What am I doing wrong ? Do I need to run vite build && vite preview to see the working service worker ? Or 'just' with the developement version ( vite ) it should also work ?

Here is the sw.js generated
import {registerRoute as workbox_routing_registerRoute} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-routing/registerRoute.mjs';
import {ExpirationPlugin as workbox_expiration_ExpirationPlugin} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-expiration/ExpirationPlugin.mjs';
import {CacheableResponsePlugin as workbox_cacheable_response_CacheableResponsePlugin} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-cacheable-response/CacheableResponsePlugin.mjs';
import {StaleWhileRevalidate as workbox_strategies_StaleWhileRevalidate} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-strategies/StaleWhileRevalidate.mjs';
import {clientsClaim as workbox_core_clientsClaim} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-core/clientsClaim.mjs';
import {precacheAndRoute as workbox_precaching_precacheAndRoute} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-precaching/precacheAndRoute.mjs';
import {cleanupOutdatedCaches as workbox_precaching_cleanupOutdatedCaches} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-precaching/cleanupOutdatedCaches.mjs';
import {NavigationRoute as workbox_routing_NavigationRoute} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-routing/NavigationRoute.mjs';
import {createHandlerBoundToURL as workbox_precaching_createHandlerBoundToURL} from 'D:/Sebastien/PROJECTS/Re8/front/node_modules/workbox-precaching/createHandlerBoundToURL.mjs';/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app.
* See https://goo.gl/nhQhGp
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
* See https://goo.gl/2aRDsh
*/








self.skipWaiting();

workbox_core_clientsClaim();


/**
* The precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
workbox_precaching_precacheAndRoute([
{
  "url": "assets/index--cHlt1Zo.js",
  "revision": null
},
{
  "url": "assets/index-Av8r0MF4.css",
  "revision": null
},
{
  "url": "assets/Normal-300-2-w6l85u1H.woff2",
  "revision": null
},
{
  "url": "assets/Normal-300-3-RcD-_CWN.woff2",
  "revision": null
},
{
  "url": "assets/Normal-300-bnnqODGJ.woff2",
  "revision": null
},
{
  "url": "assets/Normal-400-1-boqxu89h.woff2",
  "revision": null
},
{
  "url": "assets/Normal-400-3-MIIzDciT.woff2",
  "revision": null
},
{
  "url": "assets/Normal-400-4-DTXwejLd.woff2",
  "revision": null
},
{
  "url": "assets/Normal-700-1-ONdCoQol.woff2",
  "revision": null
},
{
  "url": "assets/Normal-700-3-aJuvpNbu.woff2",
  "revision": null
},
{
  "url": "assets/Normal-700-4-qfYrlmMj.woff2",
  "revision": null
},
{
  "url": "assets/workbox-window.prod.es5-prqDwDSL.js",
  "revision": null
},
{
  "url": "dev.svg",
  "revision": "55c1105458878ab968348a3d1fd9adb6"
},
{
  "url": "index.html",
  "revision": "b70d4a2334c94948c21397ee66a65129"
},
{
  "url": "manifestIcons/maskable_icon_x1024.png",
  "revision": "1d70b6c1484718e9d04d68c32cbe18f6"
},
{
  "url": "manifestIcons/maskable_icon_x120.png",
  "revision": "bbda173aa34515edb3ad74602333a844"
},
{
  "url": "manifestIcons/maskable_icon_x180.png",
  "revision": "aeafbf920cb6398a8e525ac4312819b8"
},
{
  "url": "manifestIcons/maskable_icon_x192.png",
  "revision": "4f473e08f0b646cb6eccf2f9f0dcc50c"
},
{
  "url": "manifestIcons/maskable_icon_x512.png",
  "revision": "20f49f605f7154eb09b3254dc6205e6d"
},
{
  "url": "manifestIcons/maskable_icon_x192.png",
  "revision": "4f473e08f0b646cb6eccf2f9f0dcc50c"
},
{
  "url": "manifestIcons/maskable_icon_x512.png",
  "revision": "20f49f605f7154eb09b3254dc6205e6d"
},
{
  "url": "manifestIcons/maskable_icon_x1024.png",
  "revision": "1d70b6c1484718e9d04d68c32cbe18f6"
},
{
  "url": "manifest.webmanifest",
  "revision": "97edd27b1e51efd8925a1e02651267af"
}
], {});
workbox_precaching_cleanupOutdatedCaches();
workbox_routing_registerRoute(new workbox_routing_NavigationRoute(workbox_precaching_createHandlerBoundToURL("index.html")));


workbox_routing_registerRoute(/\/api\/.*/, new workbox_strategies_StaleWhileRevalidate({ "cacheName":"api-cache", plugins: [new workbox_expiration_ExpirationPlugin({ maxEntries: 10, maxAgeSeconds: 31536000 }), new workbox_cacheable_response_CacheableResponsePlugin({ statuses: [ 0, 200 ] })] }), 'GET');

Linked SO question (with more screens)

@userquin
Copy link
Member

you need to add the api request to navigateFallbackDenylist workbox option: check this issue vite-pwa/sveltekit#65

@seba9999
Copy link
Author

Thanks for the fasts reply ... I've tried with :

VitePWA({
      strategies: 'generateSW',
      registerType: 'autoUpdate',
      workbox: {
        navigateFallbackDenylist: [/\/api\//],
        globPatterns: ['**/*.{js,jsx,css,html,png,svg,woff2,json}'],
        runtimeCaching: [
          {
            urlPattern: /\/api\//,
            handler: 'StaleWhileRevalidate',
            method: 'GET',
            options: {
              cacheName: 'api-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365, // <== 365 days
              },
              cacheableResponse: {
                statuses: [0, 200],
              },
            },
          },
        ],
      },

And still can't have the cache "api-cache" 😔 only the workbox pre-cache :
image

@userquin
Copy link
Member

workbox needs to create the cache, will not work on first request (cannot create the cache while intercepting the request), try hard page refresh: you will need to switch to custom sw (injectManifest) and warm the cache manually on install event.

@seba9999
Copy link
Author

seba9999 commented Dec 20, 2023

Not sur to understand you 100% ... I've tried a lot of hard refreshs... Still no luck and the call to my api isn't event intercepted ! :

image

Can I do so without some custom code ? With only with vite.config.js...

I'm always doing vite build + vite preview to test that out ... Is it mandatory or should it work in developement ? ( with npm start ( vite ) )

@userquin
Copy link
Member

try adding mode: 'development' to pwa options and run build + preview, you will see some logs in the console

@seba9999
Copy link
Author

I had this mode once but seems to not changed anything, But I didn't have the chrome log level "all" !

I found the error then with a log : For some reason workbox won't cache cross origin if the regex doesn't match the full url ...

Didn't find it in the docs but in some SO comment

I've changed the configuration to :

VitePWA({
      strategies: 'generateSW',
      registerType: 'autoUpdate',
      mode: 'development',
      workbox: {
        globPatterns: ['**/*.{js,jsx,css,html,png,svg,woff2,json}'],
        runtimeCaching: [
          {
            urlPattern: new RegExp(`^${API_URL}\/.*`, 'i'),
            handler: 'StaleWhileRevalidate',
            method: 'GET',
            options: {
              cacheName: 'api-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365, // <== 365 days
              },
              cacheableResponse: {
                statuses: [0, 200],
              },
            },
          },
        ],
      },

The navigateFallbackDenylist is not necessary !

Thanks anyways @userquin your help was very appreciated ♥

@userquin
Copy link
Member

userquin commented Dec 20, 2023

you can also use a callback, for example, to check in same origin, check the docs:

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

@kico-summer
Copy link

hello can you resolved? Iam too same question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants