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

Kolobok12309 commented Aug 9, 2021

How it works? / Как это работает?

  1. We create our router by @nuxtjs/router / Мы создаем свой роутер с помощью @nuxtjs/router
  2. Check if we in cache (line 31) / Проверяем в кеше ли текущее приложение (строка 31)
  3. If in cache, change router mode to abstract, to prevent error while routing / Если приложение в кеше, меняем режим роутера на abstract, дабы не было ошибки при переходах
Uncaught DOMException: Failed to execute 'replaceState' on 'History': A history state object with URL 'https://example1.com/' cannot be created in a document with origin 'https://example.com' and URL 'https://example.com/'.
  1. Create router and replace default vue-router push for nuxt patched / Создать роутер и подменить дефолтный vue-router push на пропатченный накстом
  2. If we in cache, get real fullPath of current page, for example i use vuex-router-sync and has fullPath in window.__NUXT__.state.route.fullPath / Если мы в кеше, получаем реальный fullPath текущей страницы, для примера я использую vuex-router-sync и могу получить fullPath из window.__NUXT__.state.route.fullPath
  3. Mock first call of router.resolve to prevent nuxt use window.location / Мокаем первый вызов router.resolve, чтобы nuxt не использовал window.location

@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