Skip to content

Instantly share code, notes, and snippets.

@benjick
Created June 18, 2019 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjick/b60dedb6dad35ef711b327cc42bfdb30 to your computer and use it in GitHub Desktop.
Save benjick/b60dedb6dad35ef711b327cc42bfdb30 to your computer and use it in GitHub Desktop.
Wanted to intercept and force a storeCode in Vue Storefront
import { Route } from 'vue-router'
import store from '@vue-storefront/core/store'
import { isServer } from '@vue-storefront/core/helpers'
import { storeCodeFromRoute, localizedRoute } from '@vue-storefront/core/lib/multistore'
import Vue from 'vue'
export function beforeEach(to: Route, from: Route, next) {
if (isServer) {
const { storeViews } = store.state.config
const storeCode = storeCodeFromRoute(to)
if (storeViews.multistore && (storeViews.forcePrefix || true) && !storeCode) {
const { request: req, response: res } = Vue.prototype.$ssrRequestContext.server
const cfCountry = req.headers.http_cf_ipcountry
console.log('cfCountry', cfCountry)
if (cfCountry && storeViews[cfCountry]) {
console.log(from, to, cfCountry)
const newUrl = localizedRoute(to, cfCountry)
console.log('newUrl', newUrl)
return res.redirect(newUrl)
}
if (storeViews.fallbackStoreCode) {
const newUrl = localizedRoute(to, storeViews.fallbackStoreCode)
console.log('newUrl', newUrl)
return res.redirect(newUrl)
}
const lastResort: any = Object.values(storeViews).find((view: any) => view && view.storeCode)
const newUrl = localizedRoute(to, lastResort.storeCode)
console.log('newUrl', lastResort, newUrl)
return res.redirect(newUrl)
}
next()
} else {
next()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment