Using Nuxt3 plugins

Some small difference with Nuxt3’s use of plugins.

First of all we need to use defineNuxtPlugin().

// plugins/userHasAccess.ts

export default defineNuxtPlugin(() => {
  return {
    provide: {
      // params can be added here
      userHasAccess: (user: User, access: string | string[]) => {
        if (typeof access === "string") {
          return user?.roles?.includes(access);
        } else {
          return user?.roles?.some((r) => access.includes(r));
        }
      },
    },
  };
});

The plugins are already registered globally for use.

// pages/index.vue
<template>
  <div v-if="$userHasAccess(user, 'ROLE_NEEDED')">
      I can be seen
  </div>
</template>

<script setup lang="ts">
const { $userHasAccess } = useNuxtApp();

import { useAuthStore } from "~/store/auth";
const authStore = useAuthStore();
const { user } = storeToRefs(authStore);

</script>


The user object looks like —

{
  "email" : "yourmemail@company.com",
  "roles" : ["ROLE_NEEDED"]
}

Posted

in

,

by

Tags:

Comments

Leave a Reply