0
0
VueHow-ToBeginner · 4 min read

How to Create Auth Flow in Vue: Simple Guide with Example

To create an auth flow in Vue, use reactive state or Vuex to track user login status, protect routes with router navigation guards, and store tokens or user info in localStorage. This setup lets you control access and update UI based on authentication.
📐

Syntax

An auth flow in Vue typically involves these parts:

  • State management: Use reactive or ref to hold user info or token.
  • Router guards: Use router.beforeEach to check auth before navigation.
  • Storage: Save auth token or user data in localStorage to persist login.
javascript
import { reactive } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';

const authState = reactive({ isLoggedIn: false });

const routes = [
  { path: '/login', component: Login },
  { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } }
];

const router = createRouter({ history: createWebHistory(), routes });

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !authState.isLoggedIn) {
    next('/login');
  } else {
    next();
  }
});
💻

Example

This example shows a simple Vue app with login, logout, and protected dashboard routes. It uses reactive state and router.beforeEach to control access.

javascript
import { createApp, reactive } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';

const authState = reactive({ isLoggedIn: !!localStorage.getItem('token') });

const Login = {
  template: `
    <div>
      <h2>Login</h2>
      <button @click="login">Log In</button>
    </div>
  `,
  setup() {
    const login = () => {
      localStorage.setItem('token', 'fake-token');
      authState.isLoggedIn = true;
      router.push('/dashboard');
    };
    return { login };
  }
};

const Dashboard = {
  template: `
    <div>
      <h2>Dashboard</h2>
      <button @click="logout">Log Out</button>
    </div>
  `,
  setup() {
    const logout = () => {
      localStorage.removeItem('token');
      authState.isLoggedIn = false;
      router.push('/login');
    };
    return { logout };
  }
};

const routes = [
  { path: '/login', component: Login },
  { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } },
  { path: '/:pathMatch(.*)*', redirect: '/login' }
];

const router = createRouter({ history: createWebHistory(), routes });

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !authState.isLoggedIn) {
    next('/login');
  } else if (to.path === '/login' && authState.isLoggedIn) {
    next('/dashboard');
  } else {
    next();
  }
});

const app = createApp({});
app.use(router);
app.mount('#app');
Output
User sees a login page with a button. Clicking 'Log In' stores a token, sets logged-in state, and navigates to dashboard. Dashboard shows a logout button that clears token and returns to login.
⚠️

Common Pitfalls

Common mistakes when creating auth flow in Vue include:

  • Not protecting routes properly, allowing unauthorized access.
  • Forgetting to update reactive state after login/logout, causing UI not to update.
  • Storing sensitive info insecurely or not clearing it on logout.
  • Not handling page refresh, losing auth state if only stored in memory.
javascript
/* Wrong: Not updating reactive state after login */
function login() {
  localStorage.setItem('token', 'token');
  // Missing: authState.isLoggedIn = true;
  router.push('/dashboard');
}

/* Right: Update reactive state */
function login() {
  localStorage.setItem('token', 'token');
  authState.isLoggedIn = true;
  router.push('/dashboard');
}
📊

Quick Reference

Tips for Vue auth flow:

  • Use reactive or ref to track login state.
  • Protect routes with router.beforeEach and meta.requiresAuth.
  • Store tokens in localStorage for persistence.
  • Clear tokens and update state on logout.
  • Redirect logged-in users away from login page.

Key Takeaways

Use reactive state to track if the user is logged in or not.
Protect routes by checking auth status in router navigation guards.
Store auth tokens in localStorage to keep users logged in after refresh.
Always update reactive state when login or logout happens to update UI.
Redirect users properly based on their authentication status.