Adding global middlewares is very straightforward; you just have to declare them in the middleware key in the router option of the config file. For example, take a look at the following:
// nuxt.config.js
export default {
router: {
middleware: 'auth'
}
}
Now, let's create some global middleware in the following steps. In this exercise, we want to to get the information of the user agent from the HTTP request header and to track the routes the user is navigating to:
- Create two middlewares in the /middleware/ directory, one for obtaining the user agent information and the other for obtaining the route path information that the user is navigating to:
// middleware/user-agent.js
export default (context) => {
context.userAgent = process.server ? context.req.headers[
'user-agent'] : navigator.userAgent
}
// middleware/visits.js
export default ({ store, route, redirect }) => {
store.commit('addVisit', route.path...