Vue · Middle · Question 42 of 75

How do you use a store outside of a component, e.g. in a router guard?

router.beforeEach((to) => {
  const auth = useAuthStore();
  if (to.meta.requiresAuth && !auth.user) return "/login";
});

Explanation

At module top level the Pinia instance may not be active yet (and in SSR it would be shared between requests). Calling the hook inside the guard uses the app's active Pinia.

Further reading

Problem with a question

Vue · Middle · question 42

Test yourself

Take the Vue · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz