...

/

Example: Authorized Routes

Example: Authorized Routes

Let's see an example of authorized routes.

To put the use of Vue Router into practice, let’s look at something a lot of client-side apps typically need: protected routes. Let’s build a simple example that demonstrates how to configure routes with authentication checks that will redirect to a login form when a guest tries to access them.

To keep the example simple and focus on the routing aspects, we’re going to create a mock authentication service. In a real app, this would call out to our server or third-party authentication service.

Here’s our src/auth.js file:

Press + to interact
let loggedIn = false;
export default {
login(email, password) {
return new Promise((resolve, reject) => {
if (email === 'user@example.com' && password === 'password') {
loggedIn = true;
resolve();
}
else {
reject();
}
});
},
logout() {
loggedIn = false;
},
isAuthenticated() {
return loggedIn;
},
};

Code explanation

...