I'm using GTM in my next.js app and I'm using next-offline which uses workbox-webpack-plugin internally for offline support is it a good idea to use runtime caching staleWhileRevalidate
strategy to cache gtm.js ?
My app works offline and it saves analytics offline and send them when back online by importing this script:
// Initialize offline google analytics which will store failed analytics requests and try again later when connection is back
// it will also cache the analytics.js library
workbox.googleAnalytics.initialize({
// using a custom dimension(cd1) to track online vs. offline interactions
parameterOverrides: {
cd1: "offline"
},
// Using a custom metric to track time requests spent in the queue
hitFilter: params => {
const queueTimeInSeconds = Math.round(params.get("qt") / 1000);
params.set("cm1", queueTimeInSeconds);
}
});
Let's say the user on the second visit opened my home page i use runtime cache with networkFirst strategy to cache html, so if the user revisited my home page again while he is totally offline he will get a fully working app especially that i use the same networkFirst runtime caching strategy to cache the api requests, But while totally offline the request to fetch gtm.js will return 404 and the analytics won't work offline because gtm.js won't init the request to fetch analytics.js which will be served from workbox cache. My idea was to use staleWhileRevalidate strategy to cache gtm.js so the offline analytics works even if the user opens the app in offline mode and if he went back online those analytics will be resent by workbox.
Is this a good idea ? will it work as expected or there is something i'm missing ?
I'm not familiar with gtm.js
, but workbox-google-analytics
will automatically create an appropriate runtime caching route to handle offline access to the analytics.js
and gtag.js
scripts for you:
Workbox Google Analytics does exactly this. It also also adds fetch handlers to cache the
analytics.js
andgtag.js
scripts, so they can also be run offline. Lastly, when failed requests are retried Workbox Google Analytics also automatically sets (or updates) theqt
in the request payload to ensure timestamps in Google Analytics reflect the time of the original user interaction.
It sounds like gtm.js
is loaded from a different URL than gtag.js
and might have a different syntax for its collection pings, so filing a feature request in the Workbox GitHub repo asking for gtm.js
support sounds like your best bet.