Written by: Thiago Nunes Batista
Published on 03/02/2025
Last updated: 03/02/2025
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:
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.
"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.
Finally, after passing all these checks, you are free to enter the party hall.
In Nuxt.js, we have the following types of Middlewares:
/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"
});
}
});
/*
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>
/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
.
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.