how to write global router-function in nuxt.js

15,680

Solution 1

You can create a plugin for Nuxt

create a plugins/route.js file:

export default ({ app }) => {
   // Every time the route changes (fired on initialization too)
   app.router.afterEach((to, from) => {
     //do something to validate
   })
}

and update your nuxt.config.js file:

plugins: ['~/plugins/route']

More details about Nuxt plugins: https://nuxtjs.org/guide/plugins

Solution 2

If anybody might be still interested, it's possible to setup global middleware in nuxt.config.js like this:

router: { middleware: ['foo'] },

then in your middleware/foo.js you do whatever...

export default function({ route, from, store, redirect }) {}

Beware: You can't use this for static sites (nuxt generate), because middleware is not executed on page load, but only on subsequent route changes. Thanks @ProblemsOfSumit for pointing that out.

Share:
15,680
Jacky Wong
Author by

Jacky Wong

Updated on June 05, 2022

Comments

  • Jacky Wong
    Jacky Wong almost 2 years

    I am using Vue.js with Nuxt.js, but I got a problem in router's functions.

    In the pure Vue, i can write in main.js like this:

    val route = new Router({
       routes:{
          [...]
       }
    })
    
    route.beforeEach(to,from,next){
        //do something to validate
    }
    

    And how to do the same in nuxt.js ? I can not find any file like main.js.

    Also, all i know is to deal with the pages folder to achieve router, I can not set the redirect path

    please help, thx :)

  • Pyae Sone
    Pyae Sone over 5 years
    @JackyWong how do you do it with middleware?
  • Alireza
    Alireza almost 5 years
    I guess if you use SPA mode, you don't have middleware, right?
  • iSaumya
    iSaumya over 4 years
    Can't thank you enough for this helpful snippet of code. I was trying to make a middleware for this
  • Schäbo
    Schäbo over 4 years
    For future reference: You can use middleware in SPA mode. For SPAs it is only executed on the client side. See this discussion on github for all the gotchas: github.com/nuxt/nuxt.js/issues/2653
  • ProblemsOfSumit
    ProblemsOfSumit about 4 years
    For static sites, you can't use middleware because they are not executed on page load, only on subsequent route changes.
  • ProblemsOfSumit
    ProblemsOfSumit about 4 years
    If you reload any of your routes directly, they are also not called
  • PirateApp
    PirateApp over 2 years
    what is the difference between a nuxt plugin and router middleware, from what I see they seem to do the exact same thing?
  • xpuu
    xpuu over 2 years
    Plugins have much broader scope of use as opposed to middlewares which are closely connected to routing.