vuejs3nuxt.jsvue-routernuxt3.js

How to include the children of a route when creating a middleware?


I have created a global auth middleware but need to check if you are going to any route in /dashboard and its subroutes like /dashboard/account or /dashboard/settings.

The middleware below is a very simple version of what I created but it looks like this:

export default defineNuxtRouteMiddleware((to, from) => {
    const useAuth = useAuthStore()
    
    //This only checks this one path
    if (to.path == '/dashboard' && !useAuth.authenticated) {
        console.log(to.path)
        return navigateTo('/auth/login')
    }

    //Using wildcards doesn't check any paths at all.
    if (to.path == '/dashboard/**' && !useAuth.authenticated) {
        console.log(to.path)
        return navigateTo('/auth/login')
    }
})

What can I do for it the check all the main route and it's sub-routes / nested routes?


Solution

  • to variable is a string, so you have all the String functions at your disposal. You could use regex search for very specific string matching, but maybe simpler for your case would just be String.startsWith()

    if (to.path.startsWith('/dashboard') && !useAuth.authenticated)