The Complete Production SOP: How to Deploy and Run Vue Router 4 Route Guards & Dynamic Route Matching in Autonomous AI Agents
Step-by-step SOP to install and run Vue Router 4 Route Guards & Dynamic Route Matching in Codex, Claude Code, and Cursor. Includes verified prompts and fixes.
Technical Overview & Architectural Context
Autonomous coding agents frequently introduce critical navigation vulnerabilities and performance regressions when configuring Vue Router 4. Common LLM hallucinations include generating Vue Router 3 syntax (such as calling next() in async guards alongside returned route locations), creating infinite redirection loops when evaluating beforeEach conditions, forgetting to guard against unauthenticated access to nested child routes, and failing to implement scrollBehavior restoration properly across async chunk transitions. Without strict procedural boundaries, agents also misuse dynamic route parameters by writing unstructured string interpolations instead of type-safe RouteRecordRaw record trees with parameter regex constraints. This results in route shadowing, unexpected fallback matching, and silent hydration mismatches in Nuxt or Vite SSR/SPA builds. This skill enforces deterministic SOP boundaries for Vue 3 client-side routing. It establishes explicit patterns for TypeScript-typed RouteLocationNormalized signatures, return-based navigation resolution instead of legacy next callbacks, centralized authentication state checks, and reliable savedPosition scroll restoration across all supported agent runtimes (Codex, Claude Code, Cursor, and Windsurf).
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Mount the skill manifest into your agent runtime configuration to enable deterministic trigger matching.
Autonomous runtimes like Claude Code, Cursor, Windsurf, and Codex Desktop monitor specific configuration directories (such as ~/.claude/skills, .cursor/rules, or ~/.agents/skills) to register system instructions. By downloading and storing the SKILL.md in the workspace or global agent skills path, the agent runtime parses the YAML frontmatter triggers ('vue router beforeeach auth guard', 'scrollbehavior vue router', and 'dynamic route params vue router') and enforces the execution SOP before modifying any router configurations.
mkdir -p .agents/skills/vue-router-4-navigation-guards && curl -fsSL https://askills.dev/api/skills/vue-router-4-navigation-guards/raw -o .agents/skills/vue-router-4-navigation-guards/SKILL.md---
name: "vue-router-4-navigation-guards"
description: "Manage client-side routing, authentication guards, scroll behavior, and nested views in Vue 3."
metadata:
author: "Eduardo San Martin Morote"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "vue router beforeeach auth guard"
- "scrollbehavior vue router"
- "dynamic route params vue router"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---Place the SKILL.md inside the root .agents/skills/ directory of your repository. This ensures multi-agent setups (e.g. switching between Cursor and Claude Code) share the exact same deterministic routing instructions without duplicated rule files.
Ensure your agent runtime configuration has read access to .agents/skills/. In Cursor, add '.agents/skills/**' to your active project context indexing settings if repository indexing is constrained.
Route Typing & Authentication Meta Injection
Inject strict TypeScript module augmentations and standard router initialization files.
Before executing runtime guards, the agent must ensure Vue Router's RouteMeta interface is properly augmented with typed properties (such as requiresAuth, roles, or guestOnly). This prevents arbitrary string indexing errors during TypeScript compilation and ensures guards evaluate strongly-typed metadata flags.
pnpm add vue-router@^4.3.0 && mkdir -p src/routerimport { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
declare module 'vue-router' {
interface RouteMeta {
requiresAuth?: boolean;
guestOnly?: boolean;
}
}
export const routes: RouteRecordRaw[] = [
{
path: '/login',
name: 'login',
component: () => import('@/views/LoginView.vue'),
meta: { guestOnly: true }
},
{
path: '/dashboard',
name: 'dashboard',
component: () => import('@/views/DashboardView.vue'),
meta: { requiresAuth: true }
},
{
path: '/users/:id(\\d+)',
name: 'user-detail',
component: () => import('@/views/UserDetailView.vue'),
meta: { requiresAuth: true },
props: true
}
];
export const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
}
if (to.hash) {
return { el: to.hash, behavior: 'smooth' };
}
return { top: 0, left: 0 };
}
});Always require the agent to cast regex-constrained route params directly using props: true or defineProps<{ id: string }>() to preserve loose coupling between views and the router instance.
Do not pass unchecked user input into router.push inside navigation guards; circular redirections occur if target matches the current route during authentication checks.
Deterministic beforeEach Guard Implementation
Configure async global route guards using return values rather than deprecated next callbacks.
In Vue Router 4, invoking the legacy next() callback alongside returning a promise or redirect object causes unhandled navigation rejections or double invocation bugs. This step prompts the agent to use standard return-based navigation resolution: returning true or undefined to allow navigation, or returning a RouteLocationRaw object to redirect.
cat << 'EOF' >> src/router/guards.ts
import type { Router } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
export function setupNavigationGuards(router: Router): void {
router.beforeEach(async (to, from) => {
const authStore = useAuthStore();
// Avoid infinite redirect if auth state is not yet initialized
if (!authStore.isInitialized) {
await authStore.checkAuth();
}
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
return { name: 'login', query: { redirect: to.fullPath } };
}
if (to.meta.guestOnly && authStore.isAuthenticated) {
return { name: 'dashboard' };
}
});
}
EOFInstruct the agent to inspect to.matched.some(record => record.meta.requiresAuth) when dealing with deeply nested routes to avoid skipping checks on intermediate parents.
Never invoke store methods that trigger secondary router.push calls inside a beforeEach guard; return the target route directly from the guard hook.
Verification, Type-Checking & Unit Test Execution
Execute automated self-healing checks to verify guard behavior and route matching.
Instruct the autonomous agent to run TypeScript compilation (vue-tsc --noEmit) and router unit tests using Vitest and @vue/test-utils to confirm that unauthenticated access redirects cleanly and scrollBehavior returns expected coordinates.
pnpm run type-check && pnpm test:runimport { describe, it, expect, beforeEach } from 'vitest';
import { router } from '@/router';
import { setActivePinia, createPinia } from 'pinia';
import { useAuthStore } from '@/stores/auth';
describe('Vue Router 4 Navigation Guards', () => {
beforeEach(async () => {
setActivePinia(createPinia());
await router.push('/');
});
it('redirects unauthenticated users from protected routes to login', async () => {
const auth = useAuthStore();
auth.isAuthenticated = false;
auth.isInitialized = true;
await router.push('/dashboard');
expect(router.currentRoute.value.name).toBe('login');
expect(router.currentRoute.value.query.redirect).toBe('/dashboard');
});
});Require the agent to verify that router.isReady() resolves in all test suites before mounting application components.
Failing to mock pinia or asynchronous auth verification before dispatching router navigation in unit tests causes tests to fail intermittently due to race conditions.
Real-World Scenario: Protect Admin Portal & Implement Dynamic Team Route with Numeric ID Matching
“Refactor src/router/index.ts to secure all '/portal' child routes using a beforeEach auth guard with redirect parameter tracking. Add dynamic matching for '/teams/:teamId' ensuring teamId matches only numeric digits (\d+). Implement smooth scrollBehavior that preserves scroll positions during backward/forward navigation.”
Runtime Troubleshooting & Failure Modes
Root Cause: The navigation guard returns a redirect location (e.g., return '/login') without checking if the target route ('to.path' or 'to.name') is already the login page, creating an infinite redirect cycle.
router.beforeEach((to) => {
const auth = useAuthStore();
if (to.meta.requiresAuth && !auth.isAuthenticated && to.name !== 'login') {
return { name: 'login', query: { redirect: to.fullPath } };
}
});Root Cause: The agent mixed Vue Router 3 syntax with Vue Router 4 async patterns by declaring the third 'next' argument and calling next() while also returning a value or promise from the guard.
// Remove the 'next' parameter completely and rely purely on return values:
router.beforeEach((to, from) => {
if (to.meta.guestOnly && isAuthenticated()) {
return { name: 'dashboard' };
}
return true;
});Frequently Asked Questions (Vue Router 4 Route Guards & Dynamic Route Matching SOP)
Q:Can I use Vue Router 4 Route Guards & Dynamic Route Matching across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill is packaged according to the universal open SKILL.md specification. Runtimes including Codex CLI/Desktop, Claude Code CLI, Cursor, and Windsurf can parse the identical frontmatter triggers and SOP guidelines directly from the local repository directory.
Q:How does Vue Router 4 Route Guards & Dynamic Route Matching prevent context window overflow during long agent sessions?
By providing deterministic, concrete rules for Vue 3 return-based guards and typed routes, the agent avoids iterative guessing, multi-turn syntax debugging, and verbose trial-and-error logs, saving thousands of tokens during navigation refactors.
Q:Does this skill require escalated root or container permissions?
No. The skill maintains an audited security score of 98/100. It requires only standard workspace file-system read/write privileges (fs_read: true, fs_write: 'workspace') and requires zero network access or root shell execution privileges.
Ready to equip your autonomous agent with Vue Router 4 Route Guards & Dynamic Route Matching?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.