Vue Gates based module for Nuxt.js
Note: This version of the module is compatible with Nuxt 3 and Nuxt Bridge.
- Add
nuxt-gates
dependency to your project
yarn add --dev nuxt-gates # or npm install --save-dev nuxt-gates
- Add
nuxt-gates
to themodules
section ofnuxt.config.js
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
modules: [
// Simple usage
'nuxt-gates',
// With options
['nuxt-gates', { /* module options */ }]
]
})
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
modules: [
'nuxt-gates'
],
gates: {
/* module options */
}
})
- Default:
null
Super role avoids all role and permission validations.
- persistent:
false
If the value is true
then it will save the roles and permissions in localStorage
, when the application reloads the values will be set automatically.
-
In Composition API, you can access the
Gates
methods by usingconst { ... } = useGates()
orconst { $gates } = useNuxtApp()
. -
In Options API, you can access the
Gates
methods by usingthis.$gates
.
More informations on Vue Gates documentation
This should be the first step. When you log in or start the application, you must set the roles and permissions:
const { setRoles, setPermissions, getRoles, getPermissions } = useGates()
setRoles(['writer']);
setPermissions(['posts.*', 'images.create']);
getRoles(); // ['writer']
getPermissions(); // ['posts.*', 'images.create']
You can also use the custom directives as functions.
const {
hasRole,
unlessRole,
hasAnyRole,
hasAllRoles,
hasPermission,
unlessPermission,
hasAnyPermission,
hasAllPermissions
} = useGates()
hasRole('admin'); // false
unlessRole('admin'); // true
hasAnyRole('admin|writer'); // true
hasAllRoles('admin|writer'); // false
hasPermission('posts.create'); // true
unlessPermission('posts.create'); // false
hasAnyPermission('posts.create|images'); // true
hasAllPermissions('posts.create|images.create'); // true
You can create named middleware by creating a file inside the middleware/
directory, the file name will be the middleware name:
middleware/admin.js
:
export default defineNuxtRouteMiddleware() {
const { hasRole } = useGates()
// If the user is not an admin
if (!hasRole('admin')) {
return navigateTo('/login')
}
}
pages/secret.vue
:
<template>
<h1>Secret page</h1>
</template>
<script setup>
definePageMeta({
middleware: ["admin"]
})
</script>
- Run
npm run dev:prepare
to generate type stubs. - Use
npm run dev
to start playground in development mode.
Copyright (c) João Pedro Antunes Silva