• Type: String or Array or Function
    • Items: String or Function

Set the middleware for a specific page of the application.

Named middleware

You can create named middleware by creating a file inside the middleware/ directory, the file name will be the middleware name.

middleware/authenticated.js

  1. export default function ({ store, redirect }) {
  2. // If the user is not authenticated
  3. if (!store.state.authenticated) {
  4. return redirect('/login')
  5. }
  6. }

pages/secret.vue

  1. <template>
  2. <h1>Secret page</h1>
  3. </template>
  4. <script>
  5. export default {
  6. middleware: 'authenticated'
  7. }
  8. </script>

Anonymous middleware

If you need to use a middleware only for a specific page, you can directly use a function for it (or an array of functions):

pages/secret.vue

  1. <template>
  2. <h1>Secret page</h1>
  3. </template>
  4. <script>
  5. export default {
  6. middleware({ store, redirect }) {
  7. // If the user is not authenticated
  8. if (!store.state.authenticated) {
  9. return redirect('/login')
  10. }
  11. }
  12. }
  13. </script>