Middleware directory

The middleware directory contains your application middleware. Middleware lets you define custom functions that can be run before rendering either a page or a group of pages (layout).


Shared middleware should be placed in the middleware/ directory. The filename will be the name of the middleware (middleware/auth.js will be the auth middleware). You can also define page-specific middleware by using a function directly, see anonymous middleware.

A middleware receives the context as the first argument.

middleware/user-agent.js

  1. export default function (context) {
  2. // Add the userAgent property to the context
  3. context.userAgent = process.server
  4. ? context.req.headers['user-agent']
  5. : navigator.userAgent
  6. }

In universal mode, middlewares will be called once on server-side (on the first request to the Nuxt app, e.g. when directly accessing the app or refreshing the page) and on the client-side when navigating to further routes. With ssr: false, middlewares will be called on the client-side in both situations.

The middleware will be executed in series in this order:

  1. nuxt.config.js (in the order within the file)
  2. Matched layouts
  3. Matched pages

Router Middleware

A middleware can be asynchronous. To do this return a Promise or use async/await.

middleware/stats.js

  1. import http from 'http'
  2. export default function ({ route }) {
  3. return http.post('http://my-stats-api.com', {
  4. url: route.fullPath
  5. })
  6. }

Then, in your nuxt.config.js, use the router.middleware key.

nuxt.config.js

  1. export default {
  2. router: {
  3. middleware: 'stats'
  4. }
  5. }

Now the stats middleware will be called for every route change.

You can add your middleware (even multiple) to a specific layout or page as well.

pages/index.vue / layouts/default.vue

  1. export default {
  2. middleware: ['auth', 'stats']
  3. }

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>