how to write global router-function in nuxt.js

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


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.