How do you access the store within a route guard with vue SSR?

1.3k Views Asked by At

I'm using Vue + SSR on a new project and I'm trying to implement a route guard to enforce authentication on certain routes. I want to do something like this:

function requireAuth(to, from, next) {

  if(!store.auth.getters.authenticated){
  // redirect to login
  }

  ...
}

However, I can't simply import the store as in a normal app since I'm creating a fresh instance for each request, inside of a function, as per the official docs.

export function createRouter () {
  return new Router({
  ...
  });
}

Is there any way of passing the store to the route guard? Or am I coming at this from completely the wrong angle? Any help is greatly appreciated!

1

There are 1 best solutions below

1
On

Ok, I found a solution, but it's not the most elegant. Inspired by this comment on GitHub...

 # router/index.js
createRouter(store) {

  const router = new Router({
    mode: "history",
    routes: [
      {
        path: "/some-protected-route",
        beforeEnter: requireAuth.bind(store)
      }

    ...
  });

  return router;
}

...

requireAuth(to, from, next) {
  const store = this;

  if(!store.getters["auth/authenticated"]) { ... }
}

And don't forget to pass the store into the createRouter function:

# app.js

export default function createApp() {

  const store = createStore();
  const router = createRouter(store);

  sync(store,router)

  const app = new Vue({
    router,
    store,
    render: h => h(App)
  });

  return { app, router, store };
}

Also make sure to avoid / mitigate any browser-only code in the underlying logic.