Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: An Auth Store with Route Guards

Build login and logout with a Pinia auth store: user state, roles, token handling, a route guard that redirects visitors, and a plugin that resets every store on logout.

Almost every app has users. The auth store is where the question "who is using the app right now?" gets one answer. This project builds a small but realistic version: a login action, user and role state, protected pages with a guard, a redirect back to the page the visitor wanted and a clean logout that wipes private data from all stores.

Vue Router is not available in the live editor (it needs a bundler), so the running example uses a tiny stand-in router that behaves the same way for this purpose. The real Vue Router code is shown read-only first.

The auth store

JavaScript
export const useAuthStore = defineStore("auth", {
  state: () => ({
    user: null,        // { name, role } or null
    token: null,       // kept in memory only
    status: "idle",    // idle | loading | error
    error: null,
    returnTo: null,    // where to go after login
  }),
  getters: {
    isLoggedIn: (state) => state.token !== null,
    isAdmin: (state) => state.user?.role === "admin",
  },
  actions: {
    async login(email, password) {
      this.status = "loading";
      this.error = null;
      try {
        const { token, user } = await api.login(email, password);
        this.token = token;
        this.user = user;
        this.status = "idle";
        return true;
      } catch (e) {
        this.status = "error";
        this.error = e.message;
        return false;
      }
    },
    logout() {
      this.$reset();
    },
  },
});

Design choices to notice:

  • isLoggedIn and isAdmin are getters, derived from one source (token, user). There is no separate loggedIn boolean to forget to update.
  • login returns true or false, so the view can decide what to do next.
  • logout is $reset(), which puts the store back to its starting state in one line.

Where does the token live?

Place Pros Cons
Memory (store state only) Gone after reload; not stored anywhere readable; simplest User must log in again or use a refresh cookie
localStorage Survives reload Any script on the page (XSS) can read it
HttpOnly cookie set by the server JavaScript cannot read it; the best default The server must manage the session; protect against CSRF

For serious apps prefer an HttpOnly cookie, and let the store only hold the user profile. If you do persist a token, see the persistence lesson for how, and keep it short-lived.

The guard in Vue Router (read-only)

JavaScript
router.beforeEach((to) => {
  const auth = useAuthStore();              // called inside the guard, pinia is active

  if (to.meta.requiresAuth && !auth.isLoggedIn) {
    auth.returnTo = to.fullPath;
    return { name: "login" };
  }
  if (to.meta.requiresAdmin && !auth.isAdmin) {
    return { name: "forbidden" };
  }
});

Two details: install pinia (app.use(pinia)) before app.use(router), or the first navigation runs the guard with no active pinia; and call useAuthStore() inside the guard function, never at the top of the router file.

The running app

The editor has three pages: Home (public), Account (needs login) and Admin (needs the admin role). A fake API accepts [email protected] / admin123 (admin) and [email protected] / user123 (regular user). The router is a stand-in. Try opening Account while logged out: you are sent to the login form and returned to Account afterwards.

Login, roles and route guards

Walk through the flows: log out, press Account, log in as the regular user and land on Account; open Admin and see the 403 page; log out, then log in as Ada and open Admin.

A client-side guard is user experience, not security. Anyone can change JavaScript in their browser. Every protected API endpoint must check the token or session on the server. The guard only decides which page to show.

Wiping every store on logout

auth.$reset() clears the auth store only. The cart, the inbox and the profile of the previous user are still in memory, and the next person to log in on a shared computer could see them. A small plugin can handle that in one place. Pinia keeps its list of stores private, so the plugin builds its own registry: every store registers itself when it is created, and when the auth store's logout action finishes, the plugin resets all the others.

A plugin that resets all stores on logout

Log in, add a mug, change the note, then log out: every store is back to its initial values. The rule is written once, in a plugin, instead of being remembered in each logout handler. (Setup stores have no built-in $reset; give them their own reset function, or have the plugin call it when it exists.)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is isLoggedIn a getter derived from token, not a separate boolean?

    A derived value cannot go out of sync with the data it comes from.
  2. 2. Where should useAuthStore() be called in a router guard?

    Calling it at import time can run before pinia exists; inside the guard it is safe.
  3. 3. Does a route guard protect your data?

    Client code can be changed by the user. Real authorization happens on the server.
  4. 4. Why reset all stores on logout?

    Private data left in other stores would still be in memory for the next login.

Summary

  • The auth store holds the user, token and status; isLoggedIn and isAdmin are getters.
  • Guards call the store inside the guard function and redirect, remembering returnTo.
  • Prefer HttpOnly cookies for tokens; memory-only state is safer than localStorage.
  • Client guards are UX; the server enforces security.
  • Reset private state in all stores on logout with one plugin rule.

Next: Project: An Async Data Store with Caching