Route guards and permission control in Nuxt project structure implementation

In the Nuxt project structure, route guards act as prerequisites for controlling user access to routes. They are typically implemented through three types: beforeRouteEnter, beforeRouteLeave, and beforeRouteUpdate. These guards allow developers to execute specific logic before a route is loaded, left, or updated, such as permission verification, navigation restrictions, or data preloading.

Types of Route Guards and Usage Scenarios

  1. beforeRouteEnter
    Used to execute logic before the route switch occurs. In this hook, accessing component props is possible, but the component has not yet rendered. It is suitable for scenarios where data needs to be passed to the target component.

    beforeRouteEnter (to, from, next) {
      next(vm => {
        vm.data = to.params.id;
      });
    }
    
  2. beforeRouteLeave
    Executes logic when a user is about to leave the route. In this hook, confirmation of whether the user wants to proceed with leaving can be verified. It is suitable for scenarios requiring prompts for user actions.

    beforeRouteLeave (to, from, next) {
      if (this.isAuth) {
        next(true);
      } else {
        next(false);
      }
    }
    
  3. beforeRouteUpdate
    Executes logic when route parameters are about to be updated. It is suitable for scenarios where data needs to be adjusted based on parameter changes.

    beforeRouteUpdate (to, from, next) {
      if (to.params.id !== from.params.id) {
        this.data = to.params.id;
      }
    }
    

Core Mechanisms of Permission Control

Permission control is implemented via route guards and typically combines Nuxt's route.meta or custom route configurations. Developers can implement it in the following ways:

  • Role-Based Permissions: Set meta.roles in the route configuration and check user roles within the guard.
    const routes = [
      {
        path: '/dashboard',
        meta: { roles: ['admin'] }
      }
    ];
    
  • User-Based Permissions: Obtain user information via the useUser hook and verify permissions in the guard.
    export default {
      beforeRouteEnter (to, from, next) {
        next(vm => {
          if (!vm.user.isAdmin) {
            vm.$router.push('/login');
          }
        });
      }
    };
    

Implementation Steps and Code Examples

  1. Configure Route Guards
    Define guard logic in nuxt.config.js or implement it via the beforeEach/beforeRouteEnter hooks.

    export default {
      modules: ['nuxt-router'],
      router: {
        routes: [
          {
            path: '/protected',
            meta: { requiresAuth: true },
            beforeEnter: (to, from, next) => {
              if (this.$store.state.auth) next();
              else this.$router.push('/login');
            }
          }
        ]
      }
    };
    
  2. Dynamic Permission Verification
    Use useRoute and useNavigation hooks within components, combined with meta.roles, to implement dynamic permission control.

    import { useRoute, useNavigation } from 'vue-router';
    import { useUser } from '~/hooks';
    
    export default {
      setup() {
        const route = useRoute();
        const navigation = useNavigation();
        const user = useUser();
    
        if (route.meta.requiresAuth && !user.isAdmin) {
          navigation.push('/login');
        }
      }
    };
    

Combining Route Guards with Permission Control

By encapsulating permission verification logic within guards, unified route management can be achieved. For example:

  • Global Permission Interception: Set a global guard in nuxt.config.js to ensure all protected routes pass the validation.
  • Local Permission Control: Define permission rules in specific route configurations to avoid redundancy in global settings.

Summary

Route guards and permission control within Nuxt project structures are core mechanisms for securing applications. By configuring guard types and permission strategies appropriately, developers can achieve access control at the route level, enhancing application stability and user experience.