To make your plugin work in NuxtJS, you need to register it in the nuxt.config.ts file. This is done by adding the plugin to the plugins array in the configuration file. Here’s how you can do it:
- Ensure your plugin file is correctly placed in the
pluginsdirectory. - Register the plugin in the
nuxt.config.tsfile.
Here’s the step-by-step solution:
-
Create the Plugin File: Ensure you have the plugin file
plugins/my-plugin.jswith the following content:export default defineNuxtPlugin(() => { addRouteMiddleware((to, from) => { if (to.path === '/database') return abortNavigation('Forbidden') }) addRouteMiddleware('denyNoor', (to, from) => { const name = to.params.name if (name === 'noor') return abortNavigation('The name noor is not allowed') }) addRouteMiddleware(() => { console.log('Global Middleware') }, { global: true }) }) -
Register the Plugin in
nuxt.config.ts: Open yournuxt.config.tsfile and add the plugin to thepluginsarray:export default defineNuxtConfig({ compatibilityDate: '2024-04-03', devtools: { enabled: true }, plugins: [ '~/plugins/my-plugin.js' ] })
By adding the plugin to the plugins array in the nuxt.config.ts file, NuxtJS will automatically load and initialize the plugin when the application starts.
This should make your custom route middleware work as expected.