Mastering Nuxt3 Middlewares; Comprehensive Examples and Best Practices

Mastering Nuxt3 Middlewares; Comprehensive Examples and Best PracticesNuxt middlewares are the backbone of modular application development in Nuxt3, offering robust 'big brother' capabilities. This comprehensive guide dives into advanced techniques to maximize middleware utility, enhancing your Nuxt3 applications.
Categoriesnuxtnuxt3vuejavaScriptnode.js
Date
2024-01-19
Hire me on Upwork!

What is Nuxt.js

The Nuxt.js framework is a great tool for creating Vue single-page applications (SPA) with server side rendering (SSR). It’s built on top of Vue, so you have access to all the tools you need to build powerful SPAs with little effort. Nuxt.js is a framework that gives us Developers the power to build high performance applications.

Nuxt provides a lot of features out of the box, such as routing, managing metadata, server-side rendering and more. Nuxt also provides a nice folder structure based on best practices to kick-start your next project.

What is a middleware (general)

I always like to understand the term before setting it into the framework's context.

I really like the definition from Microsoft Azure:

Middleware is software that lies between an operating system and the applications running on it. Essentially functioning as hidden translation layer, middleware enables communication and data management for distributed applications. It’s sometimes called plumbing, as it connects two applications together so data and databases can be easily passed between the “pipe.” Using middleware allows users to perform such requests as submitting forms on a web browser, or allowing the web server to return dynamic web pages based on a user’s profile.

So middleware is kind of a glue connecting two parts of software with each other.

What is a middleware in Nuxt.js

In nuxt.js a middleware is a function that is executed before a site is being rendered. This could be for example a function that checks if the user has the privileges to access this site, or not.

Within nuxt there are two types of middlewares. The route middleware executed in the vue part of your application.

The normal middleware executed in the nitro part of the application.

The example above would be a route middleware, since it will intercept the built-in vue router.

All nuxt middlewares have to be placed inside the middlewares/ directory.

Nuxt3 router middleware

The router middlewares are inside the vue part of the application.

There are three types of route middlewares in nuxt 3:

  1. Inline middleware

    Directly defined in the page.

  2. Named middleware

    Defined inside the middlewares directory. Can be used before navigating to a page when referenced in the page.

    We will build the referenced middleware in the next chapter.

    <script setup>
    definePageMeta({
      middleware: ["isAdministrator"]
      // or middleware: 'isAdministrator'
    })
    </script>
  3. Global middleware

    Also defined inside the middlewares directory. Will be executed before routing to any page.

Nuxt router middleware example

The most popular use case is the authentication guard, as already mentioned above.

I also use this one in my projects. But for security reasons, I will use a trivial example to describe.

// middlewares/isAdministrator
export default defineNuxtRouteMiddleware((to, from) =>
  // isAdmin() is an example method verifying if an user is authenticated
  if (isAdmin() === false) {
		logout();
    return navigateTo('/login')
  }
})

The above middleware checks if the currently authenticated user has admin privileges or not.

Each middleware has two parameters, to and from.

To is where we want to go.

From is where we come from.

If the user has no Administrator privileges, the user will be logged out, and we will redirect him to the login Page to login again. Not the best UX, but when a user is evil, we will be to 😈.

If the user has the rights, we do nothing, which implicitly means we redirect to the wished page.

This is also the main difference and a big gotcha to the standard vue-router implementation.

With older versions of vue-router you had a third parameter called next() which navigated to the wished path, but it never existed in nuxt middlewares.

The next parameter has also been removed from vue-router and is now only optional there.

Nuxt3 server middleware

Same name, different purpose.

The server middleware in nuxt 3 sits on the nitro side of your app.

You can imagine this middleware similar to an axios interceptor.

It will take any request your nuxt app makes to its own before any other route.

From there you could log, check headers or add additional data or prepare responses.

You can also build some custom error handling inside it.

They can do very much, but server middlewares can't have a return value!

Let's give a simple example to better understand it:

Nuxt server middleware example

We will intercept any request and log what we get before proceeding.

To do so, create a server folder, and a middleware folder inside it.

Create a new file called logger.ts and paste the following code into it:

export default defineEventHandler((event) => {
  console.log('New request: ' + event.node.req.url)
})

This will produce the following output in your console.

https://d2n94a8z4tjrso.cloudfront.net/nuxt/serverMWconsoleOutput.png

Note that we are on the server side, so this output is not visible in the browsers console.

Nuxt 3 server middleware use cases

To give you a few Ideas on why you might want to use this.

  • Match route parameters like [article]

    export default defineEventHandler((event) => 
    `You want to read, ${event.context.params.name}!`)
  • Access request cookies
  • Log requests
  • warm up an API

    • You may have an Azure free plan API which goes to sleep when there are no requests. So the first one would normal lead to a timeout. You can make one initial request when your app is loaded for the first time to wake the API up.
  • Catch all route
  • Log query parameters

many more...

Conclusion

You have two types of midlewares in nuxt3 and both are super useful once you understood them.

They really glue your application parts together.

Thank you for reading,

Alex

References

Nuxt.js middlewares Documentation

Nuxt.js server documentation

Axios Interceptors

Microsoft Azure middleware definition

RedHat Midleware definition

Vue Router documentation

Recommended Products for you
recommended for you