Vue · Middle · Question 32 of 75

How do you protect routes that require authentication?

router.beforeEach((to) => {
  if (to.meta.requiresAuth && !auth.isLoggedIn) {
    return { name: "login", query: { redirect: to.fullPath } };
  }
});

Explanation

Returning false cancels navigation, returning a route redirects, returning nothing allows it. Real protection must still happen on the server API.

Further reading

Problem with a question

Vue · Middle · question 32

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