middleware
Le répertoire middleware
contient les middlewares de l'application. Un middleware nous permet de définir des fonctions personnalisées qui peuvent s'exécuter avant de render une page ou un groupe de pages (layout).
Les middlewares partagés devraient être placés dans le répertoire middleware/
. Le nom du fichiers sera aussi le nom du middleware (un fichier middleware/auth.js
sera appelé avec middleware auth
). On peut aussi utiliser des middlewares spécifiques à des pages en utilisant directement une fonction, voir middlewares anonymes .
Un middleware reçoit le context en tant que premier argument.
export default function (context) {
// Ajouter la propriété userAgent au contexte
context.userAgent = process.server
? context.req.headers['user-agent']
: navigator.userAgent
}
Dans le mode universel, les middlewares seront appelés une fois côté serveur (à la première requête à l'application Nuxt, ex: lorsque l'on accède directement à l'application ou lors du rafraîchissement de la page) et du côté client lors de la navigation sur des routes supplémentaires. En mode SPA, les middlewares seront appelés côté client dans les deux situations.
Les middlewares seront appelés en série dans cet ordre:
-
nuxt.config.js
(en suivant l'ordre définit dans le fichier) - Les layouts qui match
- Les pages qui match
Le middleware du routeur
Un middleware peut être asynchrone. Pour cela, il faut renvoyer une Promesse
ou utiliser async
/await
.
import http from 'http'
export default function ({ route }) {
return http.post('http://mes-stats-api.com', {
url: route.fullPath
})
}
Ensuite, dans le fichier nuxt.config.js
, il faut utiliser la propriété router.middleware
.
export default {
router: {
middleware: 'stats'
}
}
Maintenant, le middleware stats
sera appelé pour chaque changement de route.
On peut ajouter notre middleware (plusieurs même) pour un layout spécifique mais aussi une page.
export default {
middleware: ['auth', 'stats']
}
Middleware nommé
On peut nommer un middleware en créant un fichier à l'intérieur du répertoire middleware/
, le nom du fichier sera aussi le nom du middleware.
export default function ({ store, redirect }) {
// Si l'utilisateur n'est pas authentifié
if (!store.state.authenticated) {
return redirect('/login')
}
}
<template>
<h1>Page secrète</h1>
</template>
<script>
export default {
middleware: 'authenticated'
}
</script>
Middleware anonyme
Si l'on a besoin d'un middleware pour seulement une page spécifique, on peut directement utiliser une fonction pour cela (voire un tableau de fonctions):
<template>
<h1>Page secrète</h1>
</template>
<script>
export default {
middleware({ store, redirect }) {
// Si l'utilisateur n'est pas authentifié
if (!store.state.authenticated) {
return redirect('/login')
}
}
}
</script>

























































