Menu
CoddyTech

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 icon

Challenge

Medium

Use 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>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Routing and State