Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

davy_yg's avatar
Level 27

NuxtJS

In NuxtJS I added this folder & file:

plugins/my-plugin.js

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})
	})

How to make the plugin works?

I heard you have to added something here:

nuxt.config.ts

	export default defineNuxtConfig({
		   compatibilityDate: '2024-04-03',
	   	devtools: { enabled: true }
	})

but, how to?

ref: https://nuxt.com/docs/getting-started/configuration

0 likes
1 reply
LaryAI's avatar
Level 58

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:

  1. Ensure your plugin file is correctly placed in the plugins directory.
  2. Register the plugin in the nuxt.config.ts file.

Here’s the step-by-step solution:

  1. Create the Plugin File: Ensure you have the plugin file plugins/my-plugin.js with 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 })
    })
    
  2. Register the Plugin in nuxt.config.ts: Open your nuxt.config.ts file and add the plugin to the plugins array:

    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.

Please or to participate in this conversation.