{"id":292292,"date":"2019-07-11T08:21:19","date_gmt":"2019-07-11T15:21:19","guid":{"rendered":"https:\/\/css-tricks.com\/?p=292292"},"modified":"2019-07-15T08:20:32","modified_gmt":"2019-07-15T15:20:32","slug":"protecting-vue-routes-with-navigation-guards","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/protecting-vue-routes-with-navigation-guards\/","title":{"rendered":"Protecting Vue Routes with Navigation Guards"},"content":{"rendered":"

Authentication is a necessary part of every web application. It is a handy means by which we can personalize experiences and load content specific to a user — like a logged in state. It can also be used to evaluate permissions, and prevent otherwise private information from being accessed by unauthorized users.<\/p>\n

A common practice that applications use to protect content is to house them under specific routes and build redirect rules that navigate users toward or away from a resource depending on their permissions. To gate content reliably behind protected routes, they need to build to separate static pages. This way, redirect rules can properly handle redirects.<\/p>\n

In the case of Single Page Applications (SPA<\/abbr>s) built with modern front-end frameworks, like Vue, redirect rules cannot be utilized to protect routes. Because all pages are served from a single entry file, from a browser\u2019s perspective, there is only one page: index.html<\/code>. In a SPA<\/abbr>, route logic generally stems from a routes file. This is where we will do most of our auth configuration for this post. We will specifically lean on Vue\u2019s navigation guards to handle authentication specific routing since this helps us access selected routes before it fully resolves. Let\u2019s dig in to see how this works. <\/p>\n

<\/p>\n

Roots and Routes<\/h3>\n

Navigation guards<\/dfn><\/a> are a specific feature within Vue Router<\/a> that provide additional functionality pertaining to how routes get resolved. They are primarily used to handle error states and navigate a user seamlessly without abruptly interrupting their workflow.<\/p>\n

There are three main categories of guards in Vue Router: Global Guards, Per Route Guards and In Component Guards. As the names suggest, Global Guards<\/dfn> are called when any navigation is triggered (i.e. when URL<\/abbr>s change), Per Route Guards<\/dfn> are called when the associated route is called (i.e. when a URL<\/abbr> matches a specific route), and Component Guards<\/dfn> are called when a component in a route is created, updated or destroyed. Within each category, there are additional methods that gives you more fine grained control of application routes. Here\u2019s a quick break down of all available methods within each type of navigation guard in Vue Router.<\/p>\n

Global Guards<\/h4>\n