Skip to content

Instantly share code, notes, and snippets.

@Kolobok12309
Last active September 1, 2022 11:24
Show Gist options
  • Save Kolobok12309/bee89f80e14814a4080fa5ba2aa2a7ad to your computer and use it in GitHub Desktop.
Save Kolobok12309/bee89f80e14814a4080fa5ba2aa2a7ad to your computer and use it in GitHub Desktop.
Nuxtjs webcache fix
export default {
...
buildModules: [
[ // 1
'@nuxtjs/router',
{
path: 'configs',
keepDefaultRouter: true,
},
],
],
...
}
import Router from 'vue-router';
const cacheUrlMatchers = [
{
hostname: 'yandexwebcache.net',
pathname: '/yandbtm',
},
{
hostname: 'webcache.googleusercontent.com',
pathname: '/search',
},
];
// Check if fullUrl is cache resource
const isCachedUrl = (fullUrl = '') => {
if (process.server) return null;
const url = new URL(fullUrl);
return cacheUrlMatchers
.some(({ hostname, pathname }) =>
url.hostname === hostname && url.pathname === pathname
);
};
export function createRouter(ssrContext, createDefaultRouter, routerOptions, config) {
const defaultRouter = createDefaultRouter(ssrContext, config);
const options = routerOptions || defaultRouter.options;
// Check for current location is cache
const isCache = process.client && isCachedUrl(window.location.href); // 2
// Change mode if we in cache, to prevent "Uncaught DOMException"
const mode = isCache // 3
? 'abstract'
: options.mode;
const resultOptions = {
...options,
mode,
};
const router = new Router(resultOptions); // 4
// Set nuxt replaced methods
router.push = defaultRouter.push;
// Set init route in cache
if (isCache) {
const origRouterResolve = router.resolve.bind(router);
// Get fullpath of original page
const { route } = window.__NUXT__.state; // 5
const { fullPath } = route;
// Mock first resolve call
router.resolve = () => { // 6
// Unmock all others
router.resolve = origRouterResolve;
return origRouterResolve(fullPath);
};
}
return router;
}
@Kolobok12309
Copy link
Author

Npm package vue-router-webcache

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment