Middlewares: What They Are and How to Use Them in Nuxt.JS

What Are Middlewares?

In Front-end development, Middlewares are blocks of code that execute before navigation to a new page occurs, allowing various controls in our application, such as:

  • Authentication: Checks if the user is logged in; otherwise, they are redirected to the login screen.
  • Permission: Verifies if the user has access to the page; if not, they are redirected to an allowed page.
  • Logs: Saves information about page activities.

Middlewares act as an intermediate layer, working from the start of the page load until its complete rendering.

This middleware functionality is present in modern Front-end frameworks such as Next.js and Nuxt.JS.

In this article, I will teach you how to implement route middlewares in Nuxt.JS.

Middlewares in a Less Technical Way

people at a party

"People at a party" by Cottonbro Studio , licensed by Pexels

To explain it more simply, let’s use an analogy:

Imagine you want to enter a party, and in this process, you go through three security staff members, who act as "middlewares," each responsible for a specific action.

  1. The first security guard checks if you have a valid ticket, similar to an authentication middleware. If you don’t have one, you are redirected to the ticket office or login screen.
  2. The second guard ensures you are of legal age, a crucial requirement for entering the party, similar to a permission middleware. If you don’t meet the criteria, you are sent away.
  3. The third and final guard gives you a wristband indicating whether you have VIP access, much like middlewares that add data to requests.

Finally, after passing all these checks, you are free to enter the party hall.

Types of Middlewares

In Nuxt.js, we have the following types of Middlewares:

  • Global
  • Inline or Anonymous
  • Named
  1. Global Middlewares are created inside the /middleware folder and execute on all pages. The global suffix is required.
/*
  Example of a Global Middleware:
  This middleware checks if the requested URL/route exists.
  If it doesn’t exist, the user is redirected to the links page.

  File Name and Directory:
  /middleware/notFound.global.js
*/

export default defineNuxtRouteMiddleware((to) => {
  const hasFoundRoute = to.matched.length > 0;

  if (!hasFoundRoute) {
    return navigateTo({
      path: "/links"
    });
  }
});
  1. Inline or Anonymous Middlewares are specific to a page, defined directly within the Nuxt page file. This limits code reuse since it cannot be easily shared with other pages.
/*
  Example of an Inline Middleware:
  This middleware checks if data is present in the store.
  If not, the data is requested.
*/

<script setup lang="ts">
import { useStore } from 'vuex';

definePageMeta({
  middleware: [
    async function (to, from) {
      const store = useStore();
      if (!store.state.user) {
        await store.dispatch("fetchUser");
      }
    },
  ],
});
</script>
  1. Named Middlewares are created inside the /middleware folder.
/*
  Example of a Named Middleware:
  This middleware checks if the user is logged in.
  If not, they are redirected to the login page.

  File Name and Directory:
  /middleware/auth.js
*/

export default defineNuxtRouteMiddleware((to, from) => {
  const { $store } = useNuxtApp();

  if (!$store.auth?.loggedIn) {
    return navigateTo("/login");
  }
});

For Named Middlewares, you need to specify which pages use a particular middleware. One way to do this is by modifying the page files that will utilize the middleware:

<script setup>
definePageMeta({
  middleware: "auth-admin"
});
</script>

It’s also important to note that even if you name middleware files using PascalCase or camelCase, file names are normalized to kebab-case.

Conclusion

I hope this article has helped you understand the key points of creating and using Middlewares in Nuxt.JS in a simple and quick way 🙋🏻‍♂️.

If you need more information about Middlewares in Nuxt.JS, you can check the official documentation.