How to add route wise middleware in Nuxt

How to configure route wise middleware in Nuxt


Nuxt is a framework on the top of the Vuejs, it help developers to build project with lots features, such as data fetching, automatic routes and many more.

Middle wares are the functions (stored in a folder called middleware) that render before Page or layout . For example you want to fetch posts when user visit the blog page, it can be a middle ware.

Middleware function

Create a standard function in the middleware folder, note that the name of the file will be the name of the middle ware. In our example it is a blog fetching function. The async function uses application context as the first argument.

//blogFetch.js
export default async function (context) {
    const document = await context.app.$prismic.api.query(
      context.app.$prismic.predicates.at("document.type", "post_type")
    );
    context.store.commit("blog/setPosts", document);
    context.store.commit("blog/setLoaded", true);
  };

Use middleware in a route/page

How to use a middleware in a page ? Add the following in the script

   middleware:'blogFetch',

Name of the middleware function file will be name of the function.

Following Nuxt Posts may help you to learn more

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.