New Dec 9, 2025

Vue 3: Pinia Storage in Router Guards

Libraries, Frameworks, etc. All from Newest questions tagged vue.js - Stack Overflow View Vue 3: Pinia Storage in Router Guards on stackoverflow.com

My goal is to restrict access for authenticated users to the /login and /register routes

My Pinia Storage user.js contains user info and computed boolean property isAuthorized, when I am trying to use it in router pinia storage is always empty and isAuthorized sets to false.

My backend uses Laravel Sanctum which works with cookie based session authentication, so I'm not using tokens with localStorage.

It's clear that router and app loads faster than the pinia store, but if I open F12 -> Vue -> Pinia I see isAuthorized = true

If someone already encountered such problem without localStorage and tokens would be really grateful for your support. Thanks in advance!

store/user.js

import { computed, ref } from 'vue'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => { const user = ref(null)

const isAuthorized = computed(() => !!user.value)

function updateUser(userData) { userData ? user.value = userData : user.value = null }

return { user, isAuthorized, updateUser } })

router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '@/views/auth/LoginView.vue'
import RegisterView from '@/views/auth/RegisterView.vue'
import { useUserStore } from '@/store/user.js'

const routes = [ { name: 'Login', path: '/login', component: LoginView, beforeEnter: (to) => { const store = useUserStore() if (store.isAuthorized) { return '/' } }, }, { name: 'Register', path: '/register', component: RegisterView, beforeEnter: (to, from, next) => { const user = useUserStore() user.isAuthorized.value ? next('/') : next() }, }, // ... ];

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

export async function routerPush(name, params) { if (params === undefined) { return await router.push({ name }) } else { return await router.push({ name, params }) } } export default router

plugins/set-user.js

import { getCurrentUser } from '@/api/user.js'
import { useUserStore } from '@/store/user.js'

export default async function setUser(pinia) { const { updateUser } = useUserStore(pinia)

const userData = await getCurrentUser()

userData ? updateUser(userData) : updateUser(null) }

main.js

import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';
import './style.css';
import setUser from '@/plugins/set-user.js'

const app = createApp(App) const pinia = createPinia()

app.use(pinia) app.use(router)

setUser(pinia)

app.mount('#app')

Scroll to top