Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 87 ยท Performance, Security and Ecosystem

Authentication Patterns

How login state works in a Vue app: cookies versus tokens, where to store them, route guards, handling 401 responses and refreshing sessions, with live demos.

Authentication answers one question: who is this user? Authorization answers a second one: what may they do? In a Vue app, the browser side of both is mostly about user experience. The real checks always happen on the server, because anything running in a browser can be inspected, changed or skipped by the person using it.

That shapes everything in this lesson. Your Vue code keeps track of whether someone is signed in, shows the right screens, sends the credential with each request, and reacts when the server says "no". It must never be the only thing standing between a stranger and private data. The live examples here use a fake server inside the page, because the sandbox cannot make real requests and you should never type real passwords into a demo.

Two ways to remember a user

HTTP is stateless, so after login the browser must prove who it is on every request. There are two common designs.

Cookie sessions. The server creates a session, stores it, and sends back a session id in a cookie. The browser attaches that cookie automatically to every request to your site. If the cookie is marked HttpOnly, Secure and SameSite, JavaScript cannot read it at all, and the browser does not send it from other sites in most cases.

Tokens. The server returns a token (often a signed JWT, short for JSON Web Token), and your code sends it in an Authorization: Bearer ... header. Tokens work well for mobile apps and for APIs on a different domain, but now your JavaScript has to hold the token somewhere.

Cookie session Bearer token
Sent by The browser, automatically Your code, on each request
Readable by JavaScript No, with HttpOnly Yes, it must be
Main risk CSRF (a foreign site triggers a request) XSS (a script steals the token)
Typical defense SameSite cookies, CSRF token Short lifetime, keep it in memory
Best fit A site and API on the same site Mobile apps, third-party APIs

Where should a token live? Each place has a price:

  • Memory (a variable in a store): not readable from other scripts or other tabs, gone on reload. Safest, but you need a way to get a new one after a refresh.
  • localStorage or sessionStorage: survives reloads, but any script on your page can read it, so a single XSS bug leaks the token (see Security in Vue).
  • An HttpOnly cookie: invisible to JavaScript. Often the best home for a long-lived refresh credential.

A strong, common design is hybrid: a short-lived access token in memory, and a long-lived refresh credential in an HttpOnly cookie that the server uses to hand out new access tokens. For a plain website whose API lives on the same domain, a classic cookie session is simple and strong, and you may not need tokens at all.

Never invent your own cryptography or login protocol. For "Sign in with Google" or a company login, use OpenID Connect with the authorization code flow and PKCE, through a maintained library or an identity provider.

Keep auth state in one place

The signed-in state is needed by many components: the header, route guards, API calls. That is exactly what a small shared store is for (see Building a Simple Store). It holds the current user, a flag saying whether the first check has finished, and actions such as login and logout.

flowchart TD
  A["navigate to /dashboard"] --> B{"route needs login?"}
  B -- no --> E["show the view"]
  B -- yes --> C{"signed in?"}
  C -- yes --> E
  C -- no --> D["redirect to /login<br/>remember the target"]
  D --> F["user signs in"]
  F --> G["go to the remembered target"]

A navigation guard decides before a screen is shown. After a successful login the user continues where they wanted to go.

Route guards

A route guard is a function that runs before a navigation completes and decides to allow it, cancel it, or redirect. In Vue Router you attach a flag to the route's meta field and check it in one global guard. This is read-only here, because the router package is not available in the sandbox:

JavaScript
// router.js (read-only: Vue Router)
const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: "/", component: HomeView },
    { path: "/login", component: LoginView },
    { path: "/dashboard", component: DashboardView, meta: { requiresAuth: true } },
    { path: "/admin", component: AdminView, meta: { requiresAuth: true, role: "admin" } }
  ]
});

router.beforeEach(async (to) => {
  const auth = useAuthStore();
  await auth.ready;                       // wait for the first session check
  if (to.meta.requiresAuth && !auth.user) {
    return { path: "/login", query: { next: to.fullPath } };
  }
  if (to.meta.role && auth.user?.role !== to.meta.role) {
    return { path: "/forbidden" };
  }
});

Returning a location redirects, returning false cancels, and returning nothing allows the navigation. More on guards is in Vue Router Advanced Features.

Here is a runnable stand-in using only plain Vue reactivity. It has the same idea: a route table with an auth flag, a guard inside the navigate function, a remembered target, and a fake login that takes a moment, like a network call. Try opening Dashboard while signed out. The correct login is [email protected] with the password vue-rocks (a made-up pair that exists only in this demo).

A login flow with a route guard

A guard like this protects the screen, not the data. Someone can open the developer tools and flip a variable to see the private view. The view itself must contain nothing secret: the data comes from API calls, and the server refuses those calls without a valid session. Think of guards as good manners, and of the server as the lock.

Restoring the session on page load

After a reload, memory is empty. A cookie session is restored by asking the server "who am I?" (for example GET /api/me), and a token design asks the refresh endpoint for a new access token. Until that call finishes, you do not know whether the user is signed in, so do not redirect yet. Keep a ready promise or a loading flag in the auth store, and have the guard wait for it, as await auth.ready does above. Without it, signed-in users see a flash of the login page every time they reload.

Handling 401 and 403

The server answers in two different ways, and they need different reactions:

  • 401 Unauthorized means "I do not know who you are": the session is missing or expired. Try to refresh, and if that fails, sign the user out and go to the login page.
  • 403 Forbidden means "I know who you are, but you may not do this". Do not sign out. Show a "no access" message.

Handle this in one place, a wrapper around fetch, not in every component. The wrapper adds the credential, notices a 401, tries one refresh and retries the request once. If several requests fail at the same moment (a dashboard often fires many), they should share a single refresh call, otherwise you flood the server and some refreshes will fail because the previous refresh token was already used.

sequenceDiagram
  participant App as Vue app
  participant API as API server
  App->>API: GET /api/profile with the access token
  API-->>App: 401 token expired
  App->>API: POST /auth/refresh
  API-->>App: 200 with a new access token
  App->>API: GET /api/profile again
  API-->>App: 200 profile data

The wrapper refreshes once and repeats the original request, so components never see the expired token.

The next demo has a fake server. Press "Request profile" to make a call. Press "Expire access token" so the server stops accepting the token the app holds, then request again: the app gets a 401, refreshes, and retries on its own. "Fire 3 requests at once" sends three calls with an expired token and shows that they share one refresh. "Revoke session" makes even the refresh fail, which signs the user out.

Refreshing after a 401

Notice how the component code is untouched by token expiry: only the wrapper knows. Real wrappers also add Authorization headers and avoid retrying the refresh request itself, or you could loop forever.

Logging out properly

Logging out means more than flipping a flag:

  1. Tell the server to end the session (and clear the cookie) so a stolen credential stops working.
  2. Clear the user, the token and any cached private data in your stores (a shared computer should not show the last user's data).
  3. Close realtime connections and cancel pending requests.
  4. Navigate to a public page.

If the user can have the app open in several tabs, listen for a storage or BroadcastChannel message so the other tabs sign out too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a route guard not enough to protect private data?

    A guard controls what the interface shows. A determined user can bypass front-end code, so authorization must be enforced by the server on each API call.
  2. 2. Which storage place keeps a credential away from JavaScript entirely?

    Scripts cannot read HttpOnly cookies, so an XSS bug cannot steal them directly. The other places are all readable by script on your page.
  3. 3. A request returns 403. What should the app do?

    401 means unknown or expired identity, so refresh or sign in again. 403 means the identity is known but lacks permission, so signing in again will not help.
  4. 4. Why should concurrent 401 responses share one refresh call?

    If every failed request starts its own refresh, the server may reject the later ones because the earlier refresh already used the refresh credential. One shared promise avoids that.
  5. 5. Why wait for a session check before running a guard after a page reload?

    Until the app asks the server who the user is, redirecting would send signed-in users to the login page on every reload.

Summary

  • Authentication happens on the server; your Vue app manages the experience around it.
  • Cookie sessions (HttpOnly, Secure, SameSite) and bearer tokens trade CSRF risk against XSS risk. Prefer short-lived access tokens kept in memory plus an HttpOnly refresh cookie, or a plain cookie session on the same domain.
  • Keep user and auth state in one store, and guard routes with meta flags and a global guard that waits for the first session check.
  • Guards protect screens only; the server must protect data.
  • Handle 401 (refresh or sign in) and 403 (no access) in one fetch wrapper, with one shared refresh.
  • A proper logout ends the server session and clears every trace in the client.

Next, in Server-Side Rendering and Hydration, you will see how Vue can produce HTML on the server and then take over in the browser.