title: Vue 3 accessing vue instance in vue router. Outside a Vue file
body: <p>I'm stuck with this since awhile. I want to access my keycloak instance from within the vue router.js file.</p>
  <pre class="lang-js prettyprint-override"><code>const preventRoutes = {
    beforeEnter: (to, from, next) =&gt; {
      console.log(App.$keycloak.authenticated); //here. (Undefined)
      if (store.getters.getLoginState === &quot;true&quot;) {
        ...
      } else {
        ...
      }
    }
  }
  </code></pre>
  <p><a href="https://stackoverflow.com/questions/66954284/access-vue-3-app-instance-api-from-non-vue-fiile">access vue 3 app instance api from non-vue fiile</a></p>
  <p>I'm trying this solution. As it's the only VUE3 I can find, but still, I think he skipped some steps. Can someone simplify please?</p>
  <p>Adviced Solution</p>
  <pre class="lang-js prettyprint-override"><code>const preventRoutes = {
    beforeRouteEnter(to, from, next) {
      next(vm =&gt; {
        // access to component instance via `vm`
        // console.log(vm.$keycloak.authenticated);
        if (this.vm.$keycloak.authenticated) {
          next();
        } else {
          next(&quot;/&quot;);
        }
      })
    }
  }
  </code></pre>
  <p>main.js</p>
  <pre class="lang-js prettyprint-override"><code>const myApp = createApp(App)
  
  let initOptions = {
    url: KeycloakConfig[&quot;auth-server-url&quot;], realm: KeycloakConfig.realm, clientId: KeycloakConfig.resource, clientSecret: KeycloakConfig.credentials.secret
  }
  
  const keycloak = Keycloak(initOptions)
  
  myApp.config.globalProperties.$keycloak = keycloak;
  myApp.use(VueAxios, axios)
  myApp.use(store)
  myApp.use(router)
  myApp.mount(&quot;#app&quot;);
  
  keycloak.init({
    onLoad: &quot;check-sso&quot;,
  
    checkLoginIframe: false
  }).then(async (auth) =&gt; {
    if (!auth) {
  
    } else if (auth) {
      router.push(&quot;/dashboard&quot;); 
    }
  }).catch((e) =&gt; {
    console.log('Serwer lezy: ' + e)
  })
  </code></pre>