As always, once we understand how middleware works in Vue, it will then be easier to work with it in Nuxt as Nuxt has taken care of Vue Router for us. In the coming sections, we will learn how to work with global and per-route middlewares for Nuxt apps.
In Nuxt, all middleware should be kept in the /middleware/ directory, and the middleware filename will be the name of the middleware. For example, /middleware/user.js is the user middleware. A middleware gets the Nuxt context as its first argument:
export default (context) => { ... }
Additionally, middleware can be asynchronous:
export default async (context) => {
const { data } = await axios.get('/api/path')
}
In universal mode, middlewares are called on the server side once (for example, when first requesting the Nuxt app or when refreshing a page) and then on the client side when navigating to other routes. On the other hand, middlewares are always called on the client side whether...