Store-Aware Access Guards
Part of the Routing and State section of Coddy's Vue journey. Lesson 46 of 55.
A guard can read a Pinia session store and return a destination rather than simply cancelling. Outside component setup, pass the installed Pinia instance explicitly to the store accessor so the guard uses the same store as the app.
router.beforeEach(to=>{
const session=useSessionStore(pinia);
if(to.meta.membersOnly&&!session.ready)return {name:'sign-in'};
});Create and install one shared Pinia instance before the router begins its initial navigation. Read the store inside the callback so later session changes affect later attempts. Leave the sign-in route public; otherwise redirecting there can create a loop. This local exercise models navigation state, not a real identity provider.
Challenge
MediumUse the supplied session store in a global guard. Redirect signed-out navigation to a record with meta.requiresAuth to the named Login route. Leave public Home, Help and Login reachable. The local Sign in button sets signedIn true and replaces Login with Desk. The shell Sign out button only changes the session flag; the next restricted attempt must be redirected again. This is a local UI session, not real authentication.
Keep the supplied route readout and bootstrap files.
Try it yourself
<!doctype html><html><head><meta charset="UTF-8"><title>Routing practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Routing and State
4Query State
Reading Query ValuesCommitting Search QueriesPreserving Other FiltersNormalizing Query NumbersRecap: Catalog Filters7Pinia Options Stores
Shared Store StateDerived Store GettersStore Actions and BoundsExtracting Reactive FieldsRecap: Seat Counter10Guarded Workflows
Store-Aware Access GuardsReturning After Sign-InNested Access PoliciesProtecting Unsaved DraftsRecap: Museum Pass2Navigation Actions
Navigation from HandlersReplacing HistoryHistory TravelCurrent Navigation LinksRecap: Save and Review5Nested Layouts
Parent and Child OutletsDefault Child ViewsRelative Child PathsAncestor Navigation StateRecap: Library Workspace8Store Design
Setup Store StructurePatching Related StateResetting Store StateComposing Related StoresRecap: Trip Pack11Workshop Planner Project
Planner RoutesShared Reservations