-
-
Save coaperator/cdbc017d45e1f300b1650b9e6cdaa342 to your computer and use it in GitHub Desktop.
Nuxtjs webcache fix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
... | |
buildModules: [ | |
[ // 1 | |
'@nuxtjs/router', | |
{ | |
path: 'configs', | |
keepDefaultRouter: true, | |
}, | |
], | |
], | |
... | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment