Created
          June 18, 2019 18:28 
        
      - 
      
- 
        Save benjick/b60dedb6dad35ef711b327cc42bfdb30 to your computer and use it in GitHub Desktop. 
    Wanted to intercept and force a storeCode in Vue Storefront
  
        
  
    
      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 { 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