How can I set an afterEach handler that executes after route changes in nuxt? The middleware can be used as an beforeEach, but I could not find a way to implement the afterEach hook.
You can protect routes and make them accessible only for authenticated users for example. Create middleware directory in Nuxt root folder, and create a new file called auth. js therein. Now, Nuxt will redirect user to /login page if not already authenticated (i.e., isLoggedIn is false ).
Nuxt automatically generates the vue-router configuration for you, based on your provided Vue files inside the pages directory. That means you never have to write a router config again!
It looks like this beforeEach is being defined inside an initialized component, which means the first routing has already occured. Define it in the router module with your routes instead: const router = new VueRouter({ ... }) router. beforeEach((to, from, next)=>{ if ( to. name !== 'login' && !
You can create a plugin like the following:
// plugins/after-each.js:
export default async ({ app }) => {
app.router.afterEach((to, from) => {
// Do something
});
}
And then reference it in nuxt.config.js
:
plugins: [ { src: '~/plugins/after-each.js', mode: 'client' } ]
Note: Since Nuxt.js 2.4, mode
has been introduced as option of plugins
to specify plugin type, possible value are: client
or server
. ssr: false
will be adapted to mode: 'client'
and deprecated in next major release.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With