All skills
vuejs-ai avatar

/vue-router-best-practices

@bc922e4 official
by Vue AIvuejs-ai/skills2.9k stars
167

Vue Router 4 patterns, navigation guards, route params, and route-component lifecycle interactions.

Use this Skill: https://skilld.dev/gh/vuejs-ai/skills/vue-router-best-practices

This session only. Nothing lands on disk.

referencerouter-guard-async-await-pattern.md

≈1.5k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Async Navigation Guards Require Proper Promise Handling

Impact: MEDIUM - Navigation guards that perform async operations (API calls, auth checks) must properly handle promises. If you don't await async operations or return the promise, navigation completes before your check finishes, potentially allowing unauthorized access or navigating with incomplete data.

Task Checklist

  • Use async/await in navigation guards
  • Return the promise if not using async/await
  • Add loading states for long async operations
  • Implement timeouts for slow API calls
  • Handle errors to prevent navigation hanging

The Problem

// WRONG: Not awaiting - navigation proceeds immediately
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth) {
    checkAuth()  // This returns a Promise but we're not waiting!
    // Navigation continues before checkAuth completes
  }
})

// WRONG: Async function but forgot return
router.beforeEach(async (to, from) => {
  if (to.meta.requiresAuth) {
    const isValid = await checkAuth()
    if (!isValid) {
      // This redirect might happen after navigation already completed!
      return '/login'
    }
  }
  // Missing return - implicitly returns undefined, allowing navigation
})

Solution: Proper Async/Await Pattern

// CORRECT: Async function with proper returns
router.beforeEach(async (to, from) => {
  if (to.meta.requiresAuth) {
    try {
      const isAuthenticated = await checkAuth()

      if (!isAuthenticated) {
        return { name: 'Login', query: { redirect: to.fullPath } }
      }
    } catch (error) {
      console.error('Auth check failed:', error)
      return { name: 'Error', params: { message: 'Authentication failed' } }
    }
  }
  // Explicitly return nothing to proceed
  return true
})

Solution: Promise-Based Pattern (Alternative)

// CORRECT: Return promise explicitly
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth) {
    return checkAuth()
      .then(isAuthenticated => {
        if (!isAuthenticated) {
          return { name: 'Login' }
        }
      })
      .catch(error => {
        console.error('Auth check failed:', error)
        return { name: 'Error' }
      })
  }
})

Loading State During Async Guards

// app/composables/useNavigationLoading.js
import { ref } from 'vue'

const isNavigating = ref(false)

export function useNavigationLoading() {
  return { isNavigating }
}

export function setupNavigationLoading(router) {
  router.beforeEach(() => {
    isNavigating.value = true
  })

  router.afterEach(() => {
    isNavigating.value = false
  })

  router.onError(() => {
    isNavigating.value = false
  })
}
<!-- App.vue -->
<script setup>
import { useNavigationLoading } from '@/composables/useNavigationLoading'

const { isNavigating } = useNavigationLoading()
</script>

<template>
  <LoadingBar v-if="isNavigating" />
  <router-view />
</template>

Timeout Pattern for Slow APIs

// CORRECT: Add timeout to prevent indefinite waiting
function withTimeout(promise, ms = 5000) {
  return Promise.race([
    promise,
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Request timeout')), ms)
    )
  ])
}

router.beforeEach(async (to, from) => {
  if (to.meta.requiresAuth) {
    try {
      const isValid = await withTimeout(checkAuth(), 5000)
      if (!isValid) {
        return '/login'
      }
    } catch (error) {
      if (error.message === 'Request timeout') {
        // Let user through but show warning
        console.warn('Auth check timed out')
      } else {
        return '/login'
      }
    }
  }
})

Multiple Async Checks

// CORRECT: Run independent checks in parallel
router.beforeEach(async (to, from) => {
  if (to.meta.requiresAuth && to.meta.requiresSubscription) {
    try {
      const [isAuthenticated, hasSubscription] = await Promise.all([
        checkAuth(),
        checkSubscription()
      ])

      if (!isAuthenticated) {
        return '/login'
      }

      if (!hasSubscription) {
        return '/subscribe'
      }
    } catch (error) {
      return '/error'
    }
  }
})

Error Handling Best Practices

router.beforeEach(async (to, from) => {
  try {
    // Your async logic here
    await performChecks(to)
  } catch (error) {
    // Always handle errors to prevent navigation from hanging

    if (error.response?.status === 401) {
      return '/login'
    }

    if (error.response?.status === 403) {
      return '/forbidden'
    }

    if (error.code === 'NETWORK_ERROR') {
      // Offline - maybe allow navigation but show warning
      return true
    }

    // Unknown error - redirect to error page
    console.error('Navigation guard error:', error)
    return { name: 'Error', state: { error: error.message } }
  }
})

Key Points

  1. Always await async operations - Otherwise navigation proceeds immediately
  2. Return values matter - Return route to redirect, false to cancel, true/undefined to proceed
  3. Handle all error cases - Uncaught errors can hang navigation
  4. Add timeouts - Slow APIs shouldn't block navigation indefinitely
  5. Show loading state - Users need feedback during async checks
  6. Parallelize independent checks - Use Promise.all for better performance

Reference

Source: SKILL.md on GitHub

No alerts16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    This skill is a collection of educational documentation and best practices for using Vue Router 4. It contains no executable code, network operations, or sensitive data access, and is focused entirely on providing guidance for frontend development patterns.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer7mo

    9 files scanned · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at bc922e4. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 8 months ago
version
1.0.0
author
github.com/vuejs-ai
  • Vue
  • vue-router
  • navigation-guards
  • routing
  • lifecycle
  • spa

README badge

README badge for vuejs-ai/skills/vue-router-best-practices

Teaches Vue Router 4 navigation guards, route lifecycle handling, and common patterns like preventing infinite redirects and managing stale data across param changes. Covers gotchas like component cleanup on navigation and the deprecated next() function.

Generated from the current SKILL.md.

Does this skill cover Vue Router 4?
Yes. The skill is specific to Vue Router 4 patterns, navigation guards, route params, and component lifecycle interactions.
What are the main topics covered?
Navigation guards (async/await, infinite loops, deprecated next() function), route lifecycle issues (stale data, cleanup), and production SPA setup.
Does this address the problem of component data not updating when route params change?
Yes. The skill includes guidance on handling stale data when navigating between the same route with different params.
Does this cover how to access component instances in navigation guards?
Yes. It addresses the gotcha that `this` is not available in beforeRouteEnter guards and explains the workaround.
Does this skill help prevent infinite redirect loops?
Yes. It includes patterns for identifying and avoiding infinite navigation guard redirect loops.

Generated from the current SKILL.md. These answers refresh after source changes.